public class ECKey extends Object implements EncryptableItem, Serializable
Represents an elliptic curve public and (optionally) private key, usable for digital signatures but not encryption. Creating a new ECKey with the empty constructor will generate a new random keypair. Other static methods can be used when you already have the public or private parts. If you create a key with only the public part, you can check signatures but not create them.
ECKey also provides access to Bitcoin Core compatible text message signing, as accessible via the UI or JSON-RPC. This is slightly different to signing raw bytes - if you want to sign your own data and it won't be exposed as text to people, you don't want to use this. If in doubt, ask on the mailing list.
The ECDSA algorithm supports key recovery in which a signature plus a couple of discriminator bits can be reversed to find the public key used to calculate it. This can be convenient when you have a message and a signature and want to find out who signed it, rather than requiring the user to provide the expected identity.
This class supports a variety of serialization forms. The methods that accept/return byte arrays serialize private keys as raw byte arrays and public keys using the SEC standard byte encoding for public keys. Signatures are encoded using ASN.1/DER inside the Bitcoin protocol.
A key can be compressed or uncompressed. This refers to whether the public key is represented when encoded into bytes as an (x, y) coordinate on the elliptic curve, or whether it's represented as just an X co-ordinate and an extra byte that carries a sign bit. With the latter form the Y coordinate can be calculated dynamically, however, because the binary serialization is different the address of a key changes if its compression status is changed. If you deviate from the defaults it's important to understand this: money sent to a compressed version of the key will have a different address to the same key in uncompressed form. Whether a public key is compressed or not is recorded in the SEC binary serialisation format, and preserved in a flag in this class so round-tripping preserves state. Unless you're working with old software or doing unusual things, you can usually ignore the compressed/uncompressed distinction.
Modifier and Type | Class and Description |
---|---|
static class |
ECKey.ECDSASignature
Groups the two components that make up a signature, and provides a way to encode to DER form, which is
how ECDSA signatures are represented when embedded in other data structures in the Bitcoin protocol.
|
static class |
ECKey.KeyIsEncryptedException |
static class |
ECKey.MissingPrivateKeyException |
Modifier and Type | Field and Description |
---|---|
protected long |
creationTimeSeconds |
static org.spongycastle.crypto.params.ECDomainParameters |
CURVE
The parameters of the secp256k1 curve that Bitcoin uses.
|
static org.spongycastle.asn1.x9.X9ECParameters |
CURVE_PARAMS
The parameters of the secp256k1 curve that Bitcoin uses.
|
protected EncryptedData |
encryptedPrivateKey |
static boolean |
FAKE_SIGNATURES
If this global variable is set to true, sign() creates a dummy signature and verify() always returns true.
|
static BigInteger |
HALF_CURVE_ORDER
Equal to CURVE.getN().shiftRight(1), used for canonicalising the S value of a signature.
|
protected KeyCrypter |
keyCrypter |
protected BigInteger |
priv |
protected org.spongycastle.math.ec.ECPoint |
pub |
static Comparator<ECKey> |
PUBKEY_COMPARATOR
Compares pub key bytes using
UnsignedBytes.lexicographicalComparator() |
Modifier | Constructor and Description |
---|---|
|
ECKey()
Generates an entirely new keypair.
|
|
ECKey(BigInteger privKey,
byte[] pubKey,
boolean compressed)
Deprecated.
|
protected |
ECKey(BigInteger priv,
org.spongycastle.math.ec.ECPoint pub) |
|
ECKey(byte[] privKeyBytes,
byte[] pubKey)
Deprecated.
|
|
ECKey(EncryptedData encryptedPrivateKey,
byte[] pubKey,
KeyCrypter keyCrypter)
Deprecated.
|
|
ECKey(SecureRandom secureRandom)
Generates an entirely new keypair with the given
SecureRandom object. |
Modifier and Type | Method and Description |
---|---|
static org.spongycastle.math.ec.ECPoint |
compressPoint(org.spongycastle.math.ec.ECPoint uncompressed)
Utility for compressing an elliptic curve point.
|
ECKey |
decompress()
Returns a copy of this key, but with the public point represented in uncompressed form.
|
static org.spongycastle.math.ec.ECPoint |
decompressPoint(org.spongycastle.math.ec.ECPoint compressed)
Utility for decompressing an elliptic curve point.
|
ECKey |
decrypt(KeyCrypter keyCrypter,
org.spongycastle.crypto.params.KeyParameter aesKey)
Create a decrypted private key with the keyCrypter and AES key supplied.
|
ECKey |
decrypt(org.spongycastle.crypto.params.KeyParameter aesKey)
Create a decrypted private key with AES key.
|
protected ECKey.ECDSASignature |
doSign(Sha256Hash input,
BigInteger privateKeyForSigning) |
ECKey |
encrypt(KeyCrypter keyCrypter,
org.spongycastle.crypto.params.KeyParameter aesKey)
Create an encrypted private key with the keyCrypter and the AES key supplied.
|
static boolean |
encryptionIsReversible(ECKey originalKey,
ECKey encryptedKey,
KeyCrypter keyCrypter,
org.spongycastle.crypto.params.KeyParameter aesKey)
Check that it is possible to decrypt the key with the keyCrypter and that the original key is returned.
|
boolean |
equals(Object o) |
static ECKey |
fromASN1(byte[] asn1privkey)
Construct an ECKey from an ASN.1 encoded private key.
|
static ECKey |
fromEncrypted(EncryptedData encryptedPrivateKey,
KeyCrypter crypter,
byte[] pubKey)
Constructs a key that has an encrypted private component.
|
static ECKey |
fromPrivate(BigInteger privKey)
Creates an ECKey given the private key only.
|
static ECKey |
fromPrivate(BigInteger privKey,
boolean compressed)
Creates an ECKey given the private key only.
|
static ECKey |
fromPrivate(byte[] privKeyBytes)
Creates an ECKey given the private key only.
|
static ECKey |
fromPrivate(byte[] privKeyBytes,
boolean compressed)
Creates an ECKey given the private key only.
|
static ECKey |
fromPrivateAndPrecalculatedPublic(BigInteger priv,
org.spongycastle.math.ec.ECPoint pub)
Creates an ECKey that simply trusts the caller to ensure that point is really the result of multiplying the
generator point by the private key.
|
static ECKey |
fromPrivateAndPrecalculatedPublic(byte[] priv,
byte[] pub)
Creates an ECKey that simply trusts the caller to ensure that point is really the result of multiplying the
generator point by the private key.
|
static ECKey |
fromPublicOnly(byte[] pub)
Creates an ECKey that cannot be used for signing, only verifying signatures, from the given encoded point.
|
static ECKey |
fromPublicOnly(org.spongycastle.math.ec.ECPoint pub)
Creates an ECKey that cannot be used for signing, only verifying signatures, from the given point.
|
long |
getCreationTimeSeconds()
Returns the creation time of this key or zero if the key was deserialized from a version that did not store
that data.
|
EncryptedData |
getEncryptedData()
An alias for
getEncryptedPrivateKey() |
EncryptedData |
getEncryptedPrivateKey()
Returns the the encrypted private key bytes and initialisation vector for this ECKey, or null if the ECKey
is not encrypted.
|
Protos.Wallet.EncryptionType |
getEncryptionType()
Returns an enum constant describing what algorithm was used to encrypt the key or UNENCRYPTED.
|
KeyCrypter |
getKeyCrypter()
Returns the KeyCrypter that was used to encrypt to encrypt this ECKey.
|
DumpedPrivateKey |
getPrivateKeyEncoded(NetworkParameters params)
Exports the private key in the form used by the Satoshi client "dumpprivkey" and "importprivkey" commands.
|
BigInteger |
getPrivKey()
Gets the private key in the form of an integer field element.
|
byte[] |
getPrivKeyBytes()
Returns a 32 byte array containing the private key.
|
byte[] |
getPubKey()
Gets the raw public key value.
|
byte[] |
getPubKeyHash()
Gets the hash160 form of the public key (as seen in addresses).
|
org.spongycastle.math.ec.ECPoint |
getPubKeyPoint()
Gets the public key in the form of an elliptic curve point object from Bouncy Castle.
|
byte[] |
getSecretBytes()
A wrapper for
getPrivKeyBytes() that returns null if the private key bytes are missing or would have
to be derived (for the HD key case). |
int |
hashCode() |
boolean |
hasPrivKey()
Returns true if this key has unencrypted access to private key bytes.
|
boolean |
isCompressed()
Returns whether this key is using the compressed form or not.
|
boolean |
isEncrypted()
Indicates whether the private key is encrypted (true) or not (false).
|
static boolean |
isPubKeyCanonical(byte[] pubkey)
Returns true if the given pubkey is canonical, i.e.
|
boolean |
isPubKeyOnly()
Returns true if this key doesn't have unencrypted access to private key bytes.
|
ECKey |
maybeDecrypt(org.spongycastle.crypto.params.KeyParameter aesKey)
Creates decrypted private key if needed.
|
static byte[] |
publicKeyFromPrivate(BigInteger privKey,
boolean compressed)
Returns public key bytes from the given private key.
|
static ECKey |
recoverFromSignature(int recId,
ECKey.ECDSASignature sig,
Sha256Hash message,
boolean compressed)
Given the components of a signature and a selector value, recover and return the public key
that generated the signature according to the algorithm in SEC1v2 section 4.1.6.
|
void |
setCreationTimeSeconds(long newCreationTimeSeconds)
Sets the creation time of this key.
|
ECKey.ECDSASignature |
sign(Sha256Hash input)
Signs the given hash and returns the R and S components as BigIntegers.
|
ECKey.ECDSASignature |
sign(Sha256Hash input,
org.spongycastle.crypto.params.KeyParameter aesKey)
Signs the given hash and returns the R and S components as BigIntegers.
|
static ECKey |
signedMessageToKey(String message,
String signatureBase64)
Given an arbitrary piece of text and a Bitcoin-format message signature encoded in base64, returns an ECKey
containing the public key that was used to sign it.
|
String |
signMessage(String message)
Signs a text message using the standard Bitcoin messaging signing format and returns the signature as a base64
encoded string.
|
String |
signMessage(String message,
org.spongycastle.crypto.params.KeyParameter aesKey)
Signs a text message using the standard Bitcoin messaging signing format and returns the signature as a base64
encoded string.
|
Address |
toAddress(NetworkParameters params)
Returns the address that corresponds to the public part of this ECKey.
|
byte[] |
toASN1()
Output this ECKey as an ASN.1 encoded private key, as understood by OpenSSL or used by the Bitcoin reference
implementation in its wallet storage format.
|
String |
toString() |
String |
toStringWithPrivate()
Produce a string rendering of the ECKey INCLUDING the private key.
|
boolean |
verify(byte[] data,
byte[] signature)
Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key.
|
static boolean |
verify(byte[] data,
byte[] signature,
byte[] pub)
Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key.
|
static boolean |
verify(byte[] data,
ECKey.ECDSASignature signature,
byte[] pub)
Verifies the given ECDSA signature against the message bytes using the public key bytes.
|
boolean |
verify(Sha256Hash sigHash,
ECKey.ECDSASignature signature)
Verifies the given R/S pair (signature) against a hash using the public key.
|
void |
verifyMessage(String message,
String signatureBase64)
Convenience wrapper around
signedMessageToKey(String, String) . |
public static final Comparator<ECKey> PUBKEY_COMPARATOR
UnsignedBytes.lexicographicalComparator()
public static final org.spongycastle.asn1.x9.X9ECParameters CURVE_PARAMS
public static final org.spongycastle.crypto.params.ECDomainParameters CURVE
public static final BigInteger HALF_CURVE_ORDER
protected final BigInteger priv
protected final org.spongycastle.math.ec.ECPoint pub
protected long creationTimeSeconds
protected KeyCrypter keyCrypter
protected EncryptedData encryptedPrivateKey
public static boolean FAKE_SIGNATURES
public ECKey()
public ECKey(SecureRandom secureRandom)
SecureRandom
object. Point compression is used so the
resulting public key will be 33 bytes (32 for the co-ordinate and 1 byte to represent the y bit).protected ECKey(@Nullable BigInteger priv, org.spongycastle.math.ec.ECPoint pub)
@Deprecated public ECKey(@Nullable byte[] privKeyBytes, @Nullable byte[] pubKey)
@Deprecated public ECKey(EncryptedData encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter)
encryptedPrivateKey
- The private key, encrypted,pubKey
- The keys public keykeyCrypter
- The KeyCrypter that will be used, with an AES key, to encrypt and decrypt the private key@Deprecated public ECKey(@Nullable BigInteger privKey, @Nullable byte[] pubKey, boolean compressed)
compressed
- If set to true and pubKey is null, the derived public key will be in compressed form.public static org.spongycastle.math.ec.ECPoint compressPoint(org.spongycastle.math.ec.ECPoint uncompressed)
public static org.spongycastle.math.ec.ECPoint decompressPoint(org.spongycastle.math.ec.ECPoint compressed)
public static ECKey fromASN1(byte[] asn1privkey)
public static ECKey fromPrivate(BigInteger privKey)
public static ECKey fromPrivate(BigInteger privKey, boolean compressed)
public static ECKey fromPrivate(byte[] privKeyBytes)
public static ECKey fromPrivate(byte[] privKeyBytes, boolean compressed)
public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, org.spongycastle.math.ec.ECPoint pub)
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub)
public static ECKey fromPublicOnly(org.spongycastle.math.ec.ECPoint pub)
public static ECKey fromPublicOnly(byte[] pub)
public ECKey decompress()
public static ECKey fromEncrypted(EncryptedData encryptedPrivateKey, KeyCrypter crypter, byte[] pubKey)
public boolean isPubKeyOnly()
isEncrypted()
to tell the cases apart.public boolean hasPrivKey()
isPubKeyOnly()
.public byte[] toASN1()
ECKey.MissingPrivateKeyException
- if the private key is missing or encrypted.public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed)
public byte[] getPubKeyHash()
public byte[] getPubKey()
public org.spongycastle.math.ec.ECPoint getPubKeyPoint()
public BigInteger getPrivKey()
IllegalStateException
- if the private key bytes are not available.public boolean isCompressed()
public Address toAddress(NetworkParameters params)
public ECKey.ECDSASignature sign(Sha256Hash input) throws KeyCrypterException
toASN1()
instead. However sometimes the independent components can be useful, for instance, if you're going to do
further EC maths on them.KeyCrypterException
- if this ECKey doesn't have a private part.public ECKey.ECDSASignature sign(Sha256Hash input, @Nullable org.spongycastle.crypto.params.KeyParameter aesKey) throws KeyCrypterException
ECKey.ECDSASignature.encodeToDER()
instead. However sometimes the independent components can be useful, for instance, if you're doing to do further
EC maths on them.aesKey
- The AES key to use for decryption of the private key. If null then no decryption is required.KeyCrypterException
- if there's something wrong with aesKey.ECKey.MissingPrivateKeyException
- if this key cannot sign because it's pubkey only.protected ECKey.ECDSASignature doSign(Sha256Hash input, BigInteger privateKeyForSigning)
public static boolean verify(byte[] data, ECKey.ECDSASignature signature, byte[] pub)
Verifies the given ECDSA signature against the message bytes using the public key bytes.
When using native ECDSA verification, data must be 32 bytes, and no element may be larger than 520 bytes.
data
- Hash of the data to verify.signature
- ASN.1 encoded signature.pub
- The public key bytes to use.public static boolean verify(byte[] data, byte[] signature, byte[] pub)
data
- Hash of the data to verify.signature
- ASN.1 encoded signature.pub
- The public key bytes to use.public boolean verify(byte[] data, byte[] signature)
data
- Hash of the data to verify.signature
- ASN.1 encoded signature.public boolean verify(Sha256Hash sigHash, ECKey.ECDSASignature signature)
public static boolean isPubKeyCanonical(byte[] pubkey)
public String signMessage(String message) throws KeyCrypterException
IllegalStateException
- if this ECKey does not have the private part.KeyCrypterException
- if this ECKey is encrypted and no AESKey is provided or it does not decrypt the ECKey.public String signMessage(String message, @Nullable org.spongycastle.crypto.params.KeyParameter aesKey) throws KeyCrypterException
IllegalStateException
- if this ECKey does not have the private part.KeyCrypterException
- if this ECKey is encrypted and no AESKey is provided or it does not decrypt the ECKey.public static ECKey signedMessageToKey(String message, String signatureBase64) throws SignatureException
message
- Some piece of human readable text.signatureBase64
- The Bitcoin-format message signature in base64SignatureException
- If the public key could not be recovered or if there was a signature format error.public void verifyMessage(String message, String signatureBase64) throws SignatureException
signedMessageToKey(String, String)
. If the key derived from the
signature is not the same as this one, throws a SignatureException.SignatureException
@Nullable public static ECKey recoverFromSignature(int recId, ECKey.ECDSASignature sig, Sha256Hash message, boolean compressed)
Given the components of a signature and a selector value, recover and return the public key that generated the signature according to the algorithm in SEC1v2 section 4.1.6.
The recId is an index from 0 to 3 which indicates which of the 4 possible keys is the correct one. Because the key recovery operation yields multiple potential keys, the correct key must either be stored alongside the signature, or you must be willing to try each recId in turn until you find one that outputs the key you are expecting.
If this method returns null it means recovery was not possible and recId should be iterated.
Given the above two points, a correct usage of this method is inside a for loop from 0 to 3, and if the output is null OR a key that is not the one you expect, you try again with the next recId.
recId
- Which possible key to recover.sig
- the R and S components of the signature, wrapped.message
- Hash of the data that was signed.compressed
- Whether or not the original pubkey was compressed.public byte[] getPrivKeyBytes()
ECKey.MissingPrivateKeyException
- if the private key bytes are missing/encrypted.public DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params)
VersionedChecksummedBytes.toString()
method to get the string.params
- The network this key is intended for use on.DumpedPrivateKey
.IllegalStateException
- if the private key is not available.public long getCreationTimeSeconds()
getCreationTimeSeconds
in interface EncryptableItem
public void setCreationTimeSeconds(long newCreationTimeSeconds)
public ECKey encrypt(KeyCrypter keyCrypter, org.spongycastle.crypto.params.KeyParameter aesKey) throws KeyCrypterException
keyCrypter
- The keyCrypter that specifies exactly how the encrypted bytes are created.aesKey
- The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached as it is slow to create).KeyCrypterException
public ECKey decrypt(KeyCrypter keyCrypter, org.spongycastle.crypto.params.KeyParameter aesKey) throws KeyCrypterException
keyCrypter
- The keyCrypter that specifies exactly how the decrypted bytes are created.aesKey
- The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached).KeyCrypterException
public ECKey decrypt(org.spongycastle.crypto.params.KeyParameter aesKey) throws KeyCrypterException
aesKey
- The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached).KeyCrypterException
public ECKey maybeDecrypt(@Nullable org.spongycastle.crypto.params.KeyParameter aesKey) throws KeyCrypterException
KeyCrypterException
public static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, org.spongycastle.crypto.params.KeyParameter aesKey)
Check that it is possible to decrypt the key with the keyCrypter and that the original key is returned.
Because it is a critical failure if the private keys cannot be decrypted successfully (resulting of loss of all bitcoins controlled by the private key) you can use this method to check when you *encrypt* a wallet that it can definitely be decrypted successfully.
See Wallet.encrypt(KeyCrypter keyCrypter, KeyParameter aesKey)
for example usage.
public boolean isEncrypted()
isEncrypted
in interface EncryptableItem
@Nullable public Protos.Wallet.EncryptionType getEncryptionType()
EncryptableItem
getEncryptionType
in interface EncryptableItem
@Nullable public byte[] getSecretBytes()
getPrivKeyBytes()
that returns null if the private key bytes are missing or would have
to be derived (for the HD key case).getSecretBytes
in interface EncryptableItem
@Nullable public EncryptedData getEncryptedData()
getEncryptedPrivateKey()
getEncryptedData
in interface EncryptableItem
@Nullable public EncryptedData getEncryptedPrivateKey()
@Nullable public KeyCrypter getKeyCrypter()
public String toStringWithPrivate()
toString()
.Copyright © 2014. All rights reserved.