Java安全模块KeyGenerator线程安全吗?如果不是那么如何修复它?

2024-01-08

我有一个并发加密/解密程序,其中通过调用以下代码(用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 不是线程安全的,将其实例从单例更改为动态创建后,所有问题都解决了。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java安全模块KeyGenerator线程安全吗?如果不是那么如何修复它? 的相关文章

随机推荐