Scala RSA解密BadPaddingException:解密错误

时间:2018-07-12 07:05:18

标签: java scala encryption openssl rsa

我无法使用私钥解码数据。我正在尝试解码使用openssl的功能

$> openssl rsautl -decrypt -inkey $priv_key -in $key -out $otkey

我能够解码第一个示例,但是第二个示例输入无法解码。

import java.io.{File, FileReader}
import java.security.{Key, KeyPair, Security}
import java.util.Base64

import javax.crypto.Cipher

import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.bouncycastle.openssl.PEMReader

object ExampleRsa extends App{
  Security.addProvider(new BouncyCastleProvider())

  val PRIVATE_PATH: String = "gdap_private.pem"
  val keyPair: KeyPair = readKeyPair(new File(PRIVATE_PATH), "")


  /**
    * Example One
    */
  val encryptedBase64Value: String =
    "vK4L9M2alKwVCZ7bErcq33qnpDCplz5213Ww78KYR80hnizUWaE7Zzi7ty4Z7rq7OV2mvA3zK5iaGfO3PHONA8TurirjSJOdOznV1MI5E0d89O3by0Mr+xCWFgTpihB+nYuVHd1pstVGvGaSWDKaFpQKBa9sIB3JcPxJMfIjPhU7HP7cOXlE20SKkTXbTzz1QQ84bXZV6u1bbC1rLaFeLhd9iIfRC4DUZZQGFY/u2AWVIK8AJGfqYFBn8r6N8IoLEkgUA7dr2IR3ufIrAEiW5o1hQyE/nefnBTobMpfJA9EGrKKHCll2zN1DelVMwpFkgUVo1zcM/oNZS/Act161LA=="
  val encryptedValue: Array[Byte] = Base64.getDecoder.decode(encryptedBase64Value)
  val output: String =  decrypt(keyPair.getPrivate, encryptedValue)
  println(s"Output: $output")


  /**
    * Example Two
    */
  val encryptedBase64ValueTwo =
    "tD8a1mtOOD9kyAk/K8Ef7DWhWc8/QHchWjZX8QwI2C9xxtLGRyOoTvElZ19nj3w0PLIpP1VOIuZIzT8Mtj/CXPXStLE/4Lfvobg/KT/uPwYwcr0KA9pBvtg/NX5/F426LG4/SG4/b2RtRW8/q7hyXdO6Gup7P9BJ+9ywzz8m5T/ntGEts6vNBvIU9j9sLxLrxko9BFI8P/UPLfolP2oyDtq2UcZPDFSyYQ+dUd4OJa3NP9w0PymjP3Dso00/VE2stllLte+tFaI0cdN9R2c/2vkUr8YaP18/rD8VWqEkP7a6YqsqzmDBGPxvSHj9PwWhdTTSgSMuySH+4eA/TW0yUw=="
  val encryptedValueTwo: Array[Byte] = Base64.getDecoder.decode(encryptedBase64ValueTwo)
  val outputTwo: String =  decrypt(keyPair.getPrivate, encryptedValueTwo)
  println(s"Output: $outputTwo")


  private def decrypt(k: Key, encryptedValue: Array[Byte]): String = {
    val cipher: Cipher = Cipher.getInstance("RSA")
    cipher.init(Cipher.DECRYPT_MODE, k)
    println(s"length : ${encryptedValue.length}")
    new String(cipher.doFinal(encryptedValue), "ISO-8859-1")
  }

  private def readKeyPair(privateKey: File, keyPassword: String): KeyPair = {
    val fr: FileReader = new FileReader(privateKey)
    val pemReader: PEMReader = new PEMReader(fr, new DefaultPasswordFinder(keyPassword))
    val kp: KeyPair = pemReader.readObject().asInstanceOf[KeyPair]
    fr.close()
    kp
  }

}

以上代码输出:

线程“ main”中的异常javax.crypto.BadPaddingException:解密错误 enter image description here

0 个答案:

没有答案