我正在尝试java.security.PublicKey从byte[]只是一个原始密钥的a中创建一个- 它不在 X.509 或 ASN.1 中。在其他语言中,人们使用 libsodium,它只是给他们一个原始字节 []。我还需要能够将 my 转换java.security.PublicKey为 abyte[]供他们使用。似乎java.security不遗余力地使其具有挑战性,而不是希望我依赖预编码的 X509 SubjectPublicKeyInfo。我在这里错过了一个简单的答案吗?
Libsodium与所有 NaCl 衍生物一样,使用Curve25519进行加密操作,即 X25519 用于 DH 密钥交换,Ed25519 用于签名。Java 从版本 11 开始支持 X25519 ,从版本 15 开始支持 Ed25519 。这两种功能均由 SunEC 提供商提供。
对于原始密钥的导入/导出,最容易使用一些BouncyCastle函数。以下代码为 X25519(Java 11 及更高版本)创建 X.509 格式的公共测试密钥,并从中导出原始 32 字节密钥。然后将原始密钥再次导入 X.509 密钥:
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import org.bouncycastle.asn1.edec.EdECObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.params.X25519PublicKeyParameters;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.util.encoders.Hex;
...
// Generate public test key in X.509 format
PublicKey publicKey = loadPublicKey("X25519");
byte[] publicKeyBytes = publicKey.getEncoded();
System.out.println(Base64.getEncoder().encodeToString(publicKeyBytes)); // X.509-key, check this in an ASN.1 Parser, e.g. https://lapo.it/asn1js/
// PublicKey to raw key
X25519PublicKeyParameters x25519PublicKeyParameters = (X25519PublicKeyParameters)PublicKeyFactory.createKey(publicKeyBytes);
byte[] rawKey = x25519PublicKeyParameters.getEncoded();
System.out.println(Hex.toHexString(rawKey)); // equals the raw 32 bytes key from the X.509 key
// Raw key to PublicKey
KeyFactory keyFactory = KeyFactory.getInstance("X25519");
SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519), rawKey);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(subjectPublicKeyInfo.getEncoded());
publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
publicKeyBytes = publicKey.getEncoded();
System.out.println(Base64.getEncoder().encodeToString(publicKeyBytes)); // equals the X.509 key from above
Run Code Online (Sandbox Code Playgroud)
X.509 测试密钥是用以下方法创建的:
private static PublicKey loadPublicKey(String algorithm) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
return keyPair.getPublic();
}
Run Code Online (Sandbox Code Playgroud)
和 Ed25519 的模拟(Java 15 及更高版本)。
X25519 和 Ed25519 也可以单独使用 BouncyCastle 中的类来实现,例如org.bouncycastle.math.ec.rfc7748.X25519(密钥协商)、org.bouncycastle.crypto.generators.X25519KeyPairGenerator(密钥生成)、org.bouncycastle.crypto.params.X25519PublicKeyParameters(密钥容器)和 Ed25519 的模拟类。
| 归档时间: |
|
| 查看次数: |
356 次 |
| 最近记录: |