【问题标题】:How to convert Byte array to PrivateKey or PublicKey type?如何将 Byte 数组转换为 PrivateKey 或 PublicKey 类型?
【发布时间】:2013-10-21 15:15:23
【问题描述】:

我正在使用 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();

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

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

【问题讨论】:

    标签: java cryptography private-key public-key jce


    【解决方案1】:

    如果您有一个 byte[] 表示 key 上 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));
    

    【讨论】:

    • 我已经搜索了 2 天,以找到如何将 RSA 密钥转换为字符串并返回,这是唯一具有有效解决方案的帖子。谢谢 nsayer!
    • 你不能将对象名称指定为“public”或“private”。
    • 请注意,键上的 getEncoded() 不会告诉您什么是编码。 Key 接口有 getFormat(),它返回一个指示格式的字符串,但是你必须知道每种格式对应的类。似乎标准的 ServiceLoader 可以帮助解决这个问题?
    猜你喜欢
    • 2020-12-01
    • 2014-09-01
    • 2016-06-25
    • 2014-02-20
    • 2012-01-10
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多