将RSA公钥转换为PEM格式

时间:2013-12-17 13:28:31

标签: security bouncycastle

我想转换 -

RSA Public Key
            modulus: 9699c3c4406464638d2b30dbed44ddee485b5f9a3d7491434049440d34eb1759376a8bac0e37cee5c18df69acfc60d7252634fd15c26ab2afa16ca831598381356209acea9cea9467acdbd2a9b6d8e7b38d1baa826b1fbce2c185ba324bd17c9fdd6558eb57a082ca8c37fccaa86d4f9ffdc4e5d4a4a7f8e5f5410f835f98c64776cfc3421f19db99f140590d871e5e53efce6be8b9daffa3ab876005a48d249378ecc766281e931921e2ef0105fb64fa26952f91ad1627fedbb429aba75d3788bf7c0324f9fc1b48a9f5490ee0ab42e9e4c88ea564943aa5d9f43f7421b7d28788496daf7426f2e193199d4a525b38f0f3f68ab3c37b09fba2cc21f38e7a769
    public exponent: 10001

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAh74GWHRE+YCdi539to51
xpXlJiBI0VvSLbnUwbdKi6UP3HuOPbhVVNNAqyCs/bVIcHdZIap+Pb70Ry04L17H
RsQTOPyl4Us5r7WlzHG4J6p8XU5bl8wS0SU848oABkOIa5D4q0ap0Ryx0SniWPGP
OvPN5qA+cSHwJFgT7Ba/MQB99nJm0iLhnw5QFbtFCb8rCPXHRNYeXwAxUp33oNqZ
IMIWb+DoyyQjwizemiSgQaAk2iEGf7L7N0drlBS9/L/DWvgOOLGNJrK3uZnewNuU
2gma21x60nmWvFBMn87ocGtA4CU6GRrWX0cOvEPL/qXYy/+yA2WpM3op3YW9Hg+i
HQIDAQAB
-----END PUBLIC KEY-----

使用标准Java或BouncyCastle,任何指针都会有所帮助。

1 个答案:

答案 0 :(得分:14)

这很简单,您可以使用BigInteger格式显示的valus创建一个RSAPublicKeySpec。然后从中创建一个公钥,获取编码的字节数组并使用base64对其进行编码。你唯一要做的就是添加“BEGIN”和“END”块并纠正换行符。

KeyFactory f = KeyFactory.getInstance("RSA");
BigInteger modulus = new BigInteger(
        "9699c3c4406464638d2b30dbed44ddee485b5f9a3d7491434049440d34eb1759376a8bac"
                + "0e37cee5c18df69acfc60d7252634fd15c26ab2afa16ca831598381356209acea9cea9467acdbd2a9b6d8e7b38d1baa826b1fb"
                + "ce2c185ba324bd17c9fdd6558eb57a082ca8c37fccaa86d4f9ffdc4e5d4a4a7f8e5f5410f835f98c64776cfc3421f19db99f140"
                + "590d871e5e53efce6be8b9daffa3ab876005a48d249378ecc766281e931921e2ef0105fb64fa26952f91ad1627fedbb429aba75"
                + "d3788bf7c0324f9fc1b48a9f5490ee0ab42e9e4c88ea564943aa5d9f43f7421b7d28788496daf7426f2e193199d4a525b38f0f3f"
                + "68ab3c37b09fba2cc21f38e7a769", 16);
BigInteger exp = new BigInteger("10001", 16);
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exp);
PublicKey pub = f.generatePublic(spec);
byte[] data = pub.getEncoded();
String base64encoded = new String(Base64.encode(data));
System.out.println(base64encoded);

注意使用的Base64编码是BouncyCastle(org.bouncycastle.util.encoders.Base64)中的编码。还有其他可以完成这项工作的人。 AFAIR中的一些已经支持自动换行。