类 ECKey


  • public class ECKey
    extends Object

    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.

    • 字段详细资料

      • AGE_COMPARATOR

        public static final Comparator<ECKey> AGE_COMPARATOR
        Sorts oldest keys first, newest last.
      • PUBKEY_COMPARATOR

        public static final Comparator<ECKey> PUBKEY_COMPARATOR
        Compares pub key bytes using UnsignedBytes.lexicographicalComparator()
      • CURVE

        public static final org.bouncycastle.crypto.params.ECDomainParameters CURVE
        The parameters of the secp256k1 curve that Bitcoin uses.
      • HALF_CURVE_ORDER

        public static final BigInteger HALF_CURVE_ORDER
        Equal to CURVE.getN().shiftRight(1), used for canonicalising the S value of a signature. If you aren't sure what this is about, you can ignore it.
      • creationTimeSeconds

        protected long creationTimeSeconds
      • encryptedPrivateKey

        protected EncryptedData encryptedPrivateKey
      • FAKE_SIGNATURES

        public static boolean FAKE_SIGNATURES
        If this global variable is set to true, sign() creates a dummy signature and verify() always returns true. This is intended to help accelerate unit tests that do a lot of signing/verifying, which in the debugger can be painfully slow.
    • 构造器详细资料

      • ECKey

        public ECKey()
        Generates an entirely new keypair. 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).
      • ECKey

        public ECKey​(SecureRandom secureRandom)
        Generates an entirely new keypair with the given 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).
    • 方法详细资料

      • fromASN1

        public static ECKey fromASN1​(byte[] asn1privkey)
        Construct an ECKey from an ASN.1 encoded private key. These are produced by OpenSSL and stored by Bitcoin Core in its wallet. Note that this is slow because it requires an EC point multiply.
      • fromPrivate

        public static ECKey fromPrivate​(BigInteger privKey)
        Creates an ECKey given the private key only. The public key is calculated from it (this is slow). The resulting public key is compressed.
      • fromPrivate

        public static ECKey fromPrivate​(byte[] privKeyBytes)
        Creates an ECKey given the private key only. The public key is calculated from it (this is slow). The resulting public key is compressed.
      • fromPrivateAndPrecalculatedPublic

        public static ECKey fromPrivateAndPrecalculatedPublic​(BigInteger priv,
                                                              org.bouncycastle.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. This is used to speed things up when you know you have the right values already. The compression state of pub will be preserved.
      • fromPrivateAndPrecalculatedPublic

        public 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. This is used to speed things up when you know you have the right values already. The compression state of the point will be preserved.
      • fromPublicOnly

        public static ECKey fromPublicOnly​(org.bouncycastle.math.ec.ECPoint pub)
        Creates an ECKey that cannot be used for signing, only verifying signatures, from the given point. The compression state of pub will be preserved.
      • fromEncrypted

        public static ECKey fromEncrypted​(EncryptedData encryptedPrivateKey,
                                          byte[] pubKey)
        根据EncryptedData和公钥生成ECKey
        参数:
        encryptedPrivateKey - 私钥封装类
        pubKey - 公钥
        返回:
        ECKey
      • fromPublicOnly

        public static ECKey fromPublicOnly​(byte[] pub)
        Creates an ECKey that cannot be used for signing, only verifying signatures, from the given encoded point. The compression state of pub will be preserved.
      • isPubKeyOnly

        public boolean isPubKeyOnly()
        Returns true if this key doesn't have unencrypted access to private key bytes. This may be because it was never given any private key bytes to begin with (a watching key), or because the key is encrypted. You can use
      • hasPrivKey

        public boolean hasPrivKey()
        Returns true if this key has unencrypted access to private key bytes. Does the opposite of isPubKeyOnly().
      • publicKeyFromPrivate

        public static byte[] publicKeyFromPrivate​(BigInteger privKey,
                                                  boolean compressed)
        Returns public key bytes from the given private key. To convert a byte array into a BigInteger, use new BigInteger(1, bytes);
      • publicPointFromPrivate

        public static org.bouncycastle.math.ec.ECPoint publicPointFromPrivate​(BigInteger privKey)
        Returns public key point from the given private key. To convert a byte array into a BigInteger, use new BigInteger(1, bytes);
      • getPubKeyHash

        public byte[] getPubKeyHash()
        Gets the hash160 form of the public key (as seen in addresses).
      • getPubKey

        public byte[] getPubKey()
        Gets the raw public key value. This appears in transaction scriptSigs. Note that this is not the same as the pubKeyHash/address.
      • getPubKeyPoint

        public org.bouncycastle.math.ec.ECPoint getPubKeyPoint()
        Gets the public key in the form of an elliptic curve point object from Bouncy Castle.
      • getPrivKey

        public BigInteger getPrivKey()
        Gets the private key in the form of an integer field element. The public key is derived by performing EC point addition this number of times (i.e. point multiplying).
        抛出:
        IllegalStateException - if the private key bytes are not available.
      • isCompressed

        public boolean isCompressed()
        Returns whether this key is using the compressed form or not. Compressed pubkeys are only 33 bytes, not 64.
      • isValidPrivteHex

        public static boolean isValidPrivteHex​(String privateHex)
        验证16进制私钥字符串是否正确
        返回:
        boolean 正确返回true,否则返回false
      • sign

        public byte[] sign​(byte[] hash)
        用私钥对数据进行签名
        参数:
        hash - 需签名数据
        返回:
        byte[] 签名
      • doSign

        protected byte[] doSign​(byte[] input,
                                BigInteger privateKeyForSigning)
        用私钥对数据进行签名
        参数:
        input - 需签名数据
        privateKeyForSigning - 私钥
        返回:
        byte[] 签名
      • verify

        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.
      • verify

        public static boolean verify​(byte[] data,
                                     byte[] signature,
                                     byte[] pub)
        Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key.
        参数:
        data - Hash of the data to verify.
        signature - ASN.1 encoded signature.
        pub - The public key bytes to use.
        抛出:
        Exception - if the signature is unparseable in some way.
      • sign

        public byte[] sign​(Sha256Hash hash)
        用私钥对数据进行签名
        参数:
        hash - 需签名数据
        返回:
        byte[] 签名
      • verify

        public boolean verify​(Sha256Hash sigHash,
                              ECKey.ECDSASignature signature)
        Verifies the given R/S pair (signature) against a hash using the public key.
      • verifyOrThrow

        public void verifyOrThrow​(byte[] hash,
                                  byte[] signature)
                           throws Exception,
                                  SignatureException
        Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key, and throws an exception if the signature doesn't match
        抛出:
        Exception - if the signature is unparseable in some way.
        SignatureException - if the signature does not match.
      • isPubKeyCanonical

        public static boolean isPubKeyCanonical​(byte[] pubkey)
        Returns true if the given pubkey is canonical, i.e. the correct length taking into account compression.
      • findRecoveryId

        public byte findRecoveryId​(Sha256Hash hash,
                                   ECKey.ECDSASignature sig)
        Returns the recovery ID, a byte with value between 0 and 3, inclusive, that specifies which of 4 possible curve points was used to sign a message. This value is also referred to as "v".
        抛出:
        RuntimeException - if no recovery ID can be found.
      • recoverFromSignature

        @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.
        返回:
        An ECKey containing only the public part, or null if recovery wasn't possible.
      • getPrivKeyBytes

        public byte[] getPrivKeyBytes()
        Returns a 32 byte array containing the private key.
      • getCreationTimeSeconds

        public 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.
      • setCreationTimeSeconds

        public void setCreationTimeSeconds​(long newCreationTimeSeconds)
        Sets the creation time of this key. Zero is a convention to mean "unavailable". This method can be useful when you have a raw key you are importing from somewhere else.
      • getSecretBytes

        @Nullable
        public 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).
      • getEncryptedPrivateKey

        @Nullable
        public EncryptedData getEncryptedPrivateKey()
        Returns the the encrypted private key bytes and initialisation vector for this ECKey, or null if the ECKey is not encrypted.
      • setEncryptedPrivateKey

        public void setEncryptedPrivateKey​(EncryptedData encryptedPrivateKey)
      • hashCode

        public int hashCode()
        覆盖:
        hashCode 在类中 Object
      • getPrivateKeyAsHex

        public String getPrivateKeyAsHex()
      • getPublicKeyAsHex

        public String getPublicKeyAsHex()
      • verify

        public boolean verify​(byte[] hash,
                              byte[] signature)
        Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key.
        参数:
        hash - Hash of the data to verify.
        signature - ASN.1 encoded signature.