scoop:scoop.crypto:0.1.0
src/signature.scoop
Selected production source · src/signature.scoop
1
package scoop.crypto3
import scoop.crypto.native.*5
/**6
* Signature schemes with explicit digest and wire encoding; the key family must match the selected7
* scheme.8
*/9
public 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 }27
private fun signatureCode(algorithm: SignatureAlgorithm, key: KeyAlgorithm): Int {28
val expected = when (algorithm) {29
case RsaPkcs1Sha256 -> KeyAlgorithm.Rsa30
case RsaPssSha256 -> KeyAlgorithm.Rsa31
case EcdsaP256Sha256Der -> KeyAlgorithm.P25632
case Ed25519 -> KeyAlgorithm.Ed2551933
}34
if (key != expected) throw IllegalArgumentException(Some("signature algorithm and key do not match"))35
return when (algorithm) {36
case RsaPkcs1Sha256 -> 037
case RsaPssSha256 -> 138
case EcdsaP256Sha256Der -> 239
case Ed25519 -> 340
}41
}43
/**44
* Signs the message using a matching live private key and returns the scheme's signature encoding.45
*/46
public 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
} }53
}55
/**56
* Verifies a signature with a matching live public key. A signature mismatch returns false;57
* invalid configuration and backend errors throw.58
*/59
public 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
} }69
}