I have a java program which RSA encrypts data with a private key:
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
PrivateKey privateKey = null;
PublicKey publicKey = null;
// Load certificate from keystore
try {
FileInputStream keystoreFileInputStream = new FileInputStream("keystore.jks");
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(keystoreFileInputStream, "passphrase".toCharArray());
try {
privateKey = (PrivateKey) keystore.getKey("idm_key", "passphrase".toCharArray());
} catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO broad exception block
e.printStackTrace();
}
// Make the encrypted data.
byte[] toEncrypt = "Data to encrypt".getBytes();
byte[] encryptedData = null;
// Perform private key encryption
try {
// Encrypt the data
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
encryptedData = cipher.doFinal(toEncrypt);
} catch (Exception e) {
// TODO broad exception block
e.printStackTrace();
}
I have the need to do the same thing using openssl. Here is the code I tried:
uint8_t *encryptedBytes = NULL;
const char* data = "Data to enrypt";
char *private_key_file_name = "privatekey.pem"
FILE *fp = fopen(private_key_file_name, "r");
RSA *rsa = RSA_new();
PEM_read_RSAPrivateKey(fp, &rsa, 0, "passphase");
size_t encryptedBytesSize = RSA_size(rsa);
encryptedBytes = malloc(encryptedBytesSize * sizeof(uint8_t));
memset((void *)encryptedBytes, 0x0, encryptedBytesSize);
fclose(fp);
int result = RSA_private_encrypt(strlen(data), data, encryptedBytes, rsa,RSA_PKCS1_PADDING);
This is not producing the same output as the Java implementation. Instead, it produces the output that is gotten by signing the data in Java, i.e.,
Signature rsa = Signature.getInstance("RSA");
rsa.initSign(privateKey);
rsa.update(toEncrypt);
byte [] signed = rsa.sign();
Though this is what I would expect given the documentation for RSA_private_encrypt, it's not what I need. Is there a way to replicate what the java code is doing with openssl?