I have a parallel encryption / decryption program in which several AES128 keys are randomly generated, calling the following code (written in scala, the Java version should be pretty similar):
private def AESKeyGen: KeyGenerator = {
val keyGen = KeyGenerator.getInstance("AES")
keyGen.init(128)
keyGen
}
def generateKey: SecretKey = this.synchronized {
AESKeyGen.generateKey()
}
each key is used to encrypt a fixed byte array, and then decrypts it using the AESEncrypt and AESDecrypt functions:
def ivParameterSpec = this.synchronized{
import com.schedule1.datapassport.view._
new IvParameterSpec("DataPassports===")
}
private def getCipher = this.synchronized {
Cipher.getInstance("AES/CBC/PKCS5Padding")
}
private def nextCipher(aesKey: Key): Cipher = this.synchronized{
val cipher = getCipher
cipher.init(Cipher.ENCRYPT_MODE, aesKey, ivParameterSpec)
cipher
}
private def nextDecipher(aesKey: Key): Cipher = this.synchronized{
val cipher = getCipher
cipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec)
cipher
}
def nullBytes = Array.fill[Byte](16)(0)
def aesEncrypt(bytes: Array[Byte], key: Key): Array[Byte] = this.synchronized{
val effectiveBytes = if (bytes == null) nullBytes
else bytes
nextCipher(key).doFinal(effectiveBytes)
}
def aesDecrypt(cipher: Array[Byte], key: Key): Array[Byte] = this.synchronized{
val effectiveBytes = Utils.retry(3){
nextDecipher(key).doFinal(cipher)
}
if (effectiveBytes.toList == nullBytes.toList) null
else effectiveBytes
}
The program runs smoothly on 1 core / thread, but when I increase concurrency gradually to 8. I gradually get more chances to meet the following error:
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
...
, , , . ? ( , ?)