@@ -15,8 +15,13 @@ Bitcoin.ECKey = (function () {
1515 // Prepend zero byte to prevent interpretation as negative integer
1616 this . priv = BigInteger . fromByteArrayUnsigned ( input ) ;
1717 } else if ( "string" == typeof input ) {
18- // Prepend zero byte to prevent interpretation as negative integer
19- this . priv = BigInteger . fromByteArrayUnsigned ( Crypto . util . base64ToBytes ( input ) ) ;
18+ if ( input . length == 51 && input [ 0 ] == '5' ) {
19+ // Base58 encoded private key
20+ this . priv = BigInteger . fromByteArrayUnsigned ( ECKey . decodeString ( input ) ) ;
21+ } else {
22+ // Prepend zero byte to prevent interpretation as negative integer
23+ this . priv = BigInteger . fromByteArrayUnsigned ( Crypto . util . base64ToBytes ( input ) ) ;
24+ }
2025 }
2126 } ;
2227
@@ -44,6 +49,14 @@ Bitcoin.ECKey = (function () {
4449 return addr ;
4550 } ;
4651
52+ ECKey . prototype . getExportedPrivateKey = function ( ) {
53+ var hash = this . priv . toByteArrayUnsigned ( ) ;
54+ hash . unshift ( 0x80 ) ;
55+ var checksum = Crypto . SHA256 ( Crypto . SHA256 ( hash , { asBytes : true } ) , { asBytes : true } ) ;
56+ var bytes = hash . concat ( checksum . slice ( 0 , 4 ) ) ;
57+ return Bitcoin . Base58 . encode ( bytes ) ;
58+ } ;
59+
4760 ECKey . prototype . setPub = function ( pub ) {
4861 this . pub = pub ;
4962 } ;
@@ -64,5 +77,31 @@ Bitcoin.ECKey = (function () {
6477 return ECDSA . verify ( hash , sig , this . getPub ( ) ) ;
6578 } ;
6679
80+ /**
81+ * Parse an exported private key contained in a string.
82+ */
83+ ECKey . decodeString = function ( string ) {
84+ var bytes = Bitcoin . Base58 . decode ( string ) ;
85+
86+ var hash = bytes . slice ( 0 , 33 ) ;
87+
88+ var checksum = Crypto . SHA256 ( Crypto . SHA256 ( hash , { asBytes : true } ) , { asBytes : true } ) ;
89+
90+ if ( checksum [ 0 ] != bytes [ 33 ] ||
91+ checksum [ 1 ] != bytes [ 34 ] ||
92+ checksum [ 2 ] != bytes [ 35 ] ||
93+ checksum [ 3 ] != bytes [ 36 ] ) {
94+ throw "Checksum validation failed!" ;
95+ }
96+
97+ var version = hash . shift ( ) ;
98+
99+ if ( version != 0x80 ) {
100+ throw "Version " + version + " not supported!" ;
101+ }
102+
103+ return hash ;
104+ } ;
105+
67106 return ECKey ;
68107} ) ( ) ;
0 commit comments