Scoop API

scoop:scoop.crypto:0.1.0

src/mac.scoop

Selected production source · src/mac.scoop

1package scoop.crypto
3import scoop.crypto.native.*
5/**
6 * Owned native storage for symmetric key bytes. Close it after use; exporting creates a separate
7 * managed byte copy.
8 */
9public class SecretKey private constructor(private var handle: ULong) : Closeable {
10 /**
11 * The key length in bytes; access after close fails.
12 */
13 public val size: Long get() { @Unsafe { return bytesSize(nativeHandle()) } }
15 /**
16 * Imports key material into independently owned native storage.
17 */
18 public companion object {
19 /**
20 * Copies the supplied key bytes into a new owned SecretKey.
21 */
22 public fun fromBytes(data: List<Byte>): SecretKey {
23 val bytes = data.toArray()
24 @Unsafe { return bytes.withDataPointer { pointer, count ->
25 @Unsafe { return@withDataPointer SecretKey(cryptoValue(secretImport(pointer, count), "import secret key")) }
26 } }
27 }
28 }
30 internal fun nativeHandle(): ULong {
31 if (handle == 0UL) throw IllegalStateException(Some("secret key is closed"))
32 return handle
33 }
35 /**
36 * Returns a managed copy of the key material. Closing the key does not erase this separate
37 * copy.
38 */
39 public fun exportBytes(): Array<Byte> { @Unsafe { return cryptoBytes(secretExport(nativeHandle()), "export secret key") } }
41 /**
42 * Releases native key storage; repeated closes are harmless.
43 */
44 public override fun close() {
45 val owned = handle
46 handle = 0UL
47 if (owned != 0UL) @Unsafe { bytesFree(owned) }
48 }
51/**
52 * Computes HMAC with SHA-256, SHA-384, or SHA-512. Other digest selections are rejected.
53 */
54public fun hmac(algorithm: DigestAlgorithm, key: SecretKey, data: List<Byte>): Array<Byte> {
55 if (algorithm != DigestAlgorithm.Sha256 && algorithm != DigestAlgorithm.Sha384 && algorithm != DigestAlgorithm.Sha512)
56 throw IllegalArgumentException(Some("HMAC requires SHA-256, SHA-384, or SHA-512"))
57 val handle = key.nativeHandle()
58 val bytes = data.toArray()
59 @Unsafe { return bytes.withDataPointer { pointer, count ->
60 @Unsafe { return@withDataPointer cryptoBytes(nativeHmac(digestCode(algorithm), handle, pointer, count), "HMAC") }
61 } }
64/**
65 * Computes the expected MAC and compares equal-length bytes using the native constant-time
66 * comparison. A length mismatch returns false.
67 */
68public fun verifyHmac(algorithm: DigestAlgorithm, key: SecretKey, data: List<Byte>, expected: List<Byte>): Boolean {
69 val actual = hmac(algorithm, key, data)
70 val other = expected.toArray()
71 if (actual.size != other.size) return false
72 @Unsafe { return actual.withDataPointer { left, count ->
73 @Unsafe { return@withDataPointer other.withDataPointer { right, _ -> @Unsafe { return@withDataPointer nativeEqual(left, right, count) == 1 } } }
74 } }