'Convert RSA Public Key to PEM Format
I want to convert -
RSA Public Key
modulus: 9699c3c4406464638d2b30dbed44ddee485b5f9a3d7491434049440d34eb1759376a8bac0e37cee5c18df69acfc60d7252634fd15c26ab2afa16ca831598381356209acea9cea9467acdbd2a9b6d8e7b38d1baa826b1fbce2c185ba324bd17c9fdd6558eb57a082ca8c37fccaa86d4f9ffdc4e5d4a4a7f8e5f5410f835f98c64776cfc3421f19db99f140590d871e5e53efce6be8b9daffa3ab876005a48d249378ecc766281e931921e2ef0105fb64fa26952f91ad1627fedbb429aba75d3788bf7c0324f9fc1b48a9f5490ee0ab42e9e4c88ea564943aa5d9f43f7421b7d28788496daf7426f2e193199d4a525b38f0f3f68ab3c37b09fba2cc21f38e7a769
public exponent: 10001
TO
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAh74GWHRE+YCdi539to51
xpXlJiBI0VvSLbnUwbdKi6UP3HuOPbhVVNNAqyCs/bVIcHdZIap+Pb70Ry04L17H
RsQTOPyl4Us5r7WlzHG4J6p8XU5bl8wS0SU848oABkOIa5D4q0ap0Ryx0SniWPGP
OvPN5qA+cSHwJFgT7Ba/MQB99nJm0iLhnw5QFbtFCb8rCPXHRNYeXwAxUp33oNqZ
IMIWb+DoyyQjwizemiSgQaAk2iEGf7L7N0drlBS9/L/DWvgOOLGNJrK3uZnewNuU
2gma21x60nmWvFBMn87ocGtA4CU6GRrWX0cOvEPL/qXYy/+yA2WpM3op3YW9Hg+i
HQIDAQAB
-----END PUBLIC KEY-----
Either using standard Java or BouncyCastle, any pointers would help.
Solution 1:[1]
That is easy, you can create an RSAPublicKeySpec using the shown valus in BigInteger format. Then create a public key from it, get the encoded byte array and encode it using base64. The only thing you have to to is to add the "BEGIN" and "END" block and correct the line breaks.
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.getEncoder().encode(data));
System.out.println(base64encoded);
Note the used Base64 encode is the one from BouncyCastle (org.bouncycastle.util.encoders.Base64). There are other that can do the job as well. AFAIR some of them already support the automatic line breaking.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | dropbear |