Scoop API

scoop:scoop.crypto:0.1.0

src/signature.scoop

Selected production source · src/signature.scoop

1package scoop.crypto
3import scoop.crypto.native.*
5/**
6 * Signature schemes with explicit digest and wire encoding; the key family must match the selected
7 * scheme.
8 */
9public enum SignatureAlgorithm {
10 /**
11 * RSA PKCS#1 v1.5 signing with SHA-256.
12 */
13 RsaPkcs1Sha256,
14 /**
15 * RSA-PSS signing with SHA-256.
16 */
17 RsaPssSha256,
18 /**
19 * ECDSA on P-256 with SHA-256 and a DER-encoded signature.
20 */
21 EcdsaP256Sha256Der,
22 /**
23 * Ed25519 signing over the supplied message bytes.
24 */
25 Ed25519 }
27private fun signatureCode(algorithm: SignatureAlgorithm, key: KeyAlgorithm): Int {
28 val expected = when (algorithm) {
29 case RsaPkcs1Sha256 -> KeyAlgorithm.Rsa
30 case RsaPssSha256 -> KeyAlgorithm.Rsa
31 case EcdsaP256Sha256Der -> KeyAlgorithm.P256
32 case Ed25519 -> KeyAlgorithm.Ed25519
33 }
34 if (key != expected) throw IllegalArgumentException(Some("signature algorithm and key do not match"))
35 return when (algorithm) {
36 case RsaPkcs1Sha256 -> 0
37 case RsaPssSha256 -> 1
38 case EcdsaP256Sha256Der -> 2
39 case Ed25519 -> 3
40 }
43/**
44 * Signs the message using a matching live private key and returns the scheme's signature encoding.
45 */
46public fun sign(algorithm: SignatureAlgorithm, key: PrivateKey, data: List<Byte>): Array<Byte> {
47 val code = signatureCode(algorithm, key.algorithm)
48 val handle = key.nativeHandle()
49 val bytes = data.toArray()
50 @Unsafe { return bytes.withDataPointer { pointer, count ->
51 @Unsafe { return@withDataPointer cryptoBytes(keySign(code, handle, pointer, count), "sign") }
52 } }
55/**
56 * Verifies a signature with a matching live public key. A signature mismatch returns false;
57 * invalid configuration and backend errors throw.
58 */
59public fun verify(algorithm: SignatureAlgorithm, key: PublicKey, data: List<Byte>, signature: List<Byte>): Boolean {
60 val code = signatureCode(algorithm, key.algorithm)
61 val handle = key.nativeHandle()
62 val bytes = data.toArray()
63 val signed = signature.toArray()
64 @Unsafe { return bytes.withDataPointer { pointer, count ->
65 @Unsafe { return@withDataPointer signed.withDataPointer { signaturePointer, size ->
66 @Unsafe { return@withDataPointer cryptoValue(keyVerify(code, handle, pointer, count, signaturePointer, size), "verify signature") == 1UL }
67 } }
68 } }