jasypt-spring-boot
jasypt-spring-boot copied to clipboard
Asymmetric Encryption / 2k private key / javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes
Thanx for making great module!
"Asymmetric Encryption" is very good feature. Private key remains secret. Only Public key is needed for encryption! Excellent.
Problem description
There is one issue with "Asymmetric Encryption". In case Private key lenght is default (2048 bits) then the longest secret to be encrypted can be 245 bytes. More details here. Encrypting longer secrets raise exception:
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes
at java.base/com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:348)
at java.base/com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:405)
at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2202)
at com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.encrypt(AsymmetricCryptography.java:79)
at com.ulisesbocchio.jasyptspringboot.encryptor.SimpleAsymmetricByteEncryptor.encrypt(SimpleAsymmetricByteEncryptor.java:30)
at com.ulisesbocchio.jasyptspringboot.encryptor.ByteEncryptorStringEncryptorDelegate.encrypt(ByteEncryptorStringEncryptorDelegate.java:26)
...
Use case:
Some applications have public/private key pairs in their properties file to encrypt communication with other parties. Private key should be encrypted, of course.
1024 bit rsa private key length is 862 bytes. It is around 3 times longer than 2048 bit key supports.
openssl genpkey -algorithm rsa -pkeyopt rsa_keygen_bits:1024 2>/dev/null | grep -v " KEY" | paste -sd, | wc --bytes
862
Proposed solution:
To keep the "Asymmetric Encryption" benefits but remove the length limit for secret, what about adding the following approach: For each property:
- generate symmetric key
- encrypt secret using symmetric key
- encrypt symmetric key using public key
One option about how to store this information in properties file:
property1=ENC(symmetric_key1_encrypted_using_public_key,secret_encrypted_using_symmetric_key1)
property2=ENC(symmetric_key2_encrypted_using_public_key,secret_encrypted_using_symmetric_key2)
And decryption does the opposite: For each property:
- decrypt encrypted symmetric key using private key
- decrypt encrypted secret using symmetric key
Summary
"Asymmetric Encryption" benefits are still there: only Public key is needed for encryption. Additional benefit: secret length is not limited.