【问题标题】:convert RSA Publickey to base64 and vice versa将 RSA Publickey 转换为 base64,反之亦然
【发布时间】:2017-05-22 11:07:00
【问题描述】:

我有一个从这个函数生成的 publicKey/privateKey 对:

public static void generateKey() {
        try {
            final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
            keyGen.initialize(2048);
            final KeyPair key = keyGen.generateKeyPair();

            File privateKeyFile = new File(PRIVATE_KEY_FILE);
            File publicKeyFile = new File(PUBLIC_KEY_FILE);

            // Create files to store public and private key
            if (privateKeyFile.getParentFile() != null) {
                privateKeyFile.getParentFile().mkdirs();
            }
            privateKeyFile.createNewFile();

            if (publicKeyFile.getParentFile() != null) {
                publicKeyFile.getParentFile().mkdirs();
            }
            publicKeyFile.createNewFile();

            // Saving the Public key in a file
            ObjectOutputStream publicKeyOS = new ObjectOutputStream(
                    new FileOutputStream(publicKeyFile));
            publicKeyOS.writeObject(key.getPublic());
            publicKeyOS.close();

            // Saving the Private key in a file
            ObjectOutputStream privateKeyOS = new ObjectOutputStream(
                    new FileOutputStream(privateKeyFile));
            privateKeyOS.writeObject(key.getPrivate());
            privateKeyOS.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

现在我想在写入时将 publicKey 转换为 base64 并使用该 base64 解码来获取 publicKey ,该怎么做?

【问题讨论】:

  • 哈,由于电子寿司的编辑,我以为我在 Crypto 上:P

标签: java cryptography rsa


【解决方案1】:

通常,如果您想以 base 64 存储文件,您可以简单地对字节数组进行编码。您甚至可以在 ObjectOutputStreamFileOutputStream 之间放置一个 Base64 流(Java 8 中的 Base64 类提供了帮助)。

但是,公钥和私钥具有默认编码,可以使用它们的getEncoded 方法访问:

PublicKey publicKey = key.getPublic();
byte[] encodedPublicKey = publicKey.getEncoded();
String b64PublicKey = Base64.getEncoder().encodeToString(encodedPublicKey);

try (OutputStreamWriter publicKeyWriter =
        new OutputStreamWriter(
                new FileOutputStream(publicKeyFile),
                StandardCharsets.US_ASCII.newEncoder())) {
    publicKeyWriter.write(b64PublicKey);
}

这会以SubjectPublicKeyInfo 格式保存公钥,这种格式可以被多种类型的软件和加密库读写。

例如,您可以paste it in an online ASN.1 decoder(在线解码器本身会将其转换为十六进制,但它也会解析基数 64)。字节的格式是所谓的 ASN.1 / DER(这是一种通用格式,就像您可以在 XML 中编码多种类型的文件一样)。


如果您希望密钥采用 OpenSSL 兼容格式(带有“PUBLIC KEY”页眉和页脚),您可以使用 Bouncy Castle 等库(例如 org.bouncycastle.openssl.jcajce.JcaPEMWriter)。

【讨论】:

  • 我后来知道了 abt getencoded 方法,虽然我使用文件写入器从 base64 字符串写入文件,但这种方法效果很好;)
  • 我喜欢明确指定字符集。对于 base64,这通常不是问题,除非默认为 UTF-16。否则相同。
  • Base64.getEncoder().encodeToString(encodedPublicKey); 就是我所需要的……这对于更熟悉这些文件格式的人来说可能是显而易见的。谢谢!
  • @scottyseus 如果您已经知道答案,一切都是显而易见的 :) 如果您知道答案,诀窍就是找到解决方案。很高兴我能帮你找到它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 2011-10-25
  • 2010-12-03
  • 2011-10-08
  • 2013-03-15
  • 2019-09-19
相关资源
最近更新 更多