Java安全模块KeyGenerator线程安全吗?如果没有,那么如何修复它?

时间:2015-06-06 23:33:48

标签: java scala cryptography aes key-generator

我有一个并发的加密/解密程序,其中多个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)
...

看起来至少有一个加密货币组件不是线程安全的,尽管我已将其中大部分标记为尽可能同步。如何解决这个问题? (或者我应该切换到哪个库以避免它?)

1 个答案:

答案 0 :(得分:1)

经过一些测试后,我发现sun.misc.BASE64Encoder不是线程安全的,所有问题都是在将其实例从单例更改为动态创建后解决的。