I try to encrypt/decrypt messages using a EC key. I created the key ussing openssl:
openssl ecparam -name prime256v1 -genkey -noout -out secp256r1-key.pem
openssl ec -in secp256r1-key.pem -pubout -out secp256r1-pub.pem
openssl req -new -key secp256r1-key.pem -x509 -nodes -days 99999 -out secp256r1-cert.pem
Created a java spring boot app using bouncy castle library for encryption:
public String encrypt_1(final String msg, PublicKey publicKey) throws Exception {
final IESCipher c1 = new org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.ECIES();
final Cipher cipher;
cipher = Cipher.getInstance("ECIES");
final byte[] msgBytes = msg.getBytes("UTF-8");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
final byte[] encryptedBytes = cipher.doFinal(msgBytes);
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public String decrypt_1(final String msgEncrypted, PrivateKey privateKey) throws Exception {
final Cipher cipher = Cipher.getInstance("ECIES");
final byte[] msgBytes = Base64.getDecoder().decode(msgEncrypted);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
final byte[] decryptedJwtBytes = cipher.doFinal(msgBytes);
return new String(decryptedJwtBytes, StandardCharsets.US_ASCII);
}
This works as I have output. However when I see other people implementing ECIES in java they use IESParameterSpec and IEKeySpec with as input both public and private key of both own and foreign key (as it is asymetric). An example can be found here: https://gist.github.com/amrishodiq/9821413 or on stackOverflow: ECC algorithm key mismatch
They do something like:
...
IESParameterSpec param = new IESParameterSpec(d, e, 256);
// decrypt the text using the private key
bcipher.init(Cipher.DECRYPT_MODE, new IEKeySpec(tpPrivateKey, ownPublicKey), param);
final byte[] decryptedBytes = bcipher.doFinal(cipherTextBytes);
...
I can't get that code to work, but I want to know if this is more secure and why both keys are used at the same time during encryption/decryption.