我有一个并发加密/解密程序,其中通过调用以下代码同时随机生成多个 AES128 密钥(用 scala 编写,Java 版本应该非常相似):
private def AESKeyGen: KeyGenerator = {
val keyGen = KeyGenerator.getInstance("AES")
keyGen.init(128)
keyGen
}
def generateKey: SecretKey = this.synchronized {
AESKeyGen.generateKey()
}
每个密钥用于加密一个固定字节数组,然后使用 AESEncrypt 和 AESDecrypt 函数对其进行解密:
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
}
该程序在 1 个核心/线程上运行顺利,但是当我逐渐将并发增加到 8 时。我遇到以下错误的机会逐渐增加:
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)
...
看起来至少有一个加密货币组件不是线程安全的,尽管我已将它们中的大多数标记为尽可能同步。如何解决这个问题?(或者我应该切换到哪个库以避免它?)