whyoleg / cryptography-kotlin

Kotlin Multiplatform cryptography / crypto library
https://whyoleg.github.io/cryptography-kotlin/
Apache License 2.0
267 stars 15 forks source link

Wrong PEM label, expected PemLabel(representation=PRIVATE KEY), actual PemLabel(representation=EC PRIVATE KEY) #33

Open ngallazzi opened 2 months ago

ngallazzi commented 2 months ago

I'm trying to generate ECDSA signature from a known private key generated according to RFC 5915 specifications. However when I try to decode the key I get a parsing exception: Wrong PEM label, expected PemLabel(representation=PRIVATE KEY), actual PemLabel(representation=EC PRIVATE KEY) Isn't the library supposed to work with the RFC 5915 private key format? Thanks for the support?

val secret = "-----BEGIN EC PRIVATE KEY-----
key payload here
-----END EC PRIVATE KEY-----"

class TimeSignatureHelper(private val secret: String) {
    private val ecdsa = CryptographyProvider.Default.get(ECDSA)
    suspend fun getSignature(timestamp: String): ByteArray {
        try {
            val decoder = ecdsa.privateKeyDecoder(EC.Curve.P256)
            val privateKey = decoder.decodeFrom(EC.PrivateKey.Format.PEM, secret.encodeToByteArray())
            val signatureGenerator: SignatureGenerator =
                privateKey.signatureGenerator(
                    digest = SHA256,
                    format = ECDSA.SignatureFormat.DER
                )
            val signature = signatureGenerator.generateSignature(timestamp.encodeToByteArray())
            return signature
        } catch (e: Exception) {
            Logger.d { e.toString() }
            return byteArrayOf()
        }
    }
}
whyoleg commented 2 months ago

Hey! Yeah, sorry about that, but RFC 5915 PEM/DER encoding is not yet supported. (It looks like I need to start writing some documentation...)

Current PEM/DER encoding is based on PKCS8 / RFC 5208. The main problem with RFC 5915 is that it's not widely supported in providers: nor WebCrypto, nor JDK, nor Apple providers support it out of the box. TBH, I've tried to support it before but decided to postpone it. Now we do have all primitives which are needed to implement it (like ASN.1 module) and will try my best to make RFC 5915 compatible encoding available in the next release.

ngallazzi commented 2 months ago

@whyoleg thanks for the quick answer, I see!

ColtonIdle commented 2 weeks ago

If you use 0.4.0 snapshot then you can switch it to EC.PrivateKey.Format.PEM.SEC1 and rfc 5915 will work!