Regular expression for base 58 private key?
Solution 1
var regex = /^[5KL][1-9A-HJ-NP-Za-km-z]{50,51}$/
In javascript.
All valid WIF private keys will match this, and the only extra stuff this will match is "WIF private key"-ish strings with invalid checksums.
Shortest possible WIF key (all 00 bytes, missing the compressed 01 byte) 51 length 5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAbuatmU
Longest possible WIF key (all ff bytes with the extra 01 compression byte) 52 length L5oLkpV3aqBjhki6LmvChTCq73v9gyymzzMpBbhDLjDpKCuAXpsi
Solution 2
^5[HJK][0-9A-Za-z&&[^0OIl]]{49}
Solution 3
/^5[HJK][1-9A-Za-z][^OIl]{49}/
From https://en.bitcoin.it/wiki/Base58Check_encoding:
Such encodings will always yield a 51-character string that starts with '5', or more specifically, either '5H', '5J', or '5K'.
Solution 4
In python:
import re
re.search("^5[HJK][1-9A-Za-z][^OIl]{48}$", wif)

Comments
-
cilphex over 1 year
I'm looking for a regex that will validate a base 58 bitcoin private key. I found this one for public addresses:
/^[13n][1-9A-Za-z][^OIl]{20,40}/
But I don't know what the requirements are for a private key.
-
sebastian serrano over 9 yearsThe correct expression is /^5[HJK][1-9A-Za-z][^OIl]{48}/
-
drewbug almost 9 yearsThis doesn't disallow
O
,I
, andl
for the third character, and allows underscores and non-word characters for the final 48 characters.5JO????????????????????????????????????????????????
, for example, passes just fine. -
drewbug almost 9 yearsThis doesn't disallow
O
,I
, andl
for the third character, allows underscores and non-word characters for the final 49, and requires 52 characters instead of 51.5JO?????????????????????????????????????????????????
for example, passes just fine, even though it contains invalid characters and is too long, and5Jooooooooooooooooooooooooooooooooooooooooooooooooo
, despite being valid, fails. -
dmmd over 5 yearsCompletely off!
-
alpenmilch411 over 4 yearsIs this still valid?
-
user3074620 over 4 years@alpenmilch411 for Bitcoin WIF keys, yes. For anything besides WIF keys for BTC. No guarantees. However, that being said. WIF keys are no longer used widely, and most wallets use BIP39 phrases to store private keys.