使用Bouncy Castle解密CMSEncryptedData会抛出BadPaddingException:pad块损坏

时间:2016-07-25 10:14:48

标签: scala encryption bouncycastle jce

我使用Bouncy Castle有CMS加密数据,我想解密它的内容。但是,我遇到了获取javax.crypto.BadPaddingException: pad block corrupted的问题。我相信,秘密密钥

有问题
val provider = new BouncyCastleProvider()

// output encoder
val gen = new CMSEncryptedDataGenerator()
val encoder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME).build()

// secrete key
val spec = new DESedeKeySpec(encoder.getKey.getRepresentation.asInstanceOf[Array[Byte]])
val keyFactory = SecretKeyFactory.getInstance("DESEDE", provider)
val secretKey = keyFactory.generateSecret(spec)

// Encryption
val cmsEncryptedData: CMSEncryptedData = gen.generate(new CMSProcessableByteArray("Hello World!".getBytes()), encoder)

// Decryption
val decryptedContententBinary: Array[Byte] = {
  cmsEncryptedData.getContent(new InputDecryptorProvider {
    override def get(algorithm: AlgorithmIdentifier): InputDecryptor = new InputDecryptor {

      override def getAlgorithmIdentifier: AlgorithmIdentifier = algorithm

      override def getInputStream(encIn: InputStream): InputStream = {
        val parameters = new JceAlgorithmIdentifierConverter().setProvider(provider).getAlgorithmParameters(algorithm)
        val cipher = Cipher.getInstance(parameters.getAlgorithm, provider)
        cipher.init(Cipher.DECRYPT_MODE, secretKey, parameters) // throws javax.crypto.BadPaddingException: pad block corrupted
        new CipherInputStream(encIn, cipher)
      }
    }
  })
}

1 个答案:

答案 0 :(得分:0)

我刚刚解决了我遇到的问题。这是工作代码:

// output encoder
val gen = new CMSEncryptedDataGenerator()
val random = new SecureRandom()
val encoder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME).setSecureRandom(random).build()


// secrete key
val key = new SecretKeySpec(encoder.getKey.getRepresentation.asInstanceOf[Array[Byte]], "DESede")

// Encryption
val cmsEncryptedData: CMSEncryptedData = gen.generate(new CMSProcessableByteArray("Hello World!".getBytes()), encoder)


// Decryption
val decryptedContententBinary: Array[Byte] = {
  cmsEncryptedData.getContent(new InputDecryptorProvider {
    override def get(algorithm: AlgorithmIdentifier): InputDecryptor = new InputDecryptor {

      override def getAlgorithmIdentifier: AlgorithmIdentifier = algorithm

      override def getInputStream(encIn: InputStream): InputStream = {

        val parameters = new JceAlgorithmIdentifierConverter().setProvider(provider).getAlgorithmParameters(encoder.getAlgorithmIdentifier)
        val cipher = Cipher.getInstance(algorithm.getAlgorithm.getId, provider)
        cipher.init(Cipher.DECRYPT_MODE, key, parameters)
        new CipherInputStream(encIn, cipher)
      }
    }
  })
}