Home > Enterprise >  Curve25519 cipher accepts only 32 byte but I get wrong public key size in Kotlin
Curve25519 cipher accepts only 32 byte but I get wrong public key size in Kotlin

Time:10-21

I want to use Curve25519 cipher for verifying I get Public key as :

 val publicTxt = """
      -----BEGIN PUBLIC KEY-----
       ...
      -----END PUBLIC KEY-----
          """.trimIndent()

This is how I load the public key:

    private fun loadPublicKey(key: String): PublicKey {
    Security.addProvider(BouncyCastleProvider())

    val pemParser = PEMParser(StringReader(key))

    val converter = JcaPEMKeyConverter()

    val publicKeyInfo = SubjectPublicKeyInfo.getInstance(pemParser.readObject())

    return converter.getPublicKey(publicKeyInfo)

}

This cipher only accept 32 byte but I get 44 :

        val publicTxt = """
      -----BEGIN PUBLIC KEY-----
       ...
      -----END PUBLIC KEY-----
          """.trimIndent()

    val public = loadPublicKey(publicTxt)

    print(public.encoded.size)

CodePudding user response:

Your publicTxt is in base64 form. So you'll need to decode it first like so:

val publicTxt = """
      -----BEGIN PUBLIC KEY-----
       MCowBQYDK2VuAyEAR3L3HoVhvbTkrP2pa1R3gwGn/CEbZM92TxzmMkUe5ls=
      -----END PUBLIC KEY-----
          """.trimIndent().replace(Regex("-----BEGIN PUBLIC KEY-----|-----END PUBLIC KEY-----"), "")
val decodedBytes = Base64.getDecoder().decode(publicTxt)
val decodedString = String(decodedBytes)

val public = loadPublicKey(decodedString)
...

CodePudding user response:

I thought I needed to parse it as PublicKey using pem parser from Bouncy Castle Library but thanks to @Darkman answer all I needed is to decode it with out the header and the footer and get last 32 byte as follows:

val publicTxt = "-----BEGIN PUBLIC KEY-----"  
            "..............................."  
                "-----END PUBLIC KEY-----"

publicTxt = publicTxt.replace("-----BEGIN PUBLIC KEY-----", "")
        .replace("-----END PUBLIC KEY-----", "")

val decoded = Base64.getDecoder().decode(publicTxt)

val getLast32Byte = decoded.copyOfRange(decoded.size - 32, decoded.size)

It also works with private keys.

  • Related