Getting RSA public key from PKCS1 key

Fawzinov :

I get my public key in the below format and I need to use java to encrypt some data using this key

-----BEGIN RSA PUBLIC KEY----- MIGJAoGBAKDZp/3e4w1nJA/ImDMgaGowWfTnhlFkrvS86LBc6wh1/zBRt51/2F/o/ZzaA5mZ nx5YMlhDOf3vHyzyO4KzYlG8md3RQU7eKQQDxgRfW1v0f7WVQoC2Dxbupyz0JVV4jQStYUYW ifGsh76wI3rkzlq3F2Ea/+jqMxX/AZOO30tBAgMBAAE= -----END RSA PUBLIC KEY-----

michalk :

You can use BouncyCastle library to achieve this. Your key is in PEM fromat. To read it you can use PEMParser :

private static PublicKey readPublicKey(String path) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {
    PEMParser pemParser = new PEMParser(new FileReader(path));
    Object object = pemParser.readObject();
    SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo) object;

    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(subjectPublicKeyInfo);

    RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
    KeyFactory kf = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
    return kf.generatePublic(rsaSpec);
}

And then to encrypt with this key :

PublicKey publicKey = readPublicKey("src/main/resources/key.pem");

String dataToEncrypt = "myMessage";
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encrypted = cipher.doFinal(dataToEncrypt.getBytes(StandardCharsets.UTF_8));

Tested with versions : bcpkix-jdk15on and bcprov-jdk15on.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326199&siteId=1