I am trying to create a encryption/decryption functionality similar to a java code given below.
private static byte[] encryptPKCS7(byte[] plainData, PublicKey pubKey) throws
Exception {
CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
JcaAlgorithmParametersConverter paramsConverter = new
JcaAlgorithmParametersConverter();
OAEPParameterSpec oaepParamSpec = new OAEPParameterSpec("SHA-256",
"MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
AlgorithmIdentifier algoId =
paramsConverter.getAlgorithmIdentifier(PKCSObjectIdentifiers.id_RSAES_OAEP,
oaepParamSpec);
JceKeyTransRecipientInfoGenerator recipInfo = new
JceKeyTransRecipientInfoGenerator(KEY_IDENTIFIER.getBytes(), algoId, pubKey)
.setProvider(bcProvider);
gen.addRecipientInfoGenerator(recipInfo);
CMSProcessableByteArray data = new CMSProcessableByteArray(plainData);
BcCMSContentEncryptorBuilder builder = new
BcCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC);
CMSEnvelopedData enveloped = gen.generate(data, builder.build());
return enveloped.getEncoded();
}
The javascript code I came up with is,
function decryptText(encryptedText) {
const privateKey = fs.readFileSync('PrivateKey.pem', 'utf8');
const encryptedBuffer = Buffer.from(encryptedText, 'base64');
const decryptedBuffer = crypto.privateDecrypt({
key: privateKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: 'sha256'
}, encryptedBuffer);
return decryptedBuffer.toString('utf8');
}
using forge
function encryptPKCS7(plainData, pubKey) {
const p7 = forge.pkcs7.createEnvelopedData();
p7.addRecipient(pubKey);
p7.content = forge.util.createBuffer(plainData, 'utf8');
p7.encrypt();
return forge.util.encode64(p7.toAsn1().getBytes());
}
The java and javascript encryption is not matching.