Browse Source

Merge pull request #7 from phedny/master

Added support for the Base58-encoded private key format
hk-custom-address
Stefan Thomas 12 years ago
parent
commit
699bc2f45f
  1. 43
      src/eckey.js

43
src/eckey.js

@ -15,8 +15,13 @@ Bitcoin.ECKey = (function () {
// Prepend zero byte to prevent interpretation as negative integer // Prepend zero byte to prevent interpretation as negative integer
this.priv = BigInteger.fromByteArrayUnsigned(input); this.priv = BigInteger.fromByteArrayUnsigned(input);
} else if ("string" == typeof input) { } else if ("string" == typeof input) {
// Prepend zero byte to prevent interpretation as negative integer if (input.length == 51 && input[0] == '5') {
this.priv = BigInteger.fromByteArrayUnsigned(Crypto.util.base64ToBytes(input)); // Base58 encoded private key
this.priv = BigInteger.fromByteArrayUnsigned(ECKey.decodeString(input));
} else {
// Prepend zero byte to prevent interpretation as negative integer
this.priv = BigInteger.fromByteArrayUnsigned(Crypto.util.base64ToBytes(input));
}
} }
}; };
@ -44,6 +49,14 @@ Bitcoin.ECKey = (function () {
return addr; return addr;
}; };
ECKey.prototype.getExportedPrivateKey = function () {
var hash = this.priv.toByteArrayUnsigned();
hash.unshift(0x80);
var checksum = Crypto.SHA256(Crypto.SHA256(hash, {asBytes: true}), {asBytes: true});
var bytes = hash.concat(checksum.slice(0,4));
return Bitcoin.Base58.encode(bytes);
};
ECKey.prototype.setPub = function (pub) { ECKey.prototype.setPub = function (pub) {
this.pub = pub; this.pub = pub;
}; };
@ -64,5 +77,31 @@ Bitcoin.ECKey = (function () {
return ECDSA.verify(hash, sig, this.getPub()); return ECDSA.verify(hash, sig, this.getPub());
}; };
/**
* Parse an exported private key contained in a string.
*/
ECKey.decodeString = function (string) {
var bytes = Bitcoin.Base58.decode(string);
var hash = bytes.slice(0, 33);
var checksum = Crypto.SHA256(Crypto.SHA256(hash, {asBytes: true}), {asBytes: true});
if (checksum[0] != bytes[33] ||
checksum[1] != bytes[34] ||
checksum[2] != bytes[35] ||
checksum[3] != bytes[36]) {
throw "Checksum validation failed!";
}
var version = hash.shift();
if (version != 0x80) {
throw "Version "+version+" not supported!";
}
return hash;
};
return ECKey; return ECKey;
})(); })();

Loading…
Cancel
Save