1
votes

I have generated a private key using openssl with the following command in terminal/command:

openssl genrsa -aes256 -out private_key.pem 2048

Now i am trying to decrypt the key with Scala but i keep getting the following error:

Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:989) at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:845) at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446) at javax.crypto.Cipher.doFinal(Cipher.java:2165) at com.kewmann.utilities.security.DecryptRSAKeys.decrypt(DecryptRSAKeys.scala:46) at TestRSAKeyDecrypt$.delayedEndpoint$TestRSAKeyDecrypt$1(TestRSAKeyDecrypt.scala:20) at TestRSAKeyDecrypt$delayedInit$body.apply(TestRSAKeyDecrypt.scala:18) at scala.Function0$class.apply$mcV$sp(Function0.scala:34) at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12) at scala.App$$anonfun$main$1.apply(App.scala:76) at scala.App$$anonfun$main$1.apply(App.scala:76) at scala.collection.immutable.List.foreach(List.scala:381) at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35) at scala.App$class.main(App.scala:76) at TestRSAKeyDecrypt$.main(TestRSAKeyDecrypt.scala:18) at TestRSAKeyDecrypt.main(TestRSAKeyDecrypt.scala)

I have tried the following:

  1. Changing various Cipher Algorithm Padding.
  2. Changing to Unlimited JCE Policy as I was getting illegal key size error at one point.
  3. Change various decoders.
  4. Converting key to PCKS8 using OpenSSL (this works) but i want to decrypt programatically.

All of which could not decrypt my key. Below is my class which I wrote base on this post, [https://stackguides.com/questions/35276820/decrypting-an-openssl-pem-encoded-rsa-private-key-with-java]:

private val random = new SecureRandom()

@throws(classOf[GeneralSecurityException])
def decrypt(keyDataStr: String, ivHex: String, password: String)
{
    val pw = password.getBytes(StandardCharsets.UTF_8)
    val iv = h2b(ivHex)
    val secret = opensslKDF(pw, iv)
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv))
    val keyBytes = Base64.getMimeDecoder.decode(keyDataStr)
    val pkcs1 = cipher.doFinal(keyBytes)
    /* See note for definition of "decodeRSAPrivatePKCS1" */
    val spec = decodeRSAPrivatePKCS1(pkcs1)
    val rsa = KeyFactory.getInstance("RSA")
    rsa.generatePrivate(spec).asInstanceOf[RSAPrivateKeySpec]
}

@throws(classOf[NoSuchAlgorithmException])
private def opensslKDF(pw: Array[Byte], iv: Array[Byte]): SecretKeySpec = {
    val md5 = MessageDigest.getInstance("MD5")
    md5.update(pw)
    md5.update(iv)
    val d0 = md5.digest()
    md5.update(d0)
    md5.update(pw)
    md5.update(iv)
    val d1 = md5.digest()
    val key = new Array[Byte](24)
    System.arraycopy(d0, 0, key, 0, 16)
    System.arraycopy(d1, 0, key, 16, 8)
    new SecretKeySpec(key, "AES")
}

private def h2b(s: CharSequence): Array[Byte] = {
  val len = s.length();
  val b = new Array[Byte](len / 2)
  var src = 0
  var dst = 0
  while ( {
    src < len
  }) {
    val hi = Character.digit(s.charAt({
      src += 1; src - 1
    }), 16)
    val lo = Character.digit(s.charAt({
      src += 1; src - 1
    }), 16)
    b(dst) = (hi << 4 | lo).toByte

    dst += 1
  }
  b
}

def decodeRSAPrivatePKCS1(encoded: Array[Byte]) = {
  val input = ByteBuffer.wrap(encoded)
  if (der(input, 0x30) != input.remaining()) {
    throw new IllegalArgumentException("Excess data")
  }
  if (!BigInteger.ZERO.equals(derint(input))) {
    throw new IllegalArgumentException("Unsupported version")
  }
  val n = derint(input)
  val e = derint(input)
  val d = derint(input)
  val p = derint(input)
  val q = derint(input)
  val ep = derint(input)
  val eq = derint(input)
  val c = derint(input)
  new RSAPrivateCrtKeySpec(n, e, d, p, q, ep, eq, c)
}

private def derint(input: ByteBuffer): BigInteger = {
  val len = der(input, 0x02)
  val value = new Array[Byte](len)
  input.get(value)
  new BigInteger(+1, value)
}

private def der(input: ByteBuffer, exp: Int): Int = {
  val tag = input.get() & 0xFF
  if (tag != exp) {
    throw new IllegalArgumentException("Unexpected tag")
  }
  var n = input.get() & 0xFF
  if (n < 128) {
    n
  }
  else {
    n &= 0x7F
    if ((n < 1) || (n > 2)) {
      throw new IllegalArgumentException("Invalid length")
    }
    var len = 0
    for (i <- 0 to n) {
      len <<= 8
      len |= input.get() & 0xFF
    }
    len
  }
}

def alphanumeric(nrChars: Int = 24): String = {
  new BigInteger(nrChars * 5, random).toString(32)
}

I am totally clueless on security matters so I need some help in this area. Thanks in advance.

1
hope someone can help. thanks.Kok-Lim Wong
I don't do scala, but one thing I see is that the IV value from the DEK-Info line in OpenSSL's traditional PEM format for AES-256(CBC) is 16 bytes (32 hex digits), and all 16 bytes are used in the symmetric decrypt, but only the first 8 bytes are used as the salt (not called IV) in the PBKDF. Also if the password contains non-ASCII characters, depending on the environment where you ran openssl it might use UTF8 or it might use something different; I would avoid such characters in these files, and usually in other passwords also.dave_thompson_085
hi @dave_thompson_085, are you referring to this line? System.arraycopy(d1, 0, key, 16, 8). where the 8 should be a 16?Kok-Lim Wong
Or could you teach me how to debug? Because I have no clue on what I am doing here as I have no knowledge of cryptography.Kok-Lim Wong
No, that's part of the PBKDF output, it is not the value labelled IV but actually salt. But I see you've now used Bouncy which has PEM-like-OpenSSL already correct.dave_thompson_085

1 Answers

0
votes

Decided to abandon the approach I posted and used BouncyCastle. Sample code here.

Much easier for a crytography clueless like me.