简体   繁体   中英

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

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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM