使用BouncyCastle从文件中读取椭圆曲线私钥

使用BouncyCastle从文件中读取椭圆曲线私钥

本文介绍了使用BouncyCastle从文件中读取椭圆曲线私钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

BouncyCastle加密API允许使用常规 java.security 包对象创建和验证数字签名,例如 java.security.PublicKey java.security.PrivateKey 及其容器 java.security.KeyPair

The BouncyCastle cryptography APIs allow for creating and verifying digital signatures using the regular java.security package objects, such as java.security.PublicKey, java.security.PrivateKey and their container java.security.KeyPair.

假设我使用OpenSSL创建一个.pem(或者,更简单的.der文件),其中包含我想在我的应用程序中使用的椭圆曲线私钥。例如,它看起来像这样:

Suppose I use OpenSSL to create a .pem (or, if easier, a .der file) containing 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-----

如何使用BouncyCastle API获取包含此私钥和相应公钥的 java.security.KeyPair

How do I use the BouncyCastle APIs to obtain a java.security.KeyPair containing both this private key and a corresponding public key?

请注意我想使用BouncyCastle 1.50中提供的API(在撰写本文时是最新的)并且没有弃用的API。遗憾的是,这不包括其他SO答案中使用的 PEMReader 类。此外,这个问题特定于椭圆曲线的格式;当比较RSA或DSA密钥文件时,它们包含其他参数。

Please note I want to use the APIs available in BouncyCastle 1.50 (which is current at the time of writing) and no deprecated APIs. This unfortunately excludes the PEMReader class used in other SO answers. Furthermore, this question is specific to the format of elliptic curves; they contain additional parameters when compared RSA or DSA key files.

推荐答案

在Java中,这将是几乎相同的代码。剥离保护字符串并解码Base64数据后,将其提供给此实用程序方法:

In Java this will be pretty much the same code. After striping guarding strings away and decoding Base64 data give 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;
}

这篇关于使用BouncyCastle从文件中读取椭圆曲线私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 21:31