I need to decrypt some information coming from an external service built with NodeJS. This service ask for a RSA (2048) public key in pem format in base64, in order to encrypt the information.
I am creating the key pair in Java:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
PublicKey pubkey = kp.getPublic();
PrivateKey privkey = kp.getPrivate();
String pemPublicString = "-----BEGIN PUBLIC KEY-----\n";
pemPublicString = pemPublicString+Base64.getEncoder().encodeToString(pubkey.getEncoded())+"\n";
pemPublicString = pemPublicString+"-----END PUBLIC KEY-----\n";
String pemPrivateString = "-----BEGIN RSA PRIVATE KEY-----\n";
pemPrivateString = pemPrivateString+Base64.getEncoder().encodeToString(privkey.getEncoded())+"\n";
pemPrivateString = pemPrivateString+"-----END RSA PRIVATE KEY-----\n";
//Send to node js service
String base64publickey = Base64.getEncoder().encodeToString(pemPublicString.getBytes());
//Store for decrypting
String base64privatekey = Base64.getEncoder().encodeToString(pemPrivateString.getBytes());
The external service is encrypting the information as follows and is returning the bytes:
crypto.publicEncrypt(
{
key: publicKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: "sha256",
},
dataToEncrypt
);
I am trying to decrypt the information in Java as follows:
public String decrypt(String payload, String privateKey){
byte [] ciphertext = payload.getBytes(StandardCharsets.UTF_8);
Cipher oaepFromInit = Cipher.getInstance("RSA/ECB/OAEPPadding");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-256", "MGF1", new
MGF1ParameterSpec("SHA-1"), PSource.PSpecified.DEFAULT);
oaepFromInit.init(Cipher.DECRYPT_MODE, getRSAPrivateKeyFrom(privateKey), oaepParams);
byte[] pt = oaepFromInit.doFinal(ciphertext);
return new String(pt, StandardCharsets.UTF_8);
}
private PrivateKey getRSAPrivateKeyFrom(String content) {
byte[] decodedBytes = Base64.getDecoder().decode(content);
String decodedString = new String(decodedBytes);
Security.addProvider(new BouncyCastleProvider());
PEMParser pemParser = new PEMParser(new StringReader(decodedString));
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
Object object = pemParser.readObject();
PrivateKey k = converter.getPrivateKey((PrivateKeyInfo) object);
return k;
}
Now I am getting a BadPadding Exception, any idea of what could be the problem? Thanks in advance.