whyoleg / cryptography-kotlin

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

SHA256withECDSAinP1363Format Signature not available #30

Open ngallazzi opened 1 month ago

ngallazzi commented 1 month 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 1 month 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 1 month ago

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