Compare commits

..
3 Commits
14 changed files with 475 additions and 31 deletions

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" /> <component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="FrameworkDetectionExcludesConfiguration"> <component name="FrameworkDetectionExcludesConfiguration">
+15
View File
@@ -0,0 +1,15 @@
# crypto2 0.9.6-SNAPSHOT
SafeKeyExchange now rejects peer public keys whose encoded length is not exactly
32 bytes before calling native bindings. Low-order DH rejection remains delegated
to libsodium crypto_kx; its failure already propagates through the Kotlin bindings.
Regression tests cover low-order inputs (including nonzero inputs and high-bit
aliases), malformed lengths, and valid bidirectional exchange.
This snapshot retains the distinct-signer threshold fix described in
[SECURITY-0.9.5.md](SECURITY-0.9.5.md). Wire formats are unchanged.
Validation: all 67 JVM tests and all 67 Linux x64 Native tests passed. The three
focused JavaScript/Node tests fail during initialization with the previously
documented `_sodium_init is not a function` loader error, before exercising DH.
Other platform runtimes were not qualified. This snapshot does not fix the JS loader.
+23
View File
@@ -0,0 +1,23 @@
# crypto2 0.9.5 security fix
`Multikey.Keys.check` now counts distinct authorized signer keys. Earlier versions
could count repeated copies of one allowed key toward an N-of-M threshold.
A serialized `SealedBox` containing repeated copies of a valid seal could therefore
pass threshold authorization without the required distinct signers. Signature
verification itself was not forged. Policies built with `someOf` or `allOf`,
including these thresholds inside nested expressions, were affected.
Upgrade consumers to 0.9.5. Wire formats and public APIs are unchanged. Repeated
seals remain readable but cannot supply extra votes. Boolean expression semantics
(including intentionally overlapping branches) are unchanged.
Regression coverage includes exhaustive subsets for one through four required
keys, duplicate and unauthorized signers, nested policies, and serialized seal
repetition with valid distinct-signature controls.
Release qualification: all 64 JVM tests and all 64 Linux x64 native tests pass.
The JavaScript/Node suite cannot complete: 61 of 64 tests fail at the existing
libsodium loader (`_sodium_init is not a function`). An unchanged-source signing
test reproduces that same failure; this release does not fix the JS loader.
All 12 configured publications were uploaded to Maven Local and the private Maven
repository; SHA-256 comparison of 53 downloaded release files matched Maven Local.
+3 -3
View File
@@ -13,14 +13,14 @@ import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins { plugins {
kotlin("multiplatform") version "2.2.21" kotlin("multiplatform") version "2.4.0"
id("org.jetbrains.kotlin.plugin.serialization") version "2.2.21" id("org.jetbrains.kotlin.plugin.serialization") version "2.4.0"
id("org.jetbrains.dokka") version "1.9.20" id("org.jetbrains.dokka") version "1.9.20"
`maven-publish` `maven-publish`
} }
group = "net.sergeych" group = "net.sergeych"
version = "0.9.2" version = "0.9.6-SNAPSHOT"
repositories { repositories {
mavenCentral() mavenCentral()
@@ -155,15 +155,9 @@ sealed class Container {
abstract val decryptedWithKeyId: KeyId? abstract val decryptedWithKeyId: KeyId?
/** /**
* If the container _is decrypted by the [EncryptingPublicKey]_, e.g., using secret key encryption, * When the container is decrypted, the key that unlocked it, otherwise null.
* contains the [EncryptingPublicKey] that corresponds the [DecryptingSecretKey] used while encrypting, this
* authenticating the sender party cryptographically. This key could be used to encrypt
* the response to be visible to the sender only; the sender, providing it kept his secret key,
* could decrypt it.
*/ */
@Transient abstract val decryptedWithKey: UniversalKey?
var authorisedByKey: EncryptingPublicKey? = null
protected set
/** /**
* List of [KeyId] of the keys that unlocked the container, in the same order used for encryption.. * List of [KeyId] of the keys that unlocked the container, in the same order used for encryption..
@@ -185,7 +179,8 @@ sealed class Container {
) : Container() { ) : Container() {
@Transient @Transient
private var decryptedWithKey: DecryptingKey? = null override var decryptedWithKey: UniversalKey? = null
private set
override val decryptedWithKeyId: KeyId? override val decryptedWithKeyId: KeyId?
get() = decryptedWithKey?.id get() = decryptedWithKey?.id
@@ -202,10 +197,7 @@ sealed class Container {
if (k.id == keyId) { if (k.id == keyId) {
kotlin.runCatching { k.decrypt(encryptedMessage) }.getOrNull()?.let { kotlin.runCatching { k.decrypt(encryptedMessage) }.getOrNull()?.let {
decryptedData = it decryptedData = it
decryptedWithKey = k decryptedWithKey = k as UniversalKey
if(k is DecryptingSecretKey) {
authorisedByKey = Asymmetric.Message.decode(encryptedMessage).senderPublicKey
}
return it return it
} }
} }
@@ -284,9 +276,12 @@ sealed class Container {
} }
@Transient @Transient
override var decryptedWithKeyId: KeyId? = null override var decryptedWithKey: UniversalKey? = null
private set private set
override val decryptedWithKeyId: KeyId?
get() = decryptedWithKey?.id
override val keyIds: List<KeyId> = encryptedKeys.map { it.tag } override val keyIds: List<KeyId> = encryptedKeys.map { it.tag }
override fun decryptWith(keyRing: UniversalRing): UByteArray? { override fun decryptWith(keyRing: UniversalRing): UByteArray? {
@@ -302,11 +297,8 @@ sealed class Container {
}.getOrNull()?.let { k -> }.getOrNull()?.let { k ->
if (kotlin.runCatching { decryptedData = k.decrypt(encryptedMessage) }.isFailure) if (kotlin.runCatching { decryptedData = k.decrypt(encryptedMessage) }.isFailure)
throw InvalidContainerException() throw InvalidContainerException()
decryptedWithKeyId = key.id decryptedWithKey = key as UniversalKey
mainKey = k mainKey = k
if(key is DecryptingSecretKey) {
authorisedByKey = Asymmetric.Message.decode(encryptedKey.cipherData).senderPublicKey
}
} }
if (decryptedData != null) return decryptedData if (decryptedData != null) return decryptedData
} }
@@ -0,0 +1,78 @@
/*
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
*
* You may use, distribute and modify this code under the
* terms of the private license, which you must obtain from the author
*
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
* real dot sergeych at gmail.
*/
package net.sergeych.crypto2
internal val Hash.supportsHmac: Boolean
get() = when (this) {
Hash.Blake2b, Hash.Sha3_256, Hash.Sha3_384 -> true
Hash.Sha3AndBlake -> false
}
internal val Hash.hkdfMaxOutputSize: Int
get() = hkdfHashSize * 255
private val Hash.hkdfHashSize: Int
get() = digest(ubyteArrayOf()).size
private val Hash.hmacBlockSize: Int
get() = when (this) {
Hash.Blake2b -> 128
Hash.Sha3_256 -> 136
Hash.Sha3_384 -> 104
Hash.Sha3AndBlake -> throw IllegalArgumentException("Hash $this is not supported for HMAC")
}
internal fun hkdf(
hash: Hash,
source: UByteArray,
salt: UByteArray,
info: UByteArray,
size: Int,
): UByteArray {
require(source.isNotEmpty()) { "HKDF source bytes should not be empty" }
require(size > 0) { "HKDF output size should be positive" }
require(hash.supportsHmac) { "Hash $hash is not supported for HKDF" }
require(size <= hash.hkdfMaxOutputSize) {
"HKDF output for $hash is limited to ${hash.hkdfMaxOutputSize} bytes"
}
val hashSize = hash.hkdfHashSize
val extractionSalt = if (salt.isEmpty()) UByteArray(hashSize) else salt
val pseudorandomKey = hmac(hash, extractionSalt, source)
val result = UByteArray(size)
var previous = ubyteArrayOf()
var offset = 0
var counter = 1
while (offset < size) {
previous = hmac(hash, pseudorandomKey, previous + info + counter.toUByte())
val count = minOf(previous.size, size - offset)
for (i in 0..<count) {
result[offset + i] = previous[i]
}
offset += count
counter += 1
}
return result
}
private fun hmac(hash: Hash, key: UByteArray, data: UByteArray): UByteArray {
val blockSize = hash.hmacBlockSize
val normalizedKey = if (key.size > blockSize) hash.digest(key) else key
val keyBlock = UByteArray(blockSize)
for (i in normalizedKey.indices) {
keyBlock[i] = normalizedKey[i]
}
val innerPad = UByteArray(blockSize) { (keyBlock[it].toInt() xor 0x36).toUByte() }
val outerPad = UByteArray(blockSize) { (keyBlock[it].toInt() xor 0x5c).toUByte() }
return hash.digest(outerPad + hash.digest(innerPad + data))
}
@@ -56,7 +56,8 @@ import net.sergeych.crypto2.Multikey.Companion.someOfMultikeys
sealed class Multikey { sealed class Multikey {
/** /**
* Check that the [keys] satisfy the condition of this instance * Check that the [keys] satisfy the condition of this instance. Repeated signer keys
* count only once toward each key threshold.
*/ */
abstract fun check(keys: Iterable<VerifyingPublicKey>): Boolean abstract fun check(keys: Iterable<VerifyingPublicKey>): Boolean
@@ -96,8 +97,9 @@ sealed class Multikey {
) : Multikey() { ) : Multikey() {
override fun check(keys: Iterable<VerifyingPublicKey>): Boolean { override fun check(keys: Iterable<VerifyingPublicKey>): Boolean {
var matches = 0 var matches = 0
val matchedKeys = mutableSetOf<VerifyingPublicKey>()
for (signer in keys) { for (signer in keys) {
if (signer in validKeys) { if (signer in validKeys && matchedKeys.add(signer)) {
if (++matches >= requiredMinimum) return true if (++matches >= requiredMinimum) return true
} }
} }
@@ -15,6 +15,7 @@ import com.ionspin.kotlin.crypto.keyexchange.KeyExchangeKeyPair
import com.ionspin.kotlin.crypto.keyexchange.crypto_kx_PUBLICKEYBYTES import com.ionspin.kotlin.crypto.keyexchange.crypto_kx_PUBLICKEYBYTES
import com.ionspin.kotlin.crypto.keyexchange.crypto_kx_SECRETKEYBYTES import com.ionspin.kotlin.crypto.keyexchange.crypto_kx_SECRETKEYBYTES
import kotlinx.serialization.KSerializer import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Decoder
@@ -81,7 +82,7 @@ class SafeKeyExchange private constructor(
* The session key. It uses a pair of keys to encrypt and decrypt messages to maintain high * The session key. It uses a pair of keys to encrypt and decrypt messages to maintain high
* security level and allow using counters as nonce with no extra precautions. * security level and allow using counters as nonce with no extra precautions.
*/ */
@Serializable @Serializable(with = SafeKeyExchange.SessionKeySerializer::class)
class SessionKey( class SessionKey(
val sendingKey: EncryptingKey, val sendingKey: EncryptingKey,
val receivingKey: DecryptingKey, val receivingKey: DecryptingKey,
@@ -128,6 +129,36 @@ class SafeKeyExchange private constructor(
} }
@Serializable
private class PackedSessionKey(
val sendingKey: SymmetricKey,
val receivingKey: SymmetricKey,
val isClient: Boolean,
)
object SessionKeySerializer : KSerializer<SessionKey> {
private val packedSerializer = PackedSessionKey.serializer()
override val descriptor: SerialDescriptor = packedSerializer.descriptor
override fun serialize(encoder: Encoder, value: SessionKey) {
val sendingKey = value.sendingKey as? SymmetricKey
?: throw SerializationException("SessionKey.sendingKey must be SymmetricKey")
val receivingKey = value.receivingKey as? SymmetricKey
?: throw SerializationException("SessionKey.receivingKey must be SymmetricKey")
encoder.encodeSerializableValue(
packedSerializer,
PackedSessionKey(sendingKey, receivingKey, value.isClient)
)
}
override fun deserialize(decoder: Decoder): SessionKey {
val packed = decoder.decodeSerializableValue(packedSerializer)
return SessionKey(packed.sendingKey, packed.receivingKey, packed.isClient)
}
}
/** /**
* The public key; it should be transmitted to the other party, this is serializable. * The public key; it should be transmitted to the other party, this is serializable.
* Do not use it except to get [SessionKey] with [clientSessionKey] or [serverSessionKey]. Storing and reusing * Do not use it except to get [SessionKey] with [clientSessionKey] or [serverSessionKey]. Storing and reusing
@@ -164,17 +195,28 @@ class SafeKeyExchange private constructor(
* Create asymmetric [SessionKey] to encrypt the session. It can't decrypt what is encrypted by it * Create asymmetric [SessionKey] to encrypt the session. It can't decrypt what is encrypted by it
* but can decrypt what was encrypted with the [serverSessionKey] on the another side. * but can decrypt what was encrypted with the [serverSessionKey] on the another side.
*/ */
fun clientSessionKey(serverPublicKey: PublicKey): SessionKey = fun clientSessionKey(serverPublicKey: PublicKey): SessionKey {
KeyExchange.clientSessionKeys(pair.publicKey, pair.secretKey, serverPublicKey.keyBytes) requirePeerKeySize(serverPublicKey)
// crypto_kx rejects low-order inputs before deriving keys; the binding propagates failure.
return KeyExchange.clientSessionKeys(pair.publicKey, pair.secretKey, serverPublicKey.keyBytes)
.let { SessionKey(SymmetricKey(it.sendKey), SymmetricKey(it.receiveKey), isClient = true) } .let { SessionKey(SymmetricKey(it.sendKey), SymmetricKey(it.receiveKey), isClient = true) }
}
/** /**
* Create an asymmetric [SessionKey] instance to work with [clientSessionKey] on the other side. * Create an asymmetric [SessionKey] instance to work with [clientSessionKey] on the other side.
* Note that asymmetric means it can't decrypt what it encrypted. * Note that asymmetric means it can't decrypt what it encrypted.
*/ */
fun serverSessionKey(clientPublicKey: PublicKey): SessionKey = fun serverSessionKey(clientPublicKey: PublicKey): SessionKey {
KeyExchange.serverSessionKeys(pair.publicKey, pair.secretKey, clientPublicKey.keyBytes) requirePeerKeySize(clientPublicKey)
return KeyExchange.serverSessionKeys(pair.publicKey, pair.secretKey, clientPublicKey.keyBytes)
.let { SessionKey(SymmetricKey(it.sendKey), SymmetricKey(it.receiveKey), isClient = false) } .let { SessionKey(SymmetricKey(it.sendKey), SymmetricKey(it.receiveKey), isClient = false) }
}
private fun requirePeerKeySize(peer: PublicKey) {
require(peer.keyBytes.size == crypto_kx_PUBLICKEYBYTES) {
"Peer DH public key must be $crypto_kx_PUBLICKEYBYTES bytes"
}
}
} }
@@ -257,6 +257,75 @@ sealed class KDF {
} }
} }
/**
* Fast HKDF derivation for already strong byte material, implemented as described in
* [RFC 5869](https://www.rfc-editor.org/rfc/rfc5869).
*
* HKDF is suitable when [deriveFromBytes] receives source bytes that already contain enough entropy, for
* example a shared secret produced by a key agreement protocol, random master key material, or another
* high-entropy secret. It is fast by design: it does not slow down brute-force attempts and does not use
* extra memory. Do not use it for passwords, memorable phrases, short PINs, user-entered secrets, or other
* low-entropy inputs; use [Argon] for those instead.
*
* The derivation is deterministic for the tuple `(hash, salt, info, keySize, source)`. Store or recreate the
* same parameters to derive the same output again. [salt] and [info] are not secret, but changing either one
* changes the derived bytes.
*
* @property hash Hash function to use inside HMAC. The default is [Hash.Sha3_256]. [Hash.Blake2b],
* [Hash.Sha3_256], and [Hash.Sha3_384] are supported; [Hash.Sha3AndBlake] is intentionally rejected because
* it is a synthetic concatenated hash and has no well-defined HMAC block size.
* @property salt Optional extraction salt. Prefer a stable random salt when one is available and can be stored
* with the derived data. An empty salt is allowed by HKDF and is treated as a zero-filled salt of the selected
* hash output size.
* @property info Optional application-specific context string or binary label. Use it to domain-separate
* outputs derived from the same source, for example `"container encryption"`, `"header auth"`, or a protocol
* transcript hash. It may be empty when there is only one unambiguous use for the derived bytes.
* @property keySize Number of bytes to derive. It must be positive and no larger than `255 * hashLen`, where
* `hashLen` is the output size of [hash].
*/
@Serializable
@SerialName("hkdf")
data class HKDF(
val hash: Hash = Hash.Sha3_256,
val salt: UByteArray = ubyteArrayOf(),
val info: UByteArray = ubyteArrayOf(),
@Unsigned
val keySize: Int,
) : KDF() {
init {
require(keySize > 0) { "HKDF key size should be positive" }
require(hash.supportsHmac) { "Hash $hash is not supported for HKDF" }
require(keySize <= hash.hkdfMaxOutputSize) {
"HKDF output for $hash is limited to ${hash.hkdfMaxOutputSize} bytes"
}
}
override fun deriveKey(password: String): UByteArray =
throw UnsupportedOperationException("HKDF is not a password KDF; use Argon for passwords")
override fun deriveFromBytes(source: UByteArray): UByteArray =
hkdf(hash, source, salt, info, keySize)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is HKDF) return false
if (hash != other.hash) return false
if (keySize != other.keySize) return false
if (!salt.contentEquals(other.salt)) return false
return info.contentEquals(other.info)
}
override fun hashCode(): Int {
var result = hash.hashCode()
result = 31 * result + salt.contentHashCode()
result = 31 * result + info.contentHashCode()
result = 31 * result + keySize
return result
}
}
companion object { companion object {
/** /**
+5 -3
View File
@@ -34,6 +34,8 @@ class ContainerTest {
assertNotNull(d) assertNotNull(d)
assertContentEquals(data, d) assertContentEquals(data, d)
assertTrue { c1.isDecrypted } assertTrue { c1.isDecrypted }
assertEquals(syk1.id, c1.decryptedWithKeyId)
assertEquals(syk1, c1.decryptedWithKey)
val data2 = "To push unpushinable".encodeToUByteArray() val data2 = "To push unpushinable".encodeToUByteArray()
val c2 = Container.decode(c.updateData(data2).encoded) val c2 = Container.decode(c.updateData(data2).encoded)
@@ -61,7 +63,7 @@ class ContainerTest {
assertContentEquals(data, d) assertContentEquals(data, d)
assertTrue { c1.isDecrypted } assertTrue { c1.isDecrypted }
assertEquals(p2.publicKey.id, c1.decryptedWithKeyId) assertEquals(p2.publicKey.id, c1.decryptedWithKeyId)
assertEquals(p1.publicKey, c1.authorisedByKey) assertEquals(p2.secretKey, c1.decryptedWithKey)
val data2 = "To push unpushinable".encodeToUByteArray() val data2 = "To push unpushinable".encodeToUByteArray()
val c2 = Container.decode(c.updateData(data2).encoded) val c2 = Container.decode(c.updateData(data2).encoded)
@@ -88,7 +90,7 @@ class ContainerTest {
assertContentEquals(data, d) assertContentEquals(data, d)
assertTrue { c1.isDecrypted } assertTrue { c1.isDecrypted }
assertEquals(p4.publicKey.id, c1.decryptedWithKeyId) assertEquals(p4.publicKey.id, c1.decryptedWithKeyId)
assertEquals(p1.publicKey, c1.authorisedByKey) assertEquals(p4.secretKey, c1.decryptedWithKey)
val data2 = "To push unpushinable".encodeToUByteArray() val data2 = "To push unpushinable".encodeToUByteArray()
val c2 = Container.decode(c.updateData(data2).encoded) val c2 = Container.decode(c.updateData(data2).encoded)
@@ -338,4 +340,4 @@ class ContainerTest {
expectOpen(data2, syk3, p3.secretKey, p4.secretKey) expectOpen(data2, syk3, p3.secretKey, p4.secretKey)
} }
} }
@@ -0,0 +1,57 @@
import kotlinx.coroutines.test.runTest
import net.sergeych.bipack.BipackDecoder
import net.sergeych.crypto2.*
import kotlin.test.*
class DuplicateSignerTest {
@Test fun thresholdsCountDistinctAuthorizedKeys() = runTest {
initCrypto()
val keys = List(4) { SigningSecretKey.new().verifyingKey }
val outsider = SigningSecretKey.new().verifyingKey
// Exhaust all subsets of authorized keys, thresholds, and repeated inputs.
for (threshold in 1..keys.size) {
val policy = Multikey.someOf(threshold, keys)
for (mask in 0 until (1 shl keys.size)) {
val selected = keys.filterIndexed { index, _ -> mask and (1 shl index) != 0 }
for (copies in 1..5) {
val signers = selected.flatMap { key -> List(copies) { key } } + List(5) { outsider }
assertEquals(selected.size >= threshold, policy.check(signers))
assertEquals(selected.size >= threshold, policy.check(signers.reversed()))
}
}
}
assertFalse(Multikey.allOf(keys).check(List(10) { keys.first() }))
assertTrue(Multikey.allOf(keys).check(keys + keys))
}
@Test fun nestedPoliciesKeepBooleanSemantics() = runTest {
initCrypto()
val a = SigningSecretKey.new().verifyingKey
val b = SigningSecretKey.new().verifyingKey
val c = SigningSecretKey.new().verifyingKey
val d = SigningSecretKey.new().verifyingKey
val threshold = Multikey.someOf(2, a, b)
val policy = (threshold and c) or d
assertFalse(policy.check(a, a, c))
assertTrue(policy.check(a, a, b, c))
assertTrue(policy.check(d))
// Overlapping branches remain logical expressions, not globally consumed signatures.
assertTrue(((a or b) and (a or c)).check(a))
}
@Test fun repeatedValidSealCannotSatisfyThresholdAfterDecoding() = runTest {
initCrypto()
val a = SigningSecretKey.new()
val b = SigningSecretKey.new()
val policy = Multikey.someOf(2, a.verifyingKey, b.verifyingKey)
val original = SealedBox.create("threshold regression".encodeToByteArray().toUByteArray(), a)
val repeated = SealedBox(original.message, List(3) { original.seals.single() })
val decoded = BipackDecoder.decode<SealedBox>(repeated.encoded.asByteArray())
assertEquals(3, decoded.seals.size)
assertEquals(1, decoded.signedByKeys.toSet().size)
assertFalse(decoded.isSealedBy(policy))
assertTrue(decoded.isSealedBy(Multikey(a)))
val authorized = BipackDecoder.decode<SealedBox>((original + b).encoded.asByteArray())
assertTrue(authorized.isSealedBy(policy))
}
}
+81
View File
@@ -8,6 +8,7 @@
* real dot sergeych at gmail. * real dot sergeych at gmail.
*/ */
import com.ionspin.kotlin.crypto.util.encodeToUByteArray
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import net.sergeych.crypto2.Hash import net.sergeych.crypto2.Hash
import net.sergeych.crypto2.KDF import net.sergeych.crypto2.KDF
@@ -133,4 +134,84 @@ class KDFTest {
assertEquals(96, longKdf.deriveFromBytes(source).size) assertEquals(96, longKdf.deriveFromBytes(source).size)
} }
@Test
fun hkdfDeriveFromBytesTest() = runTest {
initCrypto()
val source = "strong source bytes with enough entropy".encodeToUByteArray()
val salt = "stored public salt".encodeToUByteArray()
val info = "crypto2:test".encodeToUByteArray()
val kdf = KDF.HKDF(Hash.Sha3_256, salt, info, 80)
val b1 = kdf.deriveFromBytes(source)
val b2 = kdf.deriveFromBytes(source)
val b3 = kdf.deriveFromBytes(source + 1u)
val b4 = kdf.copy(info = "crypto2:other".encodeToUByteArray()).deriveFromBytes(source)
val expected = hexToUBytes(
"580cfd4eb588312097c9e43852d62bec9aff988591e2e5f721a2facc80c3c494" +
"d3487b81e19f71611bdebb9983b94e058c9f0c38bc226b9b895eb554d17446b" +
"672e12c7e2c36683807cd1e8d67ada0f7"
)
assertEquals(80, b1.size)
assertContentEquals(expected, b1)
assertContentEquals(b1, b2)
assertFalse { b1 contentEquals b3 }
assertFalse { b1 contentEquals b4 }
}
@Test
fun hkdfParametersCompareArraysByContentTest() = runTest {
initCrypto()
val k1 = KDF.HKDF(
Hash.Sha3_384,
"salt".encodeToUByteArray(),
"info".encodeToUByteArray(),
42
)
val k2 = KDF.HKDF(
Hash.Sha3_384,
"salt".encodeToUByteArray(),
"info".encodeToUByteArray(),
42
)
assertEquals(k1, k2)
assertEquals(k1.hashCode(), k2.hashCode())
}
@Test
fun hkdfRejectsInvalidParametersTest() = runTest {
initCrypto()
assertThrows<IllegalArgumentException> {
KDF.HKDF(Hash.Sha3_256, keySize = 0)
}
assertThrows<IllegalArgumentException> {
KDF.HKDF(Hash.Sha3AndBlake, keySize = 32)
}
assertThrows<IllegalArgumentException> {
KDF.HKDF(Hash.Sha3_256, keySize = 32 * 255 + 1)
}
assertThrows<IllegalArgumentException> {
KDF.HKDF(Hash.Sha3_256, keySize = 32).deriveFromBytes(ubyteArrayOf())
}
}
@Test
fun hkdfDoesNotDeriveFromPasswordTest() = runTest {
initCrypto()
val kdf = KDF.HKDF(keySize = 32)
assertThrows<UnsupportedOperationException> {
kdf.deriveKey("password")
}
}
}
private fun hexToUBytes(hex: String): UByteArray {
require(hex.length % 2 == 0) { "hex string should have even length" }
return UByteArray(hex.length / 2) {
hex.substring(it * 2, it * 2 + 2).toInt(16).toUByte()
}
} }
@@ -0,0 +1,60 @@
import kotlinx.coroutines.test.runTest
import net.sergeych.crypto2.SafeKeyExchange
import net.sergeych.crypto2.initCrypto
import kotlin.test.*
class KeyExchangeValidationTest {
@Test
fun rejectsLowOrderPeerKeysOnBothSides() = runTest {
initCrypto()
// u = 0, 1, p-1, p, p+1, including aliases with the ignored high bit set.
val points = listOf(
UByteArray(32),
UByteArray(32).also { it[0] = 1u },
fieldEncoding(0xecu),
fieldEncoding(0xedu),
fieldEncoding(0xeeu),
)
for ((index, point) in points.withIndex()) {
for (highBit in listOf(false, true)) {
val bytes = point.copyOf()
if (highBit) bytes[31] = (bytes[31].toInt() or 0x80).toUByte()
val peer = SafeKeyExchange.PublicKey(bytes)
assertFails("client accepted low-order point $index, highBit=$highBit") {
SafeKeyExchange().clientSessionKey(peer)
}
assertFails("server accepted low-order point $index, highBit=$highBit") {
SafeKeyExchange().serverSessionKey(peer)
}
}
}
}
@Test
fun rejectsWrongLengthBeforeCallingNativeCode() = runTest {
initCrypto()
val valid = SafeKeyExchange().publicKey.keyBytes
for (size in listOf(0, 1, 31, 33, 64)) {
val peer = SafeKeyExchange.PublicKey(valid.copyOf(size))
assertFailsWith<IllegalArgumentException> { SafeKeyExchange().clientSessionKey(peer) }
assertFailsWith<IllegalArgumentException> { SafeKeyExchange().serverSessionKey(peer) }
}
}
@Test
fun validPeersStillAgreeInBothDirections() = runTest {
initCrypto()
val client = SafeKeyExchange()
val server = SafeKeyExchange()
val c = client.clientSessionKey(server.publicKey)
val s = server.serverSessionKey(client.publicKey)
assertContentEquals(c.sessionTag, s.sessionTag)
assertEquals("client", s.decryptString(c.encrypt("client")))
assertEquals("server", c.decryptString(s.encrypt("server")))
}
private fun fieldEncoding(first: UByte) = UByteArray(32) { 0xffu }.also {
it[0] = first
it[31] = 0x7fu
}
}
+22
View File
@@ -241,6 +241,28 @@ class KeysTest {
assertContentEquals(clientSessionKey.sessionTag, serverSessionKey.sessionTag) assertContentEquals(clientSessionKey.sessionTag, serverSessionKey.sessionTag)
} }
@Test
fun sessionKeySerializationTest() = runTest {
initCrypto()
val ske = SafeKeyExchange()
val cke = SafeKeyExchange()
val clientSessionKey = cke.clientSessionKey(ske.publicKey)
val serverSessionKey = ske.serverSessionKey(cke.publicKey)
val restoredClientSessionKey = unpack<SafeKeyExchange.SessionKey>(pack(clientSessionKey))
val restoredServerSessionKey = unpack<SafeKeyExchange.SessionKey>(pack(serverSessionKey))
assertEquals(clientSessionKey, restoredClientSessionKey)
assertEquals(serverSessionKey, restoredServerSessionKey)
assertContentEquals(clientSessionKey.sessionTag, restoredClientSessionKey.sessionTag)
assertContentEquals(serverSessionKey.sessionTag, restoredServerSessionKey.sessionTag)
val src = "Hello from restored session keys!"
assertEquals(src, restoredServerSessionKey.decryptString(restoredClientSessionKey.encrypt(src)))
assertEquals(src, restoredClientSessionKey.decryptString(restoredServerSessionKey.encrypt(src)))
}
@Test @Test
fun asymmetricKeyTest() = runTest { fun asymmetricKeyTest() = runTest {
initCrypto() initCrypto()