whyoleg / cryptography-kotlin

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

SHA256withECDSAinP1363Format Signature not available #30

Closed ngallazzi closed 1 month ago

ngallazzi commented 6 months ago

Project: Compose Multiplatform Library version: 0.3.1 agp = "8.2.0" kotlin = "1.9.21"

key:

"-----BEGIN PRIVATE KEY-----\n" + "My key payload" "-----END PRIVATE KEY-----"


class TimeSignatureHelper(private val secret: String) {
    private val ecdsa = CryptographyProvider.Default.get(ECDSA)
    suspend fun getSignature(timestamp: String): String {
        try {
            val privateKey: ECDSA.PrivateKey = ecdsa.privateKeyDecoder(EC.Curve.P256)
                .decodeFrom(EC.PrivateKey.Format.PEM, secret.toByteArray())

            val signatureGenerator: SignatureGenerator = privateKey.signatureGenerator(digest = SHA256)
            val signature = signatureGenerator.generateSignature(timestamp.encodeToByteArray())
            return signature.encodeBase64()
        } catch (e: Exception) {
            Logger.d { e.toString() }
            return ""
        }
    }
}

Exception caused by: java.security.NoSuchAlgorithmException: SHA256withECDSAinP1363Format Signature not available

whyoleg commented 6 months ago

Hey! Androids default JDK Provider as well as BouncyCastle doesn't support ECDSA.SignatureFormat.RAW out of the box, which is a default for SignatureGenerator (most probably this default should be dropped, defaults are hard in cryptography). May be it's possible for you to use ECDSA.SignatureFormat.DER format for signature? I was planning to support both signature formats consistently over all formats in the following release.

ngallazzi commented 6 months ago

@whyoleg Yep, I guess It's feasible for me, thank you!

whyoleg commented 1 month ago

0.4.0 was just released! Both ECDSA signature formats are supported by all providers