Compare commits
5
Commits
2d55af4e3b
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
70d7a13fc3 | ||
|
|
66254f8fa6 | ||
|
|
84a3e82216 | ||
|
|
d402afe1bd | ||
|
|
ff494ab4ef |
No files matched your search
Generated
+1
@@ -1,3 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="FrameworkDetectionExcludesConfiguration">
|
||||
|
||||
@@ -110,6 +110,10 @@ Keys could be associated with tags. Keyrings are used primarily to store keys in
|
||||
|
||||
Using very strong Argon_v2id, and adjustable complexity. Allows storing password key derivation parameters (included in the generated symmetric keys) to re-derive keys later, allows multiple keys derivation. All structures meant to be stored are serializable.
|
||||
|
||||
KDF convenience constructors accept salt bytes directly. When the provided salt is not exactly the Argon salt size, it is deterministically normalized with `Hash.Blake2b.deriveSaltFormBytes(...)` before the KDF is created; exact-size salts are used as is.
|
||||
|
||||
`KDF.deriveFromBytes(source)` derives exactly the configured KDF key size. Create the KDF with the required key size first, for example through `KDF.createDefault(...)` or `Complexity.kdfForSizeInBytes(...)`.
|
||||
|
||||
## Unified keys hierarchy
|
||||
|
||||
Allows the application code to use proper key abstraction and work with more key types in the future, e.g. `SigningKey`, `VerifyingKey`, `EncryptingKey` and `DecryptingKey`. Effective key generation and random byte sequence producers.
|
||||
|
||||
@@ -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.
|
||||
@@ -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
@@ -13,14 +13,14 @@ import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
|
||||
plugins {
|
||||
kotlin("multiplatform") version "2.2.21"
|
||||
id("org.jetbrains.kotlin.plugin.serialization") version "2.2.21"
|
||||
kotlin("multiplatform") version "2.4.0"
|
||||
id("org.jetbrains.kotlin.plugin.serialization") version "2.4.0"
|
||||
id("org.jetbrains.dokka") version "1.9.20"
|
||||
`maven-publish`
|
||||
}
|
||||
|
||||
group = "net.sergeych"
|
||||
version = "0.9.2-SNAPSHOT"
|
||||
version = "0.9.6-SNAPSHOT"
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
|
||||
@@ -155,15 +155,9 @@ sealed class Container {
|
||||
abstract val decryptedWithKeyId: KeyId?
|
||||
|
||||
/**
|
||||
* If the container _is decrypted by the [EncryptingPublicKey]_, e.g., using secret key encryption,
|
||||
* 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.
|
||||
* When the container is decrypted, the key that unlocked it, otherwise null.
|
||||
*/
|
||||
@Transient
|
||||
var authorisedByKey: EncryptingPublicKey? = null
|
||||
protected set
|
||||
abstract val decryptedWithKey: UniversalKey?
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
|
||||
@Transient
|
||||
private var decryptedWithKey: DecryptingKey? = null
|
||||
override var decryptedWithKey: UniversalKey? = null
|
||||
private set
|
||||
|
||||
override val decryptedWithKeyId: KeyId?
|
||||
get() = decryptedWithKey?.id
|
||||
@@ -202,10 +197,7 @@ sealed class Container {
|
||||
if (k.id == keyId) {
|
||||
kotlin.runCatching { k.decrypt(encryptedMessage) }.getOrNull()?.let {
|
||||
decryptedData = it
|
||||
decryptedWithKey = k
|
||||
if(k is DecryptingSecretKey) {
|
||||
authorisedByKey = Asymmetric.Message.decode(encryptedMessage).senderPublicKey
|
||||
}
|
||||
decryptedWithKey = k as UniversalKey
|
||||
return it
|
||||
}
|
||||
}
|
||||
@@ -284,9 +276,12 @@ sealed class Container {
|
||||
}
|
||||
|
||||
@Transient
|
||||
override var decryptedWithKeyId: KeyId? = null
|
||||
override var decryptedWithKey: UniversalKey? = null
|
||||
private set
|
||||
|
||||
override val decryptedWithKeyId: KeyId?
|
||||
get() = decryptedWithKey?.id
|
||||
|
||||
override val keyIds: List<KeyId> = encryptedKeys.map { it.tag }
|
||||
|
||||
override fun decryptWith(keyRing: UniversalRing): UByteArray? {
|
||||
@@ -302,11 +297,8 @@ sealed class Container {
|
||||
}.getOrNull()?.let { k ->
|
||||
if (kotlin.runCatching { decryptedData = k.decrypt(encryptedMessage) }.isFailure)
|
||||
throw InvalidContainerException()
|
||||
decryptedWithKeyId = key.id
|
||||
decryptedWithKey = key as UniversalKey
|
||||
mainKey = k
|
||||
if(key is DecryptingSecretKey) {
|
||||
authorisedByKey = Asymmetric.Message.decode(encryptedKey.cipherData).senderPublicKey
|
||||
}
|
||||
}
|
||||
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))
|
||||
}
|
||||
@@ -129,27 +129,41 @@ enum class Hash(
|
||||
* strong to brute force, but it is good when you just need to get a deterministic salt of arbitrary size.
|
||||
*
|
||||
* _Note that deriving salt of sizes less than hash block will reduce hash strength and should not be allowed
|
||||
* in situation where strength is of concern while extending its length above hash block size does not improve
|
||||
* in a situation where strength is of concern while extending its length above hash block size does not improve
|
||||
* it_. The only reason to use this function is when the desired _salt size_ is not equal to block size, or
|
||||
* not known beforehand.1
|
||||
* not known beforehand.
|
||||
*
|
||||
* To get a cryptographically safe (more or less) key from password use [KDF] classes, or [KDF.deriveKey]
|
||||
* and [KDF.deriveMultipleKeys].
|
||||
*/
|
||||
fun deriveSalt(base: String, sizeInBytes: Int): UByteArray {
|
||||
fun deriveSalt(base: String, sizeInBytes: Int): UByteArray =
|
||||
deriveSaltFromBytes(base.encodeToUByteArray(), sizeInBytes)
|
||||
|
||||
/**
|
||||
* Derive a salt of any size from binary data.
|
||||
*
|
||||
* @see deriveSalt
|
||||
*/
|
||||
fun deriveSaltFromBytes(base: UByteArray, sizeInBytes: Int): UByteArray {
|
||||
require(sizeInBytes > 0)
|
||||
val result = mutableListOf<UByte>()
|
||||
var round = 0
|
||||
var src = base.encodeToUByteArray()
|
||||
var src = base
|
||||
do {
|
||||
src = "rnd_${round++}_".encodeToUByteArray() + src
|
||||
val hash = digest(src)
|
||||
if (result.size + hash.size <= sizeInBytes) result += hash
|
||||
else result += hash.slice(0..<(sizeInBytes - result.size))
|
||||
else result += hash.copyOf(sizeInBytes - result.size)
|
||||
} while (result.size < sizeInBytes)
|
||||
return result.toUByteArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* Typo-compatible alias for [deriveSaltFromBytes].
|
||||
*/
|
||||
fun deriveSaltFormBytes(base: UByteArray, sizeInBytes: Int): UByteArray =
|
||||
deriveSaltFromBytes(base, sizeInBytes)
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -56,7 +56,8 @@ import net.sergeych.crypto2.Multikey.Companion.someOfMultikeys
|
||||
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
|
||||
|
||||
@@ -96,8 +97,9 @@ sealed class Multikey {
|
||||
) : Multikey() {
|
||||
override fun check(keys: Iterable<VerifyingPublicKey>): Boolean {
|
||||
var matches = 0
|
||||
val matchedKeys = mutableSetOf<VerifyingPublicKey>()
|
||||
for (signer in keys) {
|
||||
if (signer in validKeys) {
|
||||
if (signer in validKeys && matchedKeys.add(signer)) {
|
||||
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_SECRETKEYBYTES
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.SerializationException
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.descriptors.SerialDescriptor
|
||||
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
|
||||
* security level and allow using counters as nonce with no extra precautions.
|
||||
*/
|
||||
@Serializable
|
||||
@Serializable(with = SafeKeyExchange.SessionKeySerializer::class)
|
||||
class SessionKey(
|
||||
val sendingKey: EncryptingKey,
|
||||
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.
|
||||
* 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
|
||||
* but can decrypt what was encrypted with the [serverSessionKey] on the another side.
|
||||
*/
|
||||
fun clientSessionKey(serverPublicKey: PublicKey): SessionKey =
|
||||
KeyExchange.clientSessionKeys(pair.publicKey, pair.secretKey, serverPublicKey.keyBytes)
|
||||
fun clientSessionKey(serverPublicKey: PublicKey): SessionKey {
|
||||
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) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an asymmetric [SessionKey] instance to work with [clientSessionKey] on the other side.
|
||||
* Note that asymmetric means it can't decrypt what it encrypted.
|
||||
*/
|
||||
fun serverSessionKey(clientPublicKey: PublicKey): SessionKey =
|
||||
KeyExchange.serverSessionKeys(pair.publicKey, pair.secretKey, clientPublicKey.keyBytes)
|
||||
fun serverSessionKey(clientPublicKey: PublicKey): SessionKey {
|
||||
requirePeerKeySize(clientPublicKey)
|
||||
return KeyExchange.serverSessionKeys(pair.publicKey, pair.secretKey, clientPublicKey.keyBytes)
|
||||
.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"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -42,22 +42,28 @@ sealed class KDF {
|
||||
/**
|
||||
* Create [KDF] of the corresponding strength suitable to derive [numberOfKeys] symmetric keys.
|
||||
*
|
||||
* Random salt of proper size is used
|
||||
* Random salt of proper size is used by default. If a custom [salt] size is not [Argon.saltSize],
|
||||
* it is deterministically normalized with `Hash.Blake2b.deriveSaltFormBytes(...)`.
|
||||
*/
|
||||
fun kdfForSize(numberOfKeys: Int,salt: UByteArray = Argon.randomSalt()): KDF =
|
||||
creteDefault(SymmetricKey.keyLength * numberOfKeys, this, salt)
|
||||
fun kdfForSize(numberOfKeys: Int, salt: UByteArray = Argon.randomSalt()): KDF =
|
||||
createDefault(SymmetricKey.keyLength * numberOfKeys, this, salt)
|
||||
|
||||
fun kdfForSizeInBytes(sizeInBytes: Int, domain: String): KDF {
|
||||
val salt = Hash.Blake2b.deriveSalt(domain, Argon.saltSize)
|
||||
return creteDefault(sizeInBytes, this, salt)
|
||||
}
|
||||
/**
|
||||
* Create [KDF] for deriving [sizeInBytes] bytes using the provided [salt].
|
||||
*
|
||||
* The [salt] is used as is when its size is [Argon.saltSize]. Otherwise, it is deterministically
|
||||
* normalized with `Hash.Blake2b.deriveSaltFormBytes(...)` to the required size.
|
||||
*/
|
||||
fun kdfForSizeInBytes(sizeInBytes: Int, salt: UByteArray): KDF =
|
||||
createDefault(sizeInBytes, this, salt)
|
||||
|
||||
|
||||
/**
|
||||
* Derive multiple keys from the password. Derivation params will be included in the key ids, see
|
||||
* [SymmetricKey.id] as [KeyId.kdp].
|
||||
|
||||
* Random salt of proper size is used
|
||||
* If the [salt] size is not [Argon.saltSize], it is deterministically normalized with
|
||||
* `Hash.Blake2b.deriveSaltFormBytes(...)`.
|
||||
*
|
||||
* ___Important: symmetric keys do not save key ids___. _Container do it, so it is possible to re-derive
|
||||
* key to open the container, but in many cases you might need to save [KeyId.kdp] separately_.
|
||||
@@ -65,7 +71,7 @@ sealed class KDF {
|
||||
* to change with time.
|
||||
*/
|
||||
@Suppress("unused")
|
||||
fun deriveMultiple(password: String, count: Int,salt: UByteArray): List<SymmetricKey> =
|
||||
fun deriveMultiple(password: String, count: Int, salt: UByteArray): List<SymmetricKey> =
|
||||
kdfForSize(count, salt).deriveMultipleKeys(password, count)
|
||||
|
||||
/**
|
||||
@@ -75,9 +81,12 @@ sealed class KDF {
|
||||
|
||||
/**
|
||||
* Derive bytes from bytes using the default [Argon] KDF with this complexity.
|
||||
*
|
||||
* If the [salt] size is not [Argon.saltSize], it is deterministically normalized with
|
||||
* `Hash.Blake2b.deriveSaltFormBytes(...)`.
|
||||
*/
|
||||
fun derive(source: UByteArray, salt: UByteArray, derivedSize: Int): UByteArray =
|
||||
creteDefault(derivedSize, this, salt).deriveFromBytes(source, derivedSize)
|
||||
createDefault(derivedSize, this, salt).deriveFromBytes(source)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,9 +95,9 @@ sealed class KDF {
|
||||
abstract fun deriveKey(password: String): UByteArray
|
||||
|
||||
/**
|
||||
* Derive bytes from bytes using this KDF parameters.
|
||||
* Derive bytes from bytes using this KDF parameters. The derived byte count is this KDF's configured key size.
|
||||
*/
|
||||
abstract fun deriveFromBytes(source: UByteArray, derivedSize: Int): UByteArray
|
||||
abstract fun deriveFromBytes(source: UByteArray): UByteArray
|
||||
|
||||
/**
|
||||
* Derive keys from lower part of bytes derived from the password. E.g., if generated size is longer than
|
||||
@@ -148,10 +157,9 @@ sealed class KDF {
|
||||
override fun deriveKey(password: String): UByteArray =
|
||||
PasswordHash.pwhash(keySize, password, salt, instructionsComplexity, memComplexity, algorithm.code)
|
||||
|
||||
override fun deriveFromBytes(source: UByteArray, derivedSize: Int): UByteArray {
|
||||
require(derivedSize >= minKeySize) { "The derived size should be at least $minKeySize bytes" }
|
||||
override fun deriveFromBytes(source: UByteArray): UByteArray {
|
||||
return PasswordHash.pwhash(
|
||||
derivedSize,
|
||||
keySize,
|
||||
source.encodeToBase64Url(),
|
||||
salt,
|
||||
instructionsComplexity,
|
||||
@@ -249,11 +257,93 @@ 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 {
|
||||
|
||||
fun creteDefault(keySize: Int, complexity: Complexity, salt: UByteArray = Argon.randomSalt()): KDF {
|
||||
return Argon.create(complexity, salt, keySize)
|
||||
/**
|
||||
* Create default [Argon] KDF parameters. If [salt] is not exactly [Argon.saltSize], it is
|
||||
* deterministically normalized with [Hash.Blake2b.deriveSaltFormBytes] before creating the KDF.
|
||||
*/
|
||||
fun createDefault(keySize: Int, complexity: Complexity, salt: UByteArray = Argon.randomSalt()): KDF {
|
||||
val normalizedSalt = if (salt.size == Argon.saltSize) {
|
||||
salt
|
||||
} else {
|
||||
Hash.Blake2b.deriveSaltFormBytes(salt, Argon.saltSize)
|
||||
}
|
||||
return Argon.create(complexity, normalizedSalt, keySize)
|
||||
}
|
||||
|
||||
@Deprecated("Use createDefault", ReplaceWith("createDefault(keySize, complexity, salt)"))
|
||||
fun creteDefault(keySize: Int, complexity: Complexity, salt: UByteArray = Argon.randomSalt()): KDF =
|
||||
createDefault(keySize, complexity, salt)
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -34,6 +34,8 @@ class ContainerTest {
|
||||
assertNotNull(d)
|
||||
assertContentEquals(data, d)
|
||||
assertTrue { c1.isDecrypted }
|
||||
assertEquals(syk1.id, c1.decryptedWithKeyId)
|
||||
assertEquals(syk1, c1.decryptedWithKey)
|
||||
|
||||
val data2 = "To push unpushinable".encodeToUByteArray()
|
||||
val c2 = Container.decode(c.updateData(data2).encoded)
|
||||
@@ -61,7 +63,7 @@ class ContainerTest {
|
||||
assertContentEquals(data, d)
|
||||
assertTrue { c1.isDecrypted }
|
||||
assertEquals(p2.publicKey.id, c1.decryptedWithKeyId)
|
||||
assertEquals(p1.publicKey, c1.authorisedByKey)
|
||||
assertEquals(p2.secretKey, c1.decryptedWithKey)
|
||||
|
||||
val data2 = "To push unpushinable".encodeToUByteArray()
|
||||
val c2 = Container.decode(c.updateData(data2).encoded)
|
||||
@@ -88,7 +90,7 @@ class ContainerTest {
|
||||
assertContentEquals(data, d)
|
||||
assertTrue { c1.isDecrypted }
|
||||
assertEquals(p4.publicKey.id, c1.decryptedWithKeyId)
|
||||
assertEquals(p1.publicKey, c1.authorisedByKey)
|
||||
assertEquals(p4.secretKey, c1.decryptedWithKey)
|
||||
|
||||
val data2 = "To push unpushinable".encodeToUByteArray()
|
||||
val c2 = Container.decode(c.updateData(data2).encoded)
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -55,15 +55,33 @@ class HashTest {
|
||||
@Test
|
||||
fun deriveSaltTest() = runTest {
|
||||
initCrypto()
|
||||
for( i in 2..257 ) {
|
||||
val x = Hash.Sha3AndBlake.deriveSalt("base one", i)
|
||||
val y = Hash.Sha3AndBlake.deriveSalt("base one", i)
|
||||
val z = Hash.Sha3AndBlake.deriveSalt("base two", i)
|
||||
for (hash in Hash.entries) {
|
||||
for (i in 1..257) {
|
||||
val x = hash.deriveSalt("base one", i)
|
||||
val y = hash.deriveSalt("base one", i)
|
||||
val z = hash.deriveSalt("base two", i)
|
||||
assertContentEquals(x, y)
|
||||
assertFalse { x contentEquals z }
|
||||
assertEquals(x.size, i)
|
||||
assertEquals(y.size, i)
|
||||
assertEquals(z.size, i)
|
||||
if (i > 1) assertFalse { x contentEquals z }
|
||||
assertEquals(i, x.size)
|
||||
assertEquals(i, y.size)
|
||||
assertEquals(i, z.size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deriveSaltFromBytesTest() = runTest {
|
||||
initCrypto()
|
||||
val base = "base one".encodeToByteArray().asUByteArray()
|
||||
for (hash in Hash.entries) {
|
||||
for (i in listOf(1, 5, 31, 32, 33, 96, 97)) {
|
||||
val fromString = hash.deriveSalt("base one", i)
|
||||
val fromBytes = hash.deriveSaltFromBytes(base, i)
|
||||
val fromTypoAlias = hash.deriveSaltFormBytes(base, i)
|
||||
assertEquals(i, fromBytes.size)
|
||||
assertContentEquals(fromString, fromBytes)
|
||||
assertContentEquals(fromBytes, fromTypoAlias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,4 +96,3 @@ suspend fun <T> sw(label: String, f: suspend () -> T): T {
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* real dot sergeych at gmail.
|
||||
*/
|
||||
|
||||
import com.ionspin.kotlin.crypto.util.encodeToUByteArray
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import net.sergeych.crypto2.Hash
|
||||
import net.sergeych.crypto2.KDF
|
||||
@@ -16,7 +17,6 @@ import kotlin.test.Test
|
||||
import kotlin.test.assertContentEquals
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertFailsWith
|
||||
import kotlin.test.assertIs
|
||||
|
||||
class KDFTest {
|
||||
@@ -63,18 +63,34 @@ class KDFTest {
|
||||
fun complexityKdfForSizeInBytesTest() = runTest {
|
||||
initCrypto()
|
||||
val size = KDF.Argon.minKeySize + 17
|
||||
val domain = "kdf-size-in-bytes-test"
|
||||
val expectedSalt = Hash.Blake2b.deriveSalt(domain, KDF.Argon.saltSize)
|
||||
val expectedSalt = UByteArray(KDF.Argon.saltSize) { (it + 3).toUByte() }
|
||||
|
||||
val kdf = KDF.Complexity.FixedLow.kdfForSizeInBytes(size, domain)
|
||||
val kdf = KDF.Complexity.FixedLow.kdfForSizeInBytes(size, expectedSalt)
|
||||
assertIs<KDF.Argon>(kdf)
|
||||
|
||||
assertEquals(KDF.Argon.create(KDF.Complexity.FixedLow, expectedSalt, size), kdf)
|
||||
assertEquals(size, kdf.keySize)
|
||||
assertContentEquals(expectedSalt, kdf.salt)
|
||||
assertFalse {
|
||||
kdf.salt contentEquals Hash.Blake2b.deriveSalt("$domain-other", KDF.Argon.saltSize)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun createDefaultNormalizesSaltTest() = runTest {
|
||||
initCrypto()
|
||||
val size = KDF.Argon.minKeySize + 19
|
||||
val shortSalt = ubyteArrayOf(1u, 2u, 3u, 4u, 5u)
|
||||
val longSalt = UByteArray(KDF.Argon.saltSize + 7) { (it * 5).toUByte() }
|
||||
val expectedShortSalt = Hash.Blake2b.deriveSaltFormBytes(shortSalt, KDF.Argon.saltSize)
|
||||
val expectedLongSalt = Hash.Blake2b.deriveSaltFormBytes(longSalt, KDF.Argon.saltSize)
|
||||
|
||||
val shortKdf = KDF.createDefault(size, KDF.Complexity.FixedLow, shortSalt)
|
||||
val longKdf = KDF.Complexity.FixedLow.kdfForSizeInBytes(size, longSalt)
|
||||
|
||||
assertIs<KDF.Argon>(shortKdf)
|
||||
assertIs<KDF.Argon>(longKdf)
|
||||
assertEquals(KDF.Argon.saltSize, shortKdf.salt.size)
|
||||
assertEquals(KDF.Argon.saltSize, longKdf.salt.size)
|
||||
assertContentEquals(expectedShortSalt, shortKdf.salt)
|
||||
assertContentEquals(expectedLongSalt, longKdf.salt)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -84,9 +100,9 @@ class KDFTest {
|
||||
val kdf = KDF.Argon.create(KDF.Complexity.Interactive, salt, 80)
|
||||
val source = UByteArray(47) { (it * 3).toUByte() }
|
||||
|
||||
val b1 = kdf.deriveFromBytes(source, 80)
|
||||
val b2 = kdf.deriveFromBytes(source, 80)
|
||||
val b3 = kdf.deriveFromBytes(source + 1u, 80)
|
||||
val b1 = kdf.deriveFromBytes(source)
|
||||
val b2 = kdf.deriveFromBytes(source)
|
||||
val b3 = kdf.deriveFromBytes(source + 1u)
|
||||
|
||||
assertEquals(80, b1.size)
|
||||
assertContentEquals(b1, b2)
|
||||
@@ -100,21 +116,102 @@ class KDFTest {
|
||||
val source = UByteArray(23) { (it + 7).toUByte() }
|
||||
|
||||
val b1 = KDF.Complexity.Interactive.derive(source, salt, 64)
|
||||
val b2 = KDF.Argon.create(KDF.Complexity.Interactive, salt, 64).deriveFromBytes(source, 64)
|
||||
val b2 = KDF.Argon.create(KDF.Complexity.Interactive, salt, 64).deriveFromBytes(source)
|
||||
|
||||
assertContentEquals(b1, b2)
|
||||
assertEquals(64, b1.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deriveFromBytesValidationTest() = runTest {
|
||||
fun deriveFromBytesUsesKeySizeTest() = runTest {
|
||||
initCrypto()
|
||||
val salt = UByteArray(KDF.Argon.saltSize) { it.toUByte() }
|
||||
val kdf = KDF.Argon.create(KDF.Complexity.Interactive, salt, KDF.Argon.minKeySize)
|
||||
val source = ubyteArrayOf(1u, 2u, 3u)
|
||||
val shortKdf = KDF.Argon.create(KDF.Complexity.Interactive, salt, 64)
|
||||
val longKdf = KDF.Argon.create(KDF.Complexity.Interactive, salt, 96)
|
||||
|
||||
assertFailsWith<IllegalArgumentException> {
|
||||
kdf.deriveFromBytes(ubyteArrayOf(1u, 2u, 3u), KDF.Argon.minKeySize - 1)
|
||||
assertEquals(64, shortKdf.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
|
||||
}
|
||||
}
|
||||
@@ -241,6 +241,28 @@ class KeysTest {
|
||||
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
|
||||
fun asymmetricKeyTest() = runTest {
|
||||
initCrypto()
|
||||
|
||||
Reference in new issue
Block a user