如何将Byte数组转换为PrivateKey或PublicKey类型?

时间:2021-04-10 16:09:35

I am using RSA algorithm to generate public and private key

我使用RSA算法生成公钥和私钥

final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
final KeyPair key = keyGen.generateKeyPair();
final PrivateKey privateKey=key.getPrivate();
final PublicKey publickey=key.getPublic();

after that these keys are encoded using Base64 encoder and save it into database.

之后,使用Base64编码器对这些密钥进行编码,并将其保存到数据库中。

How to convert this encoded String to Private and Public Key Type in java is to decrypt file. when decoding this String using Base64Decoder will get a byte array. how to convert this Byte array to public or private key type?

如何将此编码的字符串转换为java中的私钥和公钥类型是解密文件。使用Base64Decoder解码此String时将获得一个字节数组。如何将此Byte数组转换为公钥或私钥类型?

1 个解决方案

#1


36  

If you have a byte[] representing the output of getEncoded() on a key, you can use KeyFactory to turn that back into a PublicKey object or a PrivateKey object.

如果你有一个byte []表示一个键上的getEncoded()输出,你可以使用KeyFactory将它转回一个PublicKey对象或一个PrivateKey对象。

byte[] privateKeyBytes;
byte[] publicKeyBytes;
KeyFactory kf = KeyFactory.getInstance("RSA"); // or "EC" or whatever
PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
PublicKey publicKey = kf.generatePublic(new X509EncodedKeySpec(publicKeyBytes));

#1


36  

If you have a byte[] representing the output of getEncoded() on a key, you can use KeyFactory to turn that back into a PublicKey object or a PrivateKey object.

如果你有一个byte []表示一个键上的getEncoded()输出,你可以使用KeyFactory将它转回一个PublicKey对象或一个PrivateKey对象。

byte[] privateKeyBytes;
byte[] publicKeyBytes;
KeyFactory kf = KeyFactory.getInstance("RSA"); // or "EC" or whatever
PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
PublicKey publicKey = kf.generatePublic(new X509EncodedKeySpec(publicKeyBytes));