Is Java security module KeyGenerator thread safe? If not then how to fix it?

本小妞迷上赌 提交于 2019-12-23 16:41:38

问题


I have a concurrent encryption/decryption program in which multiple AES128 keys are randomly generated concurrently by invoking the following code (written in scala, the Java version should be fairly similar):

  private def AESKeyGen: KeyGenerator = {
    val keyGen = KeyGenerator.getInstance("AES")
    keyGen.init(128)
    keyGen
  }

  def generateKey: SecretKey = this.synchronized {
    AESKeyGen.generateKey()
  }

each key is use to encrypt a fixed byte array, then decrypt it by using 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 have gradually higher chance of encountering 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)
...

Looks like at least one of the cryptocurrency component is not thread safe, despite I have marked most of them as synchronized as possible. How to fix this problem? (Or which library should I switch to to avoid it?)


回答1:


After some test I found that sun.misc.BASE64Encoder is not thread safe, all problem solved after changing its instance from a singleton to dynamic creation.



来源:https://stackoverflow.com/questions/30688609/is-java-security-module-keygenerator-thread-safe-if-not-then-how-to-fix-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!