How to convert Byte array to PrivateKey or PublicKey type?(如何将 Byte 数组转换为 PrivateKey 或 PublicKey 类型?)
问题描述
我正在使用 RSA 算法生成公钥和私钥
I am using RSA algorithm to generate public and private key
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
final KeyPair key = keyGen.generateKeyPair();
final PrivateKey privateKey=key.getPrivate();
final PublicKey publickey=key.getPublic();
之后,这些密钥使用 Base64 编码器进行编码并将其保存到数据库中.
after that these keys are encoded using Base64 encoder and save it into database.
如何在java中将此编码的字符串转换为私钥和公钥类型是解密文件.使用 Base64Decoder 解码此字符串时,将得到一个字节数组.如何将此字节数组转换为公钥或私钥类型?
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?
推荐答案
如果你有一个 byte[] 表示 key 上 getEncoded() 的输出,你可以使用 KeyFactory 将它转回一个 PublicKey 对象或 PrivateKey对象.
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[] 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));
这篇关于如何将 Byte 数组转换为 PrivateKey 或 PublicKey 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 Byte 数组转换为 PrivateKey 或 PublicKey 类型


基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01