java keygenerator,Java安全模块KeyGenerator线程安全吗?如果没有,那么如何解决呢?...

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?)

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值