我有一个并发加密/解密程序,其中通过调用以下代码(用scala编写,Java版本应该相当相似)随机并发生成多个AES128密钥:
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)
...
看起来至少有一个加密货币组件不是线程安全的,尽管我已经将它们中的大多数标记为尽可能同步。如何解决这个问题?(或者我应该切换到哪个库来避免它?)
经过一些测试,我发现sun.misc。BASE64Encoder不是线程安全的,在将其实例从单例更改为动态创建后,所有问题都解决了。