Java 如何将字节数组转换为 PrivateKey 或 PublicKey 类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19353748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:24:15  来源:igfitidea点击:

How to convert Byte array to PrivateKey or PublicKey type?

javacryptographyprivate-keypublic-keyjce

提问by sufala

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 解码此字符串时将获得一个字节数组。如何将此字节数组转换为公钥或私钥类型?

回答by nsayer

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));