Java – use bouncycastle to read the elliptic curve private key from the file

The bouncycastle encryption API allows the use of regular Java Security package objects create and validate digital signatures, such as Java security. PublicKey,java. security. Privatekey and its container Java security. KeyPair.

Suppose I create one using OpenSSL PEM (or, if simpler, a. Der file) that contains the elliptic curve private key I want to use in my application For example, it looks like this:

-----BEGIN EC PARAMETERS-----
BgUrgQQACg==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHQCAQEEIDzESrZFmTaOozu2NyiS8LMZGqkHfpSOoI/qA9Lw+d4NoAcGBSuBBAAK
oUQDQgAE7kIqoSQzC/UUXdFdQ9Xvu1Lri7pFfd7xDbQWhSqHaDtj+XY36Z1Cznun
GDxlA0AavdVDuoGXxNQPIed3FxPE3Q==
-----END EC PRIVATE KEY-----

How to use the bouncycastle API to obtain a Java. Net file containing this private key and the corresponding public key security. KeyPair?

Please note that I want to use the API provided in bouncy castle 1.50 (which is up-to-date at the time of writing) and there are no deprecated APIs Unfortunately, this does not include the pemreader class used in other so answers In addition, this problem is specific to the format of elliptic curve; When comparing RSA or DSA key files, they contain additional parameters

Solution

In Java, this will be almost the same code After stripping the protection string and decoding Base64 data, provide it to this utility method:

public static PrivateKey keyToValue(byte[] pkcs8key)
    throw GeneralSecurityException {

    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pkcs8key);
    KeyFactory factory = KeyFactory.getInstance("ECDSA");
    PrivateKey privateKey = factory.generatePrivate(spec);
    return privateKey;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>