From 1dbf1a3e64e874a35aab6a9832961a97de4f765c Mon Sep 17 00:00:00 2001 From: Andrey Pfau Date: Wed, 1 Feb 2023 20:04:04 +0300 Subject: [PATCH] Full cross-platform crypto implementation --- README.md | 2 +- build.gradle.kts | 2 +- libs.versions.toml | 1 - .../org/ton/adnl/connection/AdnlConnection.kt | 9 +- .../kotlin/org/ton/block/VmStackValue.kt | 2 +- .../kotlin/org/ton/cell/CellImpl.kt | 2 +- ton-kotlin-crypto/build.gradle.kts | 5 - ton-kotlin-crypto/common/src/AesCtr.kt | 2 + ton-kotlin-crypto/common/src/Sha256.kt | 16 - ton-kotlin-crypto/common/src/digest/Digest.kt | 28 + .../common/src/digest/md4/GeneralDigest.kt | 74 + .../common/src/digest/sha2/LongDigest.kt | 236 ++ .../common/src/digest/sha2/SHA256Digest.kt | 212 ++ .../common/src/digest/sha2/SHA512Digest.kt | 62 + ton-kotlin-crypto/common/src/hmac.kt | 3 - .../common/src/kdf/PBEParametersGenerator.kt | 26 + .../src/kdf/PKCSS2ParametersGenerator.kt | 72 + ton-kotlin-crypto/common/src/mac/Mac.kt | 22 + ton-kotlin-crypto/common/src/mac/hmac/HMac.kt | 79 + ton-kotlin-crypto/common/src/pbkdf2.kt | 3 - ton-kotlin-crypto/darwin/src/Sha256.kt | 33 - ton-kotlin-crypto/jvm/src/Sha256.kt | 18 - ton-kotlin-crypto/jvm/src/digest/DigestJvm.kt | 32 + ton-kotlin-crypto/jvm/src/hmac.kt | 15 - ton-kotlin-crypto/jvm/src/pbkdf.kt | 13 - ton-kotlin-crypto/jvm/test/hmacSha512.kt | 22 + ton-kotlin-crypto/linux/src/Sha256.kt | 15 - ton-kotlin-crypto/mingw/src/Sha256.kt | 15 - ton-kotlin-crypto/native/src/digest/Digest.kt | 18 + ton-kotlin-crypto/native/src/hmacSha512.kt | 5 - .../native/src/internal/Sha256.kt | 155 -- ton-kotlin-crypto/native/src/pbkdf2Sha512.kt | 5 - .../src/jvmTest/kotlin/TestDict.kt | 24 - .../kotlin/org/ton/lite/client/LiteClient.kt | 2 +- .../kotlin/org/ton/mnemonic/Mnemonic.kt | 2113 +---------------- .../org/ton/mnemonic/MnemonicWordList.kt | 2052 ++++++++++++++++ .../kotlin/org/ton/mnemonic/MnemonicTest.kt | 2 +- .../commonMain/kotlin/org/ton/tl/TlEncoder.kt | 2 +- 38 files changed, 2992 insertions(+), 2407 deletions(-) delete mode 100644 ton-kotlin-crypto/common/src/Sha256.kt create mode 100644 ton-kotlin-crypto/common/src/digest/Digest.kt create mode 100644 ton-kotlin-crypto/common/src/digest/md4/GeneralDigest.kt create mode 100644 ton-kotlin-crypto/common/src/digest/sha2/LongDigest.kt create mode 100644 ton-kotlin-crypto/common/src/digest/sha2/SHA256Digest.kt create mode 100644 ton-kotlin-crypto/common/src/digest/sha2/SHA512Digest.kt delete mode 100644 ton-kotlin-crypto/common/src/hmac.kt create mode 100644 ton-kotlin-crypto/common/src/kdf/PBEParametersGenerator.kt create mode 100644 ton-kotlin-crypto/common/src/kdf/PKCSS2ParametersGenerator.kt create mode 100644 ton-kotlin-crypto/common/src/mac/Mac.kt create mode 100644 ton-kotlin-crypto/common/src/mac/hmac/HMac.kt delete mode 100644 ton-kotlin-crypto/common/src/pbkdf2.kt delete mode 100644 ton-kotlin-crypto/darwin/src/Sha256.kt delete mode 100644 ton-kotlin-crypto/jvm/src/Sha256.kt create mode 100644 ton-kotlin-crypto/jvm/src/digest/DigestJvm.kt delete mode 100644 ton-kotlin-crypto/jvm/src/hmac.kt delete mode 100644 ton-kotlin-crypto/jvm/src/pbkdf.kt create mode 100644 ton-kotlin-crypto/jvm/test/hmacSha512.kt delete mode 100644 ton-kotlin-crypto/linux/src/Sha256.kt delete mode 100644 ton-kotlin-crypto/mingw/src/Sha256.kt create mode 100644 ton-kotlin-crypto/native/src/digest/Digest.kt delete mode 100644 ton-kotlin-crypto/native/src/hmacSha512.kt delete mode 100644 ton-kotlin-crypto/native/src/internal/Sha256.kt delete mode 100644 ton-kotlin-crypto/native/src/pbkdf2Sha512.kt delete mode 100644 ton-kotlin-hashmap/src/jvmTest/kotlin/TestDict.kt create mode 100644 ton-kotlin-mnemonic/src/commonMain/kotlin/org/ton/mnemonic/MnemonicWordList.kt diff --git a/README.md b/README.md index 12f3c603..50e18bbd 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ ```kotlin dependencies { - implementation("org.ton:ton-kotlin:0.2.8") + implementation("org.ton:ton-kotlin:0.2.9") } ``` diff --git a/build.gradle.kts b/build.gradle.kts index 0ef403d8..d21ee6b0 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -17,7 +17,7 @@ val isCI = System.getenv("CI") == "true" allprojects { group = "org.ton" - version = "0.2.8" + version = "0.2.9" apply(plugin = "kotlin-multiplatform") apply(plugin = "kotlinx-serialization") diff --git a/libs.versions.toml b/libs.versions.toml index 4093ef54..c70c61af 100644 --- a/libs.versions.toml +++ b/libs.versions.toml @@ -25,6 +25,5 @@ ktor-client-cio = { module = "io.ktor:ktor-client-cio", version.ref = "ktor" } ktor-server-cio = { module = "io.ktor:ktor-server-cio", version.ref = "ktor" } ktor-network = { module = "io.ktor:ktor-network", version.ref = "ktor" } ktor-utils = { module = "io.ktor:ktor-utils", version.ref = "ktor" } -bouncycastle = { module = "org.bouncycastle:bcprov-jdk15on", version.ref = "bouncycastle" } curve25519 = { module = "io.github.andreypfau:curve25519-kotlin", version.ref = "curve25519" } mockk = { module = "io.mockk:mockk", version.ref = "mockk" } diff --git a/ton-kotlin-adnl/src/commonMain/kotlin/org/ton/adnl/connection/AdnlConnection.kt b/ton-kotlin-adnl/src/commonMain/kotlin/org/ton/adnl/connection/AdnlConnection.kt index a4f598b3..be9eb600 100644 --- a/ton-kotlin-adnl/src/commonMain/kotlin/org/ton/adnl/connection/AdnlConnection.kt +++ b/ton-kotlin-adnl/src/commonMain/kotlin/org/ton/adnl/connection/AdnlConnection.kt @@ -1,5 +1,6 @@ package org.ton.adnl.connection +import io.ktor.util.* import io.ktor.utils.io.* import io.ktor.utils.io.core.* import io.ktor.utils.io.errors.* @@ -12,7 +13,8 @@ import org.ton.adnl.network.TcpClient import org.ton.api.liteserver.LiteServerDesc import org.ton.crypto.AesCtr import org.ton.crypto.SecureRandom -import org.ton.crypto.sha256 +import org.ton.crypto.digest.Digest +import org.ton.crypto.digest.sha256 import kotlin.coroutines.CoroutineContext import kotlin.time.Duration import kotlin.time.Duration.Companion.ZERO @@ -175,7 +177,10 @@ public class AdnlConnection( require(dataSize in 32..(1 shl 24)) { "Invalid packet size: $dataSize" } val nonce = SecureRandom.nextBytes(32) val payload = packet.readBytes() - val hash = sha256(nonce, payload) + val hash = Digest.sha256().apply { + update(nonce) + update(payload) + }.build() val data = buildPacket { writeIntLittleEndian(dataSize) writeFully(nonce) diff --git a/ton-kotlin-block/src/commonTest/kotlin/org/ton/block/VmStackValue.kt b/ton-kotlin-block/src/commonTest/kotlin/org/ton/block/VmStackValue.kt index af579c01..e5f67e76 100644 --- a/ton-kotlin-block/src/commonTest/kotlin/org/ton/block/VmStackValue.kt +++ b/ton-kotlin-block/src/commonTest/kotlin/org/ton/block/VmStackValue.kt @@ -11,7 +11,7 @@ class VmStackValueTest { val codec = VmStackValue.tlbCombinator() @Test - fun `test VmStackValue (de)serialization`() { + fun `test VmStackValue deserialization`() { testSerialization(codec, VmStackNull) diff --git a/ton-kotlin-cell/src/commonMain/kotlin/org/ton/cell/CellImpl.kt b/ton-kotlin-cell/src/commonMain/kotlin/org/ton/cell/CellImpl.kt index c7a736f0..aef25656 100644 --- a/ton-kotlin-cell/src/commonMain/kotlin/org/ton/cell/CellImpl.kt +++ b/ton-kotlin-cell/src/commonMain/kotlin/org/ton/cell/CellImpl.kt @@ -5,8 +5,8 @@ import org.ton.cell.Cell.Companion.DEPTH_BYTES import org.ton.cell.Cell.Companion.HASH_BYTES import org.ton.cell.Cell.Companion.getBitsDescriptor import org.ton.cell.Cell.Companion.getRefsDescriptor +import org.ton.crypto.digest.sha256 import org.ton.crypto.encodeHex -import org.ton.crypto.sha256 import kotlin.jvm.JvmStatic import kotlin.math.max diff --git a/ton-kotlin-crypto/build.gradle.kts b/ton-kotlin-crypto/build.gradle.kts index 14edb836..183764ad 100644 --- a/ton-kotlin-crypto/build.gradle.kts +++ b/ton-kotlin-crypto/build.gradle.kts @@ -17,11 +17,6 @@ kotlin { implementation(kotlin("test")) } } - val jvmMain by getting { - dependencies { - implementation(libs.bouncycastle) - } - } val nativeMain by getting { dependencies { api(libs.serialization.core) diff --git a/ton-kotlin-crypto/common/src/AesCtr.kt b/ton-kotlin-crypto/common/src/AesCtr.kt index 74591817..98c39bf0 100644 --- a/ton-kotlin-crypto/common/src/AesCtr.kt +++ b/ton-kotlin-crypto/common/src/AesCtr.kt @@ -1,5 +1,7 @@ package org.ton.crypto +import org.ton.crypto.digest.sha256 + public expect class AesCtr(key: ByteArray, iv: ByteArray) { public fun update(input: ByteArray, output: ByteArray = ByteArray(input.size)): ByteArray public fun doFinal(output: ByteArray): ByteArray diff --git a/ton-kotlin-crypto/common/src/Sha256.kt b/ton-kotlin-crypto/common/src/Sha256.kt deleted file mode 100644 index 334f459f..00000000 --- a/ton-kotlin-crypto/common/src/Sha256.kt +++ /dev/null @@ -1,16 +0,0 @@ -package org.ton.crypto - -public fun Sha256.digest(): ByteArray = digest(ByteArray(32)) - -public fun sha256(vararg bytes: ByteArray): ByteArray { - val sha256 = Sha256() - bytes.forEach { - sha256.update(it) - } - return sha256.digest() -} - -public expect class Sha256 constructor() { - public fun update(bytes: ByteArray): Sha256 - public fun digest(output: ByteArray): ByteArray -} diff --git a/ton-kotlin-crypto/common/src/digest/Digest.kt b/ton-kotlin-crypto/common/src/digest/Digest.kt new file mode 100644 index 00000000..6c66f318 --- /dev/null +++ b/ton-kotlin-crypto/common/src/digest/Digest.kt @@ -0,0 +1,28 @@ +package org.ton.crypto.digest + +public interface Digest { + public val algorithmName: String + public val digestSize: Int + + public fun update(input: ByteArray): Unit = update(input, 0, input.size) + public fun update(input: ByteArray, offset: Int, length: Int) + + public operator fun plusAssign(input: ByteArray): Unit = update(input) + + public fun build(): ByteArray = build(ByteArray(digestSize)) + public fun build(output: ByteArray): ByteArray = build(output, 0) + public fun build(output: ByteArray, offset: Int): ByteArray + + public fun reset() + + public companion object { + public fun sha256(): Digest = Digest("SHA-256") + public fun sha512(): Digest = Digest("SHA-512") + } +} + +public expect fun Digest(algorithm: String): Digest + +public expect fun sha256(bytes: ByteArray): ByteArray + +public expect fun sha512(bytes: ByteArray): ByteArray diff --git a/ton-kotlin-crypto/common/src/digest/md4/GeneralDigest.kt b/ton-kotlin-crypto/common/src/digest/md4/GeneralDigest.kt new file mode 100644 index 00000000..2e4867bc --- /dev/null +++ b/ton-kotlin-crypto/common/src/digest/md4/GeneralDigest.kt @@ -0,0 +1,74 @@ +package org.ton.crypto.digest.md4 + +import org.ton.crypto.digest.Digest + +/** + * base implementation of MD4 family style digest as outlined in "Handbook of Applied Cryptography", + * pages 344 - 347. + */ +public abstract class GeneralDigest : Digest { + private val xBuf = ByteArray(4) + private var xBuffOff = 0 + private var byteCount = 0 + + public fun update(input: Byte) { + xBuf[xBuffOff++] = input + if (xBuffOff == xBuf.size) { + processWord(xBuf, 0) + xBuffOff = 0 + } + byteCount++ + } + + public override fun update(input: ByteArray, offset: Int, length: Int) { + // fill the current word + var i = 0 + if (xBuffOff != 0) { + while (i < length) { + xBuf[xBuffOff++] = input[offset + i++] + if (xBuffOff == 4) { + processWord(xBuf, 0) + xBuffOff = 0 + break + } + } + } + + // process whole words. + val limit = ((length - i) and 3.inv()) + i + while (i < limit) { + processWord(input, offset + i) + i += 4 + } + + // load in the remainder. + while (i < length) { + xBuf[xBuffOff++] = input[offset + i++] + } + + byteCount += length + } + + public fun finish() { + val bitLength = byteCount.toLong() shl 3 + + // add the pad bytes. + update(128.toByte()) + + while (xBuffOff != 0) { + update(0.toByte()) + } + processLength(bitLength) + processBlock() + } + + override fun reset() { + byteCount = 0 + xBuffOff = 0 + xBuf.fill(0) + } + + protected abstract fun processWord(input: ByteArray, offset: Int) + protected abstract fun processLength(bitLength: Long) + protected abstract fun processBlock() +} diff --git a/ton-kotlin-crypto/common/src/digest/sha2/LongDigest.kt b/ton-kotlin-crypto/common/src/digest/sha2/LongDigest.kt new file mode 100644 index 00000000..46f0caeb --- /dev/null +++ b/ton-kotlin-crypto/common/src/digest/sha2/LongDigest.kt @@ -0,0 +1,236 @@ +package org.ton.crypto.digest.sha2 + +import io.ktor.utils.io.bits.* +import org.ton.crypto.digest.* + +/** + * Base class for SHA-384 and SHA-512. + */ +public abstract class LongDigest : Digest { + private val xBuf = ByteArray(8) + private var xBufOff: Int = 0 + private var byteCount1: Long = 0 + private var byteCount2: Long = 0 + private val w = LongArray(80) + private var wOff = 0 + + protected var h1: Long = 0L + protected var h2: Long = 0L + protected var h3: Long = 0L + protected var h4: Long = 0L + protected var h5: Long = 0L + protected var h6: Long = 0L + protected var h7: Long = 0L + protected var h8: Long = 0L + + public fun update(input: Byte) { + xBuf[xBufOff++] = input + if (xBufOff == xBuf.size) { + processWord(xBuf, 0) + xBufOff = 0 + } + byteCount1++ + } + + override fun update(input: ByteArray, offset: Int, length: Int) { + var inOff = offset + var len = length + + while (xBufOff != 0 && len > 0) { + update(input[inOff]) + inOff++ + len-- + } + + while (len > xBuf.size) { + processWord(input, inOff) + inOff += xBuf.size + len -= xBuf.size + byteCount1 += xBuf.size.toLong() + } + + while (len > 0) { + update(input[inOff]) + inOff++ + len-- + } + } + + public fun finish() { + adjustByteCounts() + + val lowBitLength = byteCount1 shl 3 + val hiBitLength = byteCount2 + + update(0x80.toByte()) + + while (xBufOff != 0) { + update(0.toByte()) + } + + processLength(lowBitLength, hiBitLength) + processBlock() + } + + override fun reset() { + byteCount1 = 0 + byteCount2 = 0 + xBufOff = 0 + xBuf.fill(0) + wOff = 0 + w.fill(0) + } + + protected fun processWord(input: ByteArray, inOff: Int) { + var n = input[inOff].toLong() shl 56 + n = n or ((input[inOff + 1].toLong() and 0xFF) shl 48) + n = n or ((input[inOff + 2].toLong() and 0xFF) shl 40) + n = n or ((input[inOff + 3].toLong() and 0xFF) shl 32) + n = n or ((input[inOff + 4].toLong() and 0xFF) shl 24) + n = n or ((input[inOff + 5].toLong() and 0xFF) shl 16) + n = n or ((input[inOff + 6].toLong() and 0xFF) shl 8) + n = n or (input[inOff + 7].toLong() and 0xFF) + w[wOff] = n + if (++wOff == 16) { + processBlock() + } + } + + protected fun adjustByteCounts() { + if (byteCount1 > 0x1fffffffffffffffL) { + byteCount2 += byteCount1 ushr 61 + byteCount1 = byteCount1 and 0x1fffffffffffffffL + } + } + + protected fun processLength( + lowW: Long, + hiW: Long + ) { + if (wOff > 14) { + processBlock() + } + + w[14] = hiW + w[15] = lowW + } + + protected fun processBlock() { + adjustByteCounts() + + // + // expand 16 word block into 80 word blocks. + // + for (t in 16 until 80) { + w[t] = w[t - 2].sigma1() + w[t - 7] + w[t - 15].sigma0() + w[t - 16] + } + + var a = h1 + var b = h2 + var c = h3 + var d = h4 + var e = h5 + var f = h6 + var g = h7 + var h = h8 + + var t = 0 + for (i in 0 until 10) { + // t = 8 * i + h += Sum1(e) + ch(e, f, g) + k[t] + w[t++] + d += h + h += Sum0(a) + Maj(a, b, c) + + // t = 8 * i + 1 + g += Sum1(d) + ch(d, e, f) + k[t] + w[t++] + c += g + g += Sum0(h) + Maj(h, a, b) + + // t = 8 * i + 2 + f += Sum1(c) + ch(c, d, e) + k[t] + w[t++] + b += f + f += Sum0(g) + Maj(g, h, a) + + // t = 8 * i + 3 + e += Sum1(b) + ch(b, c, d) + k[t] + w[t++] + a += e + e += Sum0(f) + Maj(f, g, h) + + // t = 8 * i + 4 + d += Sum1(a) + ch(a, b, c) + k[t] + w[t++] + h += d + d += Sum0(e) + Maj(e, f, g) + + // t = 8 * i + 5 + c += Sum1(h) + ch(h, a, b) + k[t] + w[t++] + g += c + c += Sum0(d) + Maj(d, e, f) + + // t = 8 * i + 6 + b += Sum1(g) + ch(g, h, a) + k[t] + w[t++] + f += b + b += Sum0(c) + Maj(c, d, e) + + // t = 8 * i + 7 + a += Sum1(f) + ch(f, g, h) + k[t] + w[t++] + e += a + a += Sum0(b) + Maj(b, c, d) + } + + h1 += a + h2 += b + h3 += c + h4 += d + h5 += e + h6 += f + h7 += g + h8 += h + + wOff = 0 + w.fill(0, 0, 16) + } +} + +private fun ch(x: Long, y: Long, z: Long): Long = (x and y) xor (x.inv() and z) + +private fun Maj(x: Long, y: Long, z: Long): Long = (x and y) or (x and z) or (y and z) + +private fun Sum0(x: Long): Long = + ((x shl 36) or (x ushr 28)) xor ((x shl 30) or (x ushr 34)) xor ((x shl 25) or (x ushr 39)) + +private fun Sum1(x: Long): Long = + ((x shl 50) or (x ushr 14)) xor ((x shl 46) or (x ushr 18)) xor ((x shl 23) or (x ushr 41)) + +private fun Long.sigma0(): Long = + ((this shl 63) or (this ushr 1)) xor ((this shl 56) or (this ushr 8)) xor (this ushr 7) + +private fun Long.sigma1(): Long = + ((this shl 45) or (this ushr 19)) xor ((this shl 3) or (this ushr 61)) xor (this ushr 6) + +/* SHA-384 and SHA-512 Constants + * (represent the first 64 bits of the fractional parts of the + * cube roots of the first sixty-four prime numbers) + */ +@OptIn(ExperimentalUnsignedTypes::class) +private val k = ulongArrayOf( + 0x428a2f98d728ae22uL, 0x7137449123ef65cduL, 0xb5c0fbcfec4d3b2fuL, 0xe9b5dba58189dbbcuL, + 0x3956c25bf348b538uL, 0x59f111f1b605d019uL, 0x923f82a4af194f9buL, 0xab1c5ed5da6d8118uL, + 0xd807aa98a3030242uL, 0x12835b0145706fbeuL, 0x243185be4ee4b28cuL, 0x550c7dc3d5ffb4e2uL, + 0x72be5d74f27b896fuL, 0x80deb1fe3b1696b1uL, 0x9bdc06a725c71235uL, 0xc19bf174cf692694uL, + 0xe49b69c19ef14ad2uL, 0xefbe4786384f25e3uL, 0x0fc19dc68b8cd5b5uL, 0x240ca1cc77ac9c65uL, + 0x2de92c6f592b0275uL, 0x4a7484aa6ea6e483uL, 0x5cb0a9dcbd41fbd4uL, 0x76f988da831153b5uL, + 0x983e5152ee66dfabuL, 0xa831c66d2db43210uL, 0xb00327c898fb213fuL, 0xbf597fc7beef0ee4uL, + 0xc6e00bf33da88fc2uL, 0xd5a79147930aa725uL, 0x06ca6351e003826fuL, 0x142929670a0e6e70uL, + 0x27b70a8546d22ffcuL, 0x2e1b21385c26c926uL, 0x4d2c6dfc5ac42aeduL, 0x53380d139d95b3dfuL, + 0x650a73548baf63deuL, 0x766a0abb3c77b2a8uL, 0x81c2c92e47edaee6uL, 0x92722c851482353buL, + 0xa2bfe8a14cf10364uL, 0xa81a664bbc423001uL, 0xc24b8b70d0f89791uL, 0xc76c51a30654be30uL, + 0xd192e819d6ef5218uL, 0xd69906245565a910uL, 0xf40e35855771202auL, 0x106aa07032bbd1b8uL, + 0x19a4c116b8d2d0c8uL, 0x1e376c085141ab53uL, 0x2748774cdf8eeb99uL, 0x34b0bcb5e19b48a8uL, + 0x391c0cb3c5c95a63uL, 0x4ed8aa4ae3418acbuL, 0x5b9cca4f7763e373uL, 0x682e6ff3d6b2b8a3uL, + 0x748f82ee5defb2fcuL, 0x78a5636f43172f60uL, 0x84c87814a1f0ab72uL, 0x8cc702081a6439ecuL, + 0x90befffa23631e28uL, 0xa4506cebde82bde9uL, 0xbef9a3f7b2c67915uL, 0xc67178f2e372532buL, + 0xca273eceea26619cuL, 0xd186b8c721c0c207uL, 0xeada7dd6cde0eb1euL, 0xf57d4f7fee6ed178uL, + 0x06f067aa72176fbauL, 0x0a637dc5a2c898a6uL, 0x113f9804bef90daeuL, 0x1b710b35131c471buL, + 0x28db77f523047d84uL, 0x32caab7b40c72493uL, 0x3c9ebe0a15c9bebcuL, 0x431d67c49c100d4cuL, + 0x4cc5d4becb3e42b6uL, 0x597f299cfc657e2auL, 0x5fcb6fab3ad6faecuL, 0x6c44198c4a475817uL +).asLongArray() diff --git a/ton-kotlin-crypto/common/src/digest/sha2/SHA256Digest.kt b/ton-kotlin-crypto/common/src/digest/sha2/SHA256Digest.kt new file mode 100644 index 00000000..4d379ee6 --- /dev/null +++ b/ton-kotlin-crypto/common/src/digest/sha2/SHA256Digest.kt @@ -0,0 +1,212 @@ +package org.ton.crypto.digest.sha2 + +import io.ktor.utils.io.bits.* +import org.ton.crypto.digest.md4.GeneralDigest + +/** + * FIPS 180-2 implementation of SHA-256. + * + * ``` + * block word digest + * SHA-1 512 32 160 + * SHA-256 512 32 256 + * SHA-384 1024 64 384 + * SHA-512 1024 64 512 + */ +public class SHA256Digest : GeneralDigest() { + private var h1 = 0 + private var h2 = 0 + private var h3 = 0 + private var h4 = 0 + private var h5 = 0 + private var h6 = 0 + private var h7 = 0 + private var h8 = 0 + private val x = IntArray(64) + private var xOff = 0 + + init { + reset() + } + + override val algorithmName: String get() = ALGORITHM_NAME + override val digestSize: Int get() = SIZE_BYTES + + override fun build(output: ByteArray, offset: Int): ByteArray { + finish() + + output.useMemory(0, output.size) { + it.storeIntAt(offset, h1) + it.storeIntAt(offset + 4, h2) + it.storeIntAt(offset + 8, h3) + it.storeIntAt(offset + 12, h4) + it.storeIntAt(offset + 16, h5) + it.storeIntAt(offset + 20, h6) + it.storeIntAt(offset + 24, h7) + it.storeIntAt(offset + 28, h8) + } + + reset() + return output + } + + override fun reset() { + super.reset() + + /** + * SHA-256 initial hash value + * The first 32 bits of the fractional parts of the square roots + * of the first eight prime numbers + */ + h1 = 0x6a09e667 + h2 = 0xbb67ae85.toInt() + h3 = 0x3c6ef372 + h4 = 0xa54ff53a.toInt() + h5 = 0x510e527f + h6 = 0x9b05688c.toInt() + h7 = 0x1f83d9ab + h8 = 0x5be0cd19 + + xOff = 0 + x.fill(0) + } + + protected override fun processWord(input: ByteArray, offset: Int) { + var n = input[offset].toInt() shl 24 + n = n or ((input[offset + 1].toInt() and 0xFF) shl 16) + n = n or ((input[offset + 2].toInt() and 0xFF) shl 8) + n = n or (input[offset + 3].toInt() and 0xFF) + x[xOff] = n + if (++xOff == 16) { + processBlock() + } + } + + protected override fun processLength(bitLength: Long) { + if (xOff > 14) { + processBlock() + } + x[14] = (bitLength ushr 32).toInt() + x[15] = (bitLength and 0xffffffff).toInt() + } + + protected override fun processBlock() { + // expand 16 word block into 64 word blocks. + for (t in 16 until 64) { + x[t] = Theta1(x[t - 2]) + x[t - 7] + Theta0(x[t - 15]) + x[t - 16] + } + + // set up working variables. + var a = h1 + var b = h2 + var c = h3 + var d = h4 + var e = h5 + var f = h6 + var g = h7 + var h = h8 + + var t = 0 + for (i in 0 until 8) { + // t = 8 * i + h += Sum1(e) + Ch(e, f, g) + k[t] + x[t] + d += h + h += Sum0(a) + Maj(a, b, c) + ++t + + // t = 8 * i + 1 + g += Sum1(d) + Ch(d, e, f) + k[t] + x[t] + c += g + g += Sum0(h) + Maj(h, a, b) + ++t + + // t = 8 * i + 2 + f += Sum1(c) + Ch(c, d, e) + k[t] + x[t] + b += f + f += Sum0(g) + Maj(g, h, a) + ++t + + // t = 8 * i + 3 + e += Sum1(b) + Ch(b, c, d) + k[t] + x[t] + a += e + e += Sum0(f) + Maj(f, g, h) + ++t + + // t = 8 * i + 4 + d += Sum1(a) + Ch(a, b, c) + k[t] + x[t] + h += d + d += Sum0(e) + Maj(e, f, g) + ++t + + // t = 8 * i + 5 + c += Sum1(h) + Ch(h, a, b) + k[t] + x[t] + g += c + c += Sum0(d) + Maj(d, e, f) + ++t + + // t = 8 * i + 6 + b += Sum1(g) + Ch(g, h, a) + k[t] + x[t] + f += b + b += Sum0(c) + Maj(c, d, e) + ++t + + // t = 8 * i + 7 + a += Sum1(f) + Ch(f, g, h) + k[t] + x[t] + e += a + a += Sum0(b) + Maj(b, c, d) + ++t + } + + h1 += a + h2 += b + h3 += c + h4 += d + h5 += e + h6 += f + h7 += g + h8 += h + + // reset the offset and clean out the word buffer. + xOff = 0 + x.fill(0) + } + + public companion object { + public const val ALGORITHM_NAME: String = "SHA-256" + public const val SIZE_BYTES: Int = 32 + public const val SIZE_BITS: Int = SIZE_BYTES * Byte.SIZE_BITS + } +} + +/** + * SHA-256 Constants + * (represent the first 32 bits of the fractional parts of the + * cube roots of the first sixty-four prime numbers) + */ +@OptIn(ExperimentalUnsignedTypes::class) +private var k = uintArrayOf( + 0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, 0x3956c25bu, 0x59f111f1u, 0x923f82a4u, 0xab1c5ed5u, + 0xd807aa98u, 0x12835b01u, 0x243185beu, 0x550c7dc3u, 0x72be5d74u, 0x80deb1feu, 0x9bdc06a7u, 0xc19bf174u, + 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu, 0x2de92c6fu, 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, + 0x983e5152u, 0xa831c66du, 0xb00327c8u, 0xbf597fc7u, 0xc6e00bf3u, 0xd5a79147u, 0x06ca6351u, 0x14292967u, + 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu, 0x53380d13u, 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u, + 0xa2bfe8a1u, 0xa81a664bu, 0xc24b8b70u, 0xc76c51a3u, 0xd192e819u, 0xd6990624u, 0xf40e3585u, 0x106aa070u, + 0x19a4c116u, 0x1e376c08u, 0x2748774cu, 0x34b0bcb5u, 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu, 0x682e6ff3u, + 0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u, 0x90befffau, 0xa4506cebu, 0xbef9a3f7u, 0xc67178f2u +).asIntArray() + +private fun Ch(x: Int, y: Int, z: Int): Int = (x and y) xor (x.inv() and z) + +private fun Maj(x: Int, y: Int, z: Int): Int = (x and y) xor (x and z) xor (y and z) + +private fun Sum0(x: Int): Int = + ((x ushr 2) or (x shl 30)) xor ((x ushr 13) or (x shl 19)) xor ((x ushr 22) or (x shl 10)) + +private fun Sum1(x: Int): Int = + ((x ushr 6) or (x shl 26)) xor ((x ushr 11) or (x shl 21)) xor ((x ushr 25) or (x shl 7)) + +private fun Theta0(x: Int): Int = + ((x ushr 7) or (x shl 25)) xor ((x ushr 18) or (x shl 14)) xor (x ushr 3) + +private fun Theta1(x: Int): Int = + ((x ushr 17) or (x shl 15)) xor ((x ushr 19) or (x shl 13)) xor (x ushr 10) diff --git a/ton-kotlin-crypto/common/src/digest/sha2/SHA512Digest.kt b/ton-kotlin-crypto/common/src/digest/sha2/SHA512Digest.kt new file mode 100644 index 00000000..061bfb88 --- /dev/null +++ b/ton-kotlin-crypto/common/src/digest/sha2/SHA512Digest.kt @@ -0,0 +1,62 @@ +package org.ton.crypto.digest.sha2 + +import io.ktor.utils.io.bits.* + +/** + * FIPS 180-2 implementation of SHA-512. + * + * ``` + * block word digest + * SHA-1 512 32 160 + * SHA-256 512 32 256 + * SHA-384 1024 64 384 + * SHA-512 1024 64 512 + */ +public class SHA512Digest : LongDigest() { + init { + reset() + } + + override val algorithmName: String get() = ALGORITHM_NAME + override val digestSize: Int get() = SIZE_BYTES + + override fun build(output: ByteArray, offset: Int): ByteArray { + finish() + output.useMemory(0, output.size) { + it.storeLongAt(offset, h1) + it.storeLongAt(offset + 8, h2) + it.storeLongAt(offset + 16, h3) + it.storeLongAt(offset + 24, h4) + it.storeLongAt(offset + 32, h5) + it.storeLongAt(offset + 40, h6) + it.storeLongAt(offset + 48, h7) + it.storeLongAt(offset + 56, h8) + } + reset() + return output + } + + override fun reset() { + super.reset() + + /* + SHA-512 initial hash value + The first 64 bits of the fractional parts of the square roots + of the first eight prime numbers + */ + h1 = 0x6a09e667f3bcc908L + h2 = 0xbb67ae8584caa73buL.toLong() + h3 = 0x3c6ef372fe94f82bL + h4 = 0xa54ff53a5f1d36f1uL.toLong() + h5 = 0x510e527fade682d1L + h6 = 0x9b05688c2b3e6c1fuL.toLong() + h7 = 0x1f83d9abfb41bd6bL + h8 = 0x5be0cd19137e2179L + } + + public companion object { + public const val ALGORITHM_NAME: String = "SHA-512" + public const val SIZE_BYTES: Int = 64 + public const val SIZE_BITS: Int = SIZE_BYTES * Byte.SIZE_BITS + } +} diff --git a/ton-kotlin-crypto/common/src/hmac.kt b/ton-kotlin-crypto/common/src/hmac.kt deleted file mode 100644 index ea8d042f..00000000 --- a/ton-kotlin-crypto/common/src/hmac.kt +++ /dev/null @@ -1,3 +0,0 @@ -package org.ton.crypto - -public expect fun hmacSha512(key: ByteArray, input: ByteArray): ByteArray diff --git a/ton-kotlin-crypto/common/src/kdf/PBEParametersGenerator.kt b/ton-kotlin-crypto/common/src/kdf/PBEParametersGenerator.kt new file mode 100644 index 00000000..dd76c9a5 --- /dev/null +++ b/ton-kotlin-crypto/common/src/kdf/PBEParametersGenerator.kt @@ -0,0 +1,26 @@ +package org.ton.crypto.kdf + +public abstract class PBEParametersGenerator( + password: ByteArray, + salt: ByteArray, + iterationCount: Int +) { + public constructor() : this(ByteArray(0), ByteArray(0), 0) + + public var password: ByteArray =password + protected set + public var salt: ByteArray = salt + protected set + public var iterationCount: Int = iterationCount + protected set + + public fun init(password: ByteArray, salt: ByteArray, iterationCount: Int): PBEParametersGenerator = apply { + this.password = password + this.salt = salt + this.iterationCount = iterationCount + } + + public abstract fun generateDerivedParameters(keySize: Int): ByteArray + + public abstract fun generateDerivedMacParameters(keySize: Int): ByteArray +} diff --git a/ton-kotlin-crypto/common/src/kdf/PKCSS2ParametersGenerator.kt b/ton-kotlin-crypto/common/src/kdf/PKCSS2ParametersGenerator.kt new file mode 100644 index 00000000..04e4b579 --- /dev/null +++ b/ton-kotlin-crypto/common/src/kdf/PKCSS2ParametersGenerator.kt @@ -0,0 +1,72 @@ +package org.ton.crypto.kdf + +import org.ton.crypto.digest.Digest +import org.ton.crypto.mac.hmac.HMac + +public class PKCSS2ParametersGenerator( + private val hMac: HMac, + password: ByteArray, + salt: ByteArray, + iterationCount: Int +) : PBEParametersGenerator(password, salt, iterationCount) { + public constructor(digest: Digest, password: ByteArray, salt: ByteArray, iterationCount: Int) : this( + HMac(digest), + password, + salt, + iterationCount + ) + public constructor(hMac: HMac) : this(hMac, ByteArray(0), ByteArray(0), 0) + public constructor(digest: Digest) : this(digest, ByteArray(0), ByteArray(0), 0) + + private val state = ByteArray(hMac.macSize) + + override fun generateDerivedParameters(keySize: Int): ByteArray = + generateDerivedKey(keySize / 8) + + override fun generateDerivedMacParameters(keySize: Int): ByteArray = + generateDerivedParameters(keySize) + + private fun generateDerivedKey(dkLen: Int): ByteArray { + val hLen = hMac.macSize + val l = (dkLen + hLen - 1) / hLen + val iBuf = ByteArray(4) + val dk = ByteArray(l * hLen) + var outOff = 0 + + hMac.init(password) + for (i in 1..l) { + iBuf[0] = (i ushr 24).toByte() + iBuf[1] = (i ushr 16).toByte() + iBuf[2] = (i ushr 8).toByte() + iBuf[3] = i.toByte() + f(salt, iterationCount, iBuf, dk, outOff) + outOff += hLen + } + + return dk + } + + private fun f( + s: ByteArray, + c: Int, + iBuf: ByteArray, + output: ByteArray, + outOff: Int + ) { + if (s.isNotEmpty()) { + hMac.update(s) + } + hMac.update(iBuf) + hMac.build(state) + + state.copyInto(output, outOff) + + for (count in 1 until c) { + hMac.update(state) + hMac.build(state) + for (j in state.indices) { + output[outOff + j] = (output[outOff + j].toInt() xor state[j].toInt()).toByte() + } + } + } +} diff --git a/ton-kotlin-crypto/common/src/mac/Mac.kt b/ton-kotlin-crypto/common/src/mac/Mac.kt new file mode 100644 index 00000000..441591d0 --- /dev/null +++ b/ton-kotlin-crypto/common/src/mac/Mac.kt @@ -0,0 +1,22 @@ +package org.ton.crypto.mac + +/** + * The base interface for implementations of message authentication codes (MACs). + */ +public interface Mac { + public val algorithmName: String + public val macSize: Int + + public fun init(key: ByteArray): Mac + + public fun update(input: ByteArray): Unit = update(input, 0, input.size) + public fun update(input: ByteArray, offset: Int, length: Int) + + public operator fun plusAssign(input: ByteArray): Unit = update(input) + + public fun build(): ByteArray = build(ByteArray(macSize)) + public fun build(output: ByteArray): ByteArray = build(output, 0) + public fun build(output: ByteArray, offset: Int): ByteArray + + public fun reset() +} diff --git a/ton-kotlin-crypto/common/src/mac/hmac/HMac.kt b/ton-kotlin-crypto/common/src/mac/hmac/HMac.kt new file mode 100644 index 00000000..79ab68ef --- /dev/null +++ b/ton-kotlin-crypto/common/src/mac/hmac/HMac.kt @@ -0,0 +1,79 @@ +package org.ton.crypto.mac.hmac + +import org.ton.crypto.digest.Digest +import org.ton.crypto.mac.* + +/** + * HMAC implementation based on RFC2104 + * + * H(K XOR opad, H(K XOR ipad, text)) + */ +public class HMac private constructor( + private val digest: Digest, + private val blockLength: Int +) : Mac { + public constructor(digest: Digest) : this(digest, byteLength(digest)) + public constructor(digest: Digest, key: ByteArray) : this(digest) { + init(key) + } + + public override val algorithmName: String get() = "HMAC/${digest.algorithmName}" + public override val macSize: Int get() = digestSize + + private val digestSize = digest.digestSize + private val inputPad = ByteArray(blockLength) + private val outputBuf = ByteArray(blockLength + digestSize) + + public override fun init(key: ByteArray): HMac = apply { + digest.reset() + var keyLength = key.size + + if (keyLength > blockLength) { + digest.update(key) + digest.build(inputPad) + keyLength = digestSize + } else { + key.copyInto(inputPad) + } + + inputPad.fill(0, keyLength, inputPad.size) + inputPad.copyInto(outputBuf) + + xorPad(inputPad, 0, blockLength, IPAD) + xorPad(outputBuf, 0, blockLength, OPAD) + + digest.update(inputPad) + } + + public override fun update(input: ByteArray, offset: Int, length: Int) { + digest.update(input, offset, length) + } + + public override fun build(output: ByteArray, offset: Int): ByteArray = output.apply { + digest.build(outputBuf, blockLength) + digest.update(outputBuf) + digest.build(output, offset) + outputBuf.fill(0, blockLength, outputBuf.size) + digest.update(inputPad) + } + + public override fun reset() { + digest.reset() + digest.update(inputPad) + } +} + +private const val IPAD = 0x36.toByte() +private const val OPAD = 0x5C.toByte() + +private fun byteLength(digest: Digest) = when (digest.algorithmName) { + "SHA-256" -> 64 + "SHA-512" -> 128 + else -> throw IllegalArgumentException("Unsupported digest algorithm: ${digest.algorithmName}") +} + +private fun xorPad(pad: ByteArray, offset: Int, length: Int, value: Byte) { + for (i in offset until offset + length) { + pad[i] = (pad[i].toInt() xor value.toInt()).toByte() + } +} diff --git a/ton-kotlin-crypto/common/src/pbkdf2.kt b/ton-kotlin-crypto/common/src/pbkdf2.kt deleted file mode 100644 index 17f0f073..00000000 --- a/ton-kotlin-crypto/common/src/pbkdf2.kt +++ /dev/null @@ -1,3 +0,0 @@ -package org.ton.crypto - -public expect fun pbkdf2Sha512(key: ByteArray, salt: ByteArray, iterations: Int): ByteArray diff --git a/ton-kotlin-crypto/darwin/src/Sha256.kt b/ton-kotlin-crypto/darwin/src/Sha256.kt deleted file mode 100644 index cef129ba..00000000 --- a/ton-kotlin-crypto/darwin/src/Sha256.kt +++ /dev/null @@ -1,33 +0,0 @@ -package org.ton.crypto - -import kotlinx.cinterop.* -import platform.CoreCrypto.CC_SHA256_CTX -import platform.CoreCrypto.CC_SHA256_Final -import platform.CoreCrypto.CC_SHA256_Init -import platform.CoreCrypto.CC_SHA256_Update -import kotlin.native.internal.createCleaner - -public actual class Sha256 { - private val sha256Ctx = nativeHeap.alloc().also { - CC_SHA256_Init(it.ptr) - } - - @OptIn(ExperimentalStdlibApi::class) - private val cleaner = createCleaner(sha256Ctx) { - nativeHeap.free(it) - } - - public actual fun update(bytes: ByteArray): Sha256 { - bytes.usePinned { pinned -> - CC_SHA256_Update(sha256Ctx.ptr, pinned.addressOf(0), bytes.size.convert()) - } - return this - } - - public actual fun digest(output: ByteArray): ByteArray = memScoped { - output.usePinned { - CC_SHA256_Final(it.addressOf(0).reinterpret(), sha256Ctx.ptr) - } - output - } -} diff --git a/ton-kotlin-crypto/jvm/src/Sha256.kt b/ton-kotlin-crypto/jvm/src/Sha256.kt deleted file mode 100644 index e8637a48..00000000 --- a/ton-kotlin-crypto/jvm/src/Sha256.kt +++ /dev/null @@ -1,18 +0,0 @@ -@file:JvmName("Sha256JvmKt") - -package org.ton.crypto - -import java.security.MessageDigest - -public actual class Sha256 { - private val digest = MessageDigest.getInstance("SHA-256") - - public actual fun update(bytes: ByteArray): Sha256 = apply { - digest.update(bytes) - } - - public actual fun digest(output: ByteArray): ByteArray { - digest.digest().copyInto(output) - return output - } -} diff --git a/ton-kotlin-crypto/jvm/src/digest/DigestJvm.kt b/ton-kotlin-crypto/jvm/src/digest/DigestJvm.kt new file mode 100644 index 00000000..90cc39fa --- /dev/null +++ b/ton-kotlin-crypto/jvm/src/digest/DigestJvm.kt @@ -0,0 +1,32 @@ +package org.ton.crypto.digest + +import java.security.MessageDigest + +public actual fun Digest(algorithm: String): Digest = DigestImpl(MessageDigest.getInstance(algorithm)) + +public actual fun sha256(bytes: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(bytes) + +public actual fun sha512(bytes: ByteArray): ByteArray = MessageDigest.getInstance("SHA-512").digest(bytes) + +@JvmInline +private value class DigestImpl( + val digest: MessageDigest +) : Digest { + override val algorithmName: String + get() = digest.algorithm + override val digestSize: Int + get() = digest.digestLength + + override fun update(input: ByteArray, offset: Int, length: Int) { + digest.update(input, offset, length) + } + + override fun build(output: ByteArray, offset: Int): ByteArray { + digest.digest(output, offset, output.size - offset) + return output + } + + override fun reset() { + digest.reset() + } +} diff --git a/ton-kotlin-crypto/jvm/src/hmac.kt b/ton-kotlin-crypto/jvm/src/hmac.kt deleted file mode 100644 index f102f9ff..00000000 --- a/ton-kotlin-crypto/jvm/src/hmac.kt +++ /dev/null @@ -1,15 +0,0 @@ -@file:JvmName("HmacJvmKt") - -package org.ton.crypto - -import javax.crypto.Mac -import javax.crypto.spec.SecretKeySpec - -public actual fun hmacSha512(key: ByteArray, input: ByteArray): ByteArray { - val algorithm = "HmacSHA512" - - val ctx = Mac.getInstance(algorithm) - ctx.init(SecretKeySpec(key, algorithm)) - ctx.update(input) - return ctx.doFinal() -} diff --git a/ton-kotlin-crypto/jvm/src/pbkdf.kt b/ton-kotlin-crypto/jvm/src/pbkdf.kt deleted file mode 100644 index d510a5e8..00000000 --- a/ton-kotlin-crypto/jvm/src/pbkdf.kt +++ /dev/null @@ -1,13 +0,0 @@ -@file:JvmName("Pbkdf2JvmKt") - -package org.ton.crypto - -import org.bouncycastle.crypto.digests.SHA512Digest -import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator -import org.bouncycastle.crypto.params.KeyParameter - -public actual fun pbkdf2Sha512(key: ByteArray, salt: ByteArray, iterations: Int): ByteArray { - val gen = PKCS5S2ParametersGenerator(SHA512Digest()) - gen.init(key, salt, iterations) - return (gen.generateDerivedParameters(512) as KeyParameter).key -} diff --git a/ton-kotlin-crypto/jvm/test/hmacSha512.kt b/ton-kotlin-crypto/jvm/test/hmacSha512.kt new file mode 100644 index 00000000..2555bc92 --- /dev/null +++ b/ton-kotlin-crypto/jvm/test/hmacSha512.kt @@ -0,0 +1,22 @@ +import org.junit.Test +import org.ton.crypto.digest.sha2.SHA512Digest +import org.ton.crypto.hex +import org.ton.crypto.mac.hmac.HMac +import kotlin.test.assertContentEquals + +class HmacSha512Test { + @Test + fun testHmacSha512() { + val key = ByteArray(32) { 0x11 } + val input = ByteArray(32) { 0x22 } + + val expected = + hex("f5b421da607e3180d016ab217ef93297596ff980c15cc1b697fb69354dbe409adddc17ff8292eeaaf279d77166dabfa88db21debacf132d5b1139a3337d5f07b") + + val actual = HMac(SHA512Digest(), key).apply { + update(input) + }.build() + + assertContentEquals(expected, actual) + } +} diff --git a/ton-kotlin-crypto/linux/src/Sha256.kt b/ton-kotlin-crypto/linux/src/Sha256.kt deleted file mode 100644 index 809502e7..00000000 --- a/ton-kotlin-crypto/linux/src/Sha256.kt +++ /dev/null @@ -1,15 +0,0 @@ -package org.ton.crypto - -import org.ton.crypto.internal.Sha256Impl - -public actual class Sha256 { - private val impl = Sha256Impl() - - public actual fun update(bytes: ByteArray): Sha256 = apply { - impl.update(bytes) - } - - public actual fun digest(output: ByteArray): ByteArray { - return impl.digest(output) - } -} diff --git a/ton-kotlin-crypto/mingw/src/Sha256.kt b/ton-kotlin-crypto/mingw/src/Sha256.kt deleted file mode 100644 index 809502e7..00000000 --- a/ton-kotlin-crypto/mingw/src/Sha256.kt +++ /dev/null @@ -1,15 +0,0 @@ -package org.ton.crypto - -import org.ton.crypto.internal.Sha256Impl - -public actual class Sha256 { - private val impl = Sha256Impl() - - public actual fun update(bytes: ByteArray): Sha256 = apply { - impl.update(bytes) - } - - public actual fun digest(output: ByteArray): ByteArray { - return impl.digest(output) - } -} diff --git a/ton-kotlin-crypto/native/src/digest/Digest.kt b/ton-kotlin-crypto/native/src/digest/Digest.kt new file mode 100644 index 00000000..3de64db4 --- /dev/null +++ b/ton-kotlin-crypto/native/src/digest/Digest.kt @@ -0,0 +1,18 @@ +package org.ton.crypto.digest + +import org.ton.crypto.digest.sha2.SHA256Digest +import org.ton.crypto.digest.sha2.SHA512Digest + +public actual fun Digest(algorithm: String): Digest = when (algorithm) { + SHA256Digest.ALGORITHM_NAME -> SHA256Digest() + SHA512Digest.ALGORITHM_NAME -> SHA512Digest() + else -> throw IllegalArgumentException("Unsupported digest algorithm: $algorithm") +} + +public actual fun sha256(bytes: ByteArray): ByteArray = Digest("SHA-256").apply { + update(bytes) +}.build() + +public actual fun sha512(bytes: ByteArray): ByteArray = Digest("SHA-512").apply { + update(bytes) +}.build() diff --git a/ton-kotlin-crypto/native/src/hmacSha512.kt b/ton-kotlin-crypto/native/src/hmacSha512.kt deleted file mode 100644 index 7ba2bab7..00000000 --- a/ton-kotlin-crypto/native/src/hmacSha512.kt +++ /dev/null @@ -1,5 +0,0 @@ -package org.ton.crypto - -public actual fun hmacSha512(key: ByteArray, input: ByteArray): ByteArray { - TODO("Not yet implemented") -} diff --git a/ton-kotlin-crypto/native/src/internal/Sha256.kt b/ton-kotlin-crypto/native/src/internal/Sha256.kt deleted file mode 100644 index 3520304b..00000000 --- a/ton-kotlin-crypto/native/src/internal/Sha256.kt +++ /dev/null @@ -1,155 +0,0 @@ -package org.ton.crypto.internal - -private val k = longArrayOf( - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -).map { it.toInt() }.toIntArray() - -internal class Sha256Impl { - private var data: ByteArray = ByteArray(64) - private var state: IntArray = IntArray(8) - private var dataLength: Int = 0 - private var bitLength: Long = 0 - - init { - state[0] = 0x6a09e667 - state[1] = 0xbb67ae85.toInt() - state[2] = 0x3c6ef372 - state[3] = 0xa54ff53a.toInt() - state[4] = 0x510e527f - state[5] = 0x9b05688c.toInt() - state[6] = 0x1f83d9ab - state[7] = 0x5be0cd19 - } - - fun update(bytes: ByteArray): Sha256Impl = apply { - val total = bytes.size - 64 - for (i in 0..total step 64) { - transform(bytes, i) - bitLength += 512 - } - dataLength = bytes.size % 64 - val offset = (bytes.size / 64) * 64 - for (i in 0 until dataLength) data[i] = bytes[offset + i] - } - - fun digest(output: ByteArray): ByteArray { - // Pad whatever data is left in the buffer. - if (dataLength < 56) { - data[dataLength] = 0x80.toByte() - for (i in dataLength + 1 until 56) data[i] = 0 - } else { - data[dataLength] = 0x80.toByte() - for (i in dataLength + 1 until 64) data[i] = 0 - transform(data, 0) - for (i in 0 until 56) data[i] = 0 - } - - // Append to the padding the total message's length in bits and transform. - bitLength += dataLength * 8 - data[63] = (bitLength and 0xFF).toByte() - data[62] = ((bitLength ushr 8) and 0xFF).toByte() - data[61] = ((bitLength ushr 16) and 0xFF).toByte() - data[60] = ((bitLength ushr 24) and 0xFF).toByte() - data[59] = ((bitLength ushr 32) and 0xFF).toByte() - data[58] = ((bitLength ushr 40) and 0xFF).toByte() - data[57] = ((bitLength ushr 48) and 0xFF).toByte() - data[56] = ((bitLength ushr 56) and 0xFF).toByte() - transform(data, 0) - - // Since this implementation uses little endian byte ordering and SHA uses big endian, - // reverse all the bytes when copying the final state to the output hash. - - for (i in 0 until 4) { - output[i] = ((state[0] ushr (24 - i * 8)) and 0xFF).toByte() - output[i + 4] = ((state[1] ushr (24 - i * 8)) and 0xFF).toByte() - output[i + 8] = ((state[2] ushr (24 - i * 8)) and 0xFF).toByte() - output[i + 12] = ((state[3] ushr (24 - i * 8)) and 0xFF).toByte() - output[i + 16] = ((state[4] ushr (24 - i * 8)) and 0xFF).toByte() - output[i + 20] = ((state[5] ushr (24 - i * 8)) and 0xFF).toByte() - output[i + 24] = ((state[6] ushr (24 - i * 8)) and 0xFF).toByte() - output[i + 28] = ((state[7] ushr (24 - i * 8)) and 0xFF).toByte() - } - return output - } - - private fun transform(data: ByteArray, offset: Int) { - var a: Int - var b: Int - var c: Int - var d: Int - var e: Int - var f: Int - var g: Int - var h: Int - var t1: Int - var t2: Int - val m = IntArray(64) - - data.copyToIntArray(offset, 16, m) - - for (i in 16 until 64) { - m[i] = sig1(m[i - 2]) + m[i - 7] + sig0(m[i - 15]) + m[i - 16] - } - a = state[0] - b = state[1] - c = state[2] - d = state[3] - e = state[4] - f = state[5] - g = state[6] - h = state[7] - - for (i in 0 until 64) { - t1 = h + ep1(e) + ch(e, f, g) + k[i] + m[i] - t2 = ep0(a) + maj(a, b, c) - h = g - g = f - f = e - e = d + t1 - d = c - c = b - b = a - a = t1 + t2 - } - - state[0] += a - state[1] += b - state[2] += c - state[3] += d - state[4] += e - state[5] += f - state[6] += g - state[7] += h - } -} - -private inline fun maj(x: Int, y: Int, z: Int) = (x and y) xor (x and z) xor (y and z) - -private inline fun ep0(x: Int) = rotateRight(x, 2) xor rotateRight(x, 13) xor rotateRight(x, 22) - -private inline fun ch(x: Int, y: Int, z: Int) = (x and y) xor (x.inv() and z) - -private inline fun ep1(x: Int) = rotateRight(x, 6) xor rotateRight(x, 11) xor rotateRight(x, 25) - -private inline fun sig0(x: Int) = rotateRight(x, 7) xor rotateRight(x, 18) xor (x ushr 3) - -private inline fun sig1(x: Int) = rotateRight(x, 17) xor rotateRight(x, 19) xor (x ushr 10) - -private inline fun rotateRight(a: Int, b: Int) = a ushr b or (a shl (32 - b)) - -private inline fun ByteArray.copyToIntArray(sourceOffset: Int, count: Int, target: IntArray) { - for (i in 0 until count) { - val value = this.getIntAt(sourceOffset + i * 4) - target[i] = (value and 0x000000FF shl 24) or - (value and 0x0000ff00 shl 8) or - (value and 0x00ff0000 ushr 8) or - (value and 0xff000000.toInt() ushr 24) - } -} diff --git a/ton-kotlin-crypto/native/src/pbkdf2Sha512.kt b/ton-kotlin-crypto/native/src/pbkdf2Sha512.kt deleted file mode 100644 index c3582839..00000000 --- a/ton-kotlin-crypto/native/src/pbkdf2Sha512.kt +++ /dev/null @@ -1,5 +0,0 @@ -package org.ton.crypto - -public actual fun pbkdf2Sha512(key: ByteArray, salt: ByteArray, iterations: Int): ByteArray { - TODO("Not yet implemented") -} diff --git a/ton-kotlin-hashmap/src/jvmTest/kotlin/TestDict.kt b/ton-kotlin-hashmap/src/jvmTest/kotlin/TestDict.kt deleted file mode 100644 index dea28929..00000000 --- a/ton-kotlin-hashmap/src/jvmTest/kotlin/TestDict.kt +++ /dev/null @@ -1,24 +0,0 @@ -import org.junit.Test -import org.ton.boc.BagOfCells -import org.ton.crypto.hex -import org.ton.hashmap.HmEdge -import org.ton.tlb.constructor.AnyTlbConstructor - -fun main() { - val cell = - BagOfCells(hex(runCmd("fift -I /usr/local/lib/fift/ /Users/andreypfau/IdeaProjects/ton-kotlin/ton-kotlin-hashmap/src/jvmTest/resources/test.fif"))).first() - val codec = HmEdge.tlbCodec(4, AnyTlbConstructor) - val map = codec.loadTlb(cell) - println(map.toString()) - map.forEach { - println("${it.first.toBinary()} = ${it.second.bits.toBinary()}") - } -} - -private fun runCmd(cmd: String): String { - return Runtime.getRuntime().exec(cmd).inputStream.use { - it.readBytes().decodeToString().also { - println("cmd result: $it") - } - } -} diff --git a/ton-kotlin-liteclient/src/commonMain/kotlin/org/ton/lite/client/LiteClient.kt b/ton-kotlin-liteclient/src/commonMain/kotlin/org/ton/lite/client/LiteClient.kt index 5d5471f2..48ac6434 100644 --- a/ton-kotlin-liteclient/src/commonMain/kotlin/org/ton/lite/client/LiteClient.kt +++ b/ton-kotlin-liteclient/src/commonMain/kotlin/org/ton/lite/client/LiteClient.kt @@ -22,7 +22,7 @@ import org.ton.cell.Cell import org.ton.cell.CellBuilder import org.ton.cell.CellType import org.ton.crypto.crc16 -import org.ton.crypto.sha256 +import org.ton.crypto.digest.sha256 import org.ton.lite.api.LiteApiClient import org.ton.lite.api.exception.LiteServerNotReadyException import org.ton.lite.api.exception.LiteServerUnknownException diff --git a/ton-kotlin-mnemonic/src/commonMain/kotlin/org/ton/mnemonic/Mnemonic.kt b/ton-kotlin-mnemonic/src/commonMain/kotlin/org/ton/mnemonic/Mnemonic.kt index 5137a70a..7c18fe19 100644 --- a/ton-kotlin-mnemonic/src/commonMain/kotlin/org/ton/mnemonic/Mnemonic.kt +++ b/ton-kotlin-mnemonic/src/commonMain/kotlin/org/ton/mnemonic/Mnemonic.kt @@ -3,8 +3,9 @@ package org.ton.mnemonic import io.ktor.utils.io.core.* import org.ton.crypto.Ed25519 import org.ton.crypto.SecureRandom -import org.ton.crypto.hmacSha512 -import org.ton.crypto.pbkdf2Sha512 +import org.ton.crypto.digest.Digest +import org.ton.crypto.kdf.PKCSS2ParametersGenerator +import org.ton.crypto.mac.hmac.HMac import kotlin.jvm.JvmStatic import kotlin.random.Random @@ -28,11 +29,15 @@ public interface Mnemonic { // Default salt used to check, if mnemonic phrase requires a password public const val DEFAULT_PASSWORD_SALT: String = "TON fast seed version" + public const val DEFAULT_WORD_COUNT: Int = 24 + + public fun mnemonicWords(): List = MNEMONIC_WORD_LIST.toList() + @JvmStatic public suspend fun generate( - wordCount: Int = 24, password: String = "", - wordlist: Array = DEFAULT_WORDLIST, + wordCount: Int = DEFAULT_WORD_COUNT, + wordlist: Array = MNEMONIC_WORD_LIST, random: Random = SecureRandom ): Array { while (true) { @@ -61,7 +66,7 @@ public interface Mnemonic { public suspend fun isValid( mnemonic: Array, password: String = "", - wordlist: Array = DEFAULT_WORDLIST + wordlist: Array = MNEMONIC_WORD_LIST ): Boolean { if (!mnemonic.all { wordlist.contains(it) }) { return false @@ -82,2079 +87,43 @@ public interface Mnemonic { } @JvmStatic - public fun toSeed(mnemonic: Array, password: String = ""): ByteArray = - pbkdf2Sha512( - toEntropy(mnemonic, password), - DEFAULT_SALT.toByteArray(), - DEFAULT_ITERATIONS - ).sliceArray(0..31) + public fun toSeed(mnemonic: Array, password: String = ""): ByteArray { + val pbdkf2Sha512 = PKCSS2ParametersGenerator( + digest = Digest("SHA-512"), + password = toEntropy(mnemonic, password), + salt = DEFAULT_SALT.toByteArray(), + iterationCount = DEFAULT_ITERATIONS + ) + return pbdkf2Sha512.generateDerivedParameters(512).sliceArray(0..31) + } @JvmStatic - public fun toEntropy(mnemonic: Array, password: String = ""): ByteArray = - hmacSha512(mnemonic.joinToString(" ").toByteArray(), password.toByteArray()) + public fun toEntropy(mnemonic: Array, password: String = ""): ByteArray { + val hMac = HMac(Digest("SHA-512"), mnemonic.joinToString(" ").toByteArray()) + hMac += password.toByteArray() + return hMac.build() + } @JvmStatic - public fun isBasicSeed(entropy: ByteArray): Boolean = - pbkdf2Sha512(entropy, DEFAULT_BASIC_SALT.toByteArray(), DEFAULT_BASIC_ITERATIONS).first() == 0.toByte() + public fun isBasicSeed(entropy: ByteArray): Boolean { + val pbdkf2Sha512 = PKCSS2ParametersGenerator( + digest = Digest("SHA-512"), + password = entropy, + salt = DEFAULT_BASIC_SALT.toByteArray(), + iterationCount = DEFAULT_BASIC_ITERATIONS + ) + return pbdkf2Sha512.generateDerivedParameters(512).first() == 0.toByte() + } @JvmStatic - public fun isPasswordSeed(entropy: ByteArray): Boolean = - pbkdf2Sha512( - entropy, - DEFAULT_PASSWORD_SALT.toByteArray(), - DEFAULT_PASSWORD_ITERATIONS - ).first() == 1.toByte() - - public val DEFAULT_WORDLIST: Array - get() = arrayOf( - "abandon", - "ability", - "able", - "about", - "above", - "absent", - "absorb", - "abstract", - "absurd", - "abuse", - "access", - "accident", - "account", - "accuse", - "achieve", - "acid", - "acoustic", - "acquire", - "across", - "act", - "action", - "actor", - "actress", - "actual", - "adapt", - "add", - "addict", - "address", - "adjust", - "admit", - "adult", - "advance", - "advice", - "aerobic", - "affair", - "afford", - "afraid", - "again", - "age", - "agent", - "agree", - "ahead", - "aim", - "air", - "airport", - "aisle", - "alarm", - "album", - "alcohol", - "alert", - "alien", - "all", - "alley", - "allow", - "almost", - "alone", - "alpha", - "already", - "also", - "alter", - "always", - "amateur", - "amazing", - "among", - "amount", - "amused", - "analyst", - "anchor", - "ancient", - "anger", - "angle", - "angry", - "animal", - "ankle", - "announce", - "annual", - "another", - "answer", - "antenna", - "antique", - "anxiety", - "any", - "apart", - "apology", - "appear", - "apple", - "approve", - "april", - "arch", - "arctic", - "area", - "arena", - "argue", - "arm", - "armed", - "armor", - "army", - "around", - "arrange", - "arrest", - "arrive", - "arrow", - "art", - "artefact", - "artist", - "artwork", - "ask", - "aspect", - "assault", - "asset", - "assist", - "assume", - "asthma", - "athlete", - "atom", - "attack", - "attend", - "attitude", - "attract", - "auction", - "audit", - "august", - "aunt", - "author", - "auto", - "autumn", - "average", - "avocado", - "avoid", - "awake", - "aware", - "away", - "awesome", - "awful", - "awkward", - "axis", - "baby", - "bachelor", - "bacon", - "badge", - "bag", - "balance", - "balcony", - "ball", - "bamboo", - "banana", - "banner", - "bar", - "barely", - "bargain", - "barrel", - "base", - "basic", - "basket", - "battle", - "beach", - "bean", - "beauty", - "because", - "become", - "beef", - "before", - "begin", - "behave", - "behind", - "believe", - "below", - "belt", - "bench", - "benefit", - "best", - "betray", - "better", - "between", - "beyond", - "bicycle", - "bid", - "bike", - "bind", - "biology", - "bird", - "birth", - "bitter", - "black", - "blade", - "blame", - "blanket", - "blast", - "bleak", - "bless", - "blind", - "blood", - "blossom", - "blouse", - "blue", - "blur", - "blush", - "board", - "boat", - "body", - "boil", - "bomb", - "bone", - "bonus", - "book", - "boost", - "border", - "boring", - "borrow", - "boss", - "bottom", - "bounce", - "box", - "boy", - "bracket", - "brain", - "brand", - "brass", - "brave", - "bread", - "breeze", - "brick", - "bridge", - "brief", - "bright", - "bring", - "brisk", - "broccoli", - "broken", - "bronze", - "broom", - "brother", - "brown", - "brush", - "bubble", - "buddy", - "budget", - "buffalo", - "build", - "bulb", - "bulk", - "bullet", - "bundle", - "bunker", - "burden", - "burger", - "burst", - "bus", - "business", - "busy", - "butter", - "buyer", - "buzz", - "cabbage", - "cabin", - "cable", - "cactus", - "cage", - "cake", - "call", - "calm", - "camera", - "camp", - "can", - "canal", - "cancel", - "candy", - "cannon", - "canoe", - "canvas", - "canyon", - "capable", - "capital", - "captain", - "car", - "carbon", - "card", - "cargo", - "carpet", - "carry", - "cart", - "case", - "cash", - "casino", - "castle", - "casual", - "cat", - "catalog", - "catch", - "category", - "cattle", - "caught", - "cause", - "caution", - "cave", - "ceiling", - "celery", - "cement", - "census", - "century", - "cereal", - "certain", - "chair", - "chalk", - "champion", - "change", - "chaos", - "chapter", - "charge", - "chase", - "chat", - "cheap", - "check", - "cheese", - "chef", - "cherry", - "chest", - "chicken", - "chief", - "child", - "chimney", - "choice", - "choose", - "chronic", - "chuckle", - "chunk", - "churn", - "cigar", - "cinnamon", - "circle", - "citizen", - "city", - "civil", - "claim", - "clap", - "clarify", - "claw", - "clay", - "clean", - "clerk", - "clever", - "click", - "client", - "cliff", - "climb", - "clinic", - "clip", - "clock", - "clog", - "close", - "cloth", - "cloud", - "clown", - "club", - "clump", - "cluster", - "clutch", - "coach", - "coast", - "coconut", - "code", - "coffee", - "coil", - "coin", - "collect", - "color", - "column", - "combine", - "come", - "comfort", - "comic", - "common", - "company", - "concert", - "conduct", - "confirm", - "congress", - "connect", - "consider", - "control", - "convince", - "cook", - "cool", - "copper", - "copy", - "coral", - "core", - "corn", - "correct", - "cost", - "cotton", - "couch", - "country", - "couple", - "course", - "cousin", - "cover", - "coyote", - "crack", - "cradle", - "craft", - "cram", - "crane", - "crash", - "crater", - "crawl", - "crazy", - "cream", - "credit", - "creek", - "crew", - "cricket", - "crime", - "crisp", - "critic", - "crop", - "cross", - "crouch", - "crowd", - "crucial", - "cruel", - "cruise", - "crumble", - "crunch", - "crush", - "cry", - "crystal", - "cube", - "culture", - "cup", - "cupboard", - "curious", - "current", - "curtain", - "curve", - "cushion", - "custom", - "cute", - "cycle", - "dad", - "damage", - "damp", - "dance", - "danger", - "daring", - "dash", - "daughter", - "dawn", - "day", - "deal", - "debate", - "debris", - "decade", - "december", - "decide", - "decline", - "decorate", - "decrease", - "deer", - "defense", - "define", - "defy", - "degree", - "delay", - "deliver", - "demand", - "demise", - "denial", - "dentist", - "deny", - "depart", - "depend", - "deposit", - "depth", - "deputy", - "derive", - "describe", - "desert", - "design", - "desk", - "despair", - "destroy", - "detail", - "detect", - "develop", - "device", - "devote", - "diagram", - "dial", - "diamond", - "diary", - "dice", - "diesel", - "diet", - "differ", - "digital", - "dignity", - "dilemma", - "dinner", - "dinosaur", - "direct", - "dirt", - "disagree", - "discover", - "disease", - "dish", - "dismiss", - "disorder", - "display", - "distance", - "divert", - "divide", - "divorce", - "dizzy", - "doctor", - "document", - "dog", - "doll", - "dolphin", - "domain", - "donate", - "donkey", - "donor", - "door", - "dose", - "double", - "dove", - "draft", - "dragon", - "drama", - "drastic", - "draw", - "dream", - "dress", - "drift", - "drill", - "drink", - "drip", - "drive", - "drop", - "drum", - "dry", - "duck", - "dumb", - "dune", - "during", - "dust", - "dutch", - "duty", - "dwarf", - "dynamic", - "eager", - "eagle", - "early", - "earn", - "earth", - "easily", - "east", - "easy", - "echo", - "ecology", - "economy", - "edge", - "edit", - "educate", - "effort", - "egg", - "eight", - "either", - "elbow", - "elder", - "electric", - "elegant", - "element", - "elephant", - "elevator", - "elite", - "else", - "embark", - "embody", - "embrace", - "emerge", - "emotion", - "employ", - "empower", - "empty", - "enable", - "enact", - "end", - "endless", - "endorse", - "enemy", - "energy", - "enforce", - "engage", - "engine", - "enhance", - "enjoy", - "enlist", - "enough", - "enrich", - "enroll", - "ensure", - "enter", - "entire", - "entry", - "envelope", - "episode", - "equal", - "equip", - "era", - "erase", - "erode", - "erosion", - "error", - "erupt", - "escape", - "essay", - "essence", - "estate", - "eternal", - "ethics", - "evidence", - "evil", - "evoke", - "evolve", - "exact", - "example", - "excess", - "exchange", - "excite", - "exclude", - "excuse", - "execute", - "exercise", - "exhaust", - "exhibit", - "exile", - "exist", - "exit", - "exotic", - "expand", - "expect", - "expire", - "explain", - "expose", - "express", - "extend", - "extra", - "eye", - "eyebrow", - "fabric", - "face", - "faculty", - "fade", - "faint", - "faith", - "fall", - "false", - "fame", - "family", - "famous", - "fan", - "fancy", - "fantasy", - "farm", - "fashion", - "fat", - "fatal", - "father", - "fatigue", - "fault", - "favorite", - "feature", - "february", - "federal", - "fee", - "feed", - "feel", - "female", - "fence", - "festival", - "fetch", - "fever", - "few", - "fiber", - "fiction", - "field", - "figure", - "file", - "film", - "filter", - "final", - "find", - "fine", - "finger", - "finish", - "fire", - "firm", - "first", - "fiscal", - "fish", - "fit", - "fitness", - "fix", - "flag", - "flame", - "flash", - "flat", - "flavor", - "flee", - "flight", - "flip", - "float", - "flock", - "floor", - "flower", - "fluid", - "flush", - "fly", - "foam", - "focus", - "fog", - "foil", - "fold", - "follow", - "food", - "foot", - "force", - "forest", - "forget", - "fork", - "fortune", - "forum", - "forward", - "fossil", - "foster", - "found", - "fox", - "fragile", - "frame", - "frequent", - "fresh", - "friend", - "fringe", - "frog", - "front", - "frost", - "frown", - "frozen", - "fruit", - "fuel", - "fun", - "funny", - "furnace", - "fury", - "future", - "gadget", - "gain", - "galaxy", - "gallery", - "game", - "gap", - "garage", - "garbage", - "garden", - "garlic", - "garment", - "gas", - "gasp", - "gate", - "gather", - "gauge", - "gaze", - "general", - "genius", - "genre", - "gentle", - "genuine", - "gesture", - "ghost", - "giant", - "gift", - "giggle", - "ginger", - "giraffe", - "girl", - "give", - "glad", - "glance", - "glare", - "glass", - "glide", - "glimpse", - "globe", - "gloom", - "glory", - "glove", - "glow", - "glue", - "goat", - "goddess", - "gold", - "good", - "goose", - "gorilla", - "gospel", - "gossip", - "govern", - "gown", - "grab", - "grace", - "grain", - "grant", - "grape", - "grass", - "gravity", - "great", - "green", - "grid", - "grief", - "grit", - "grocery", - "group", - "grow", - "grunt", - "guard", - "guess", - "guide", - "guilt", - "guitar", - "gun", - "gym", - "habit", - "hair", - "half", - "hammer", - "hamster", - "hand", - "happy", - "harbor", - "hard", - "harsh", - "harvest", - "hat", - "have", - "hawk", - "hazard", - "head", - "health", - "heart", - "heavy", - "hedgehog", - "height", - "hello", - "helmet", - "help", - "hen", - "hero", - "hidden", - "high", - "hill", - "hint", - "hip", - "hire", - "history", - "hobby", - "hockey", - "hold", - "hole", - "holiday", - "hollow", - "home", - "honey", - "hood", - "hope", - "horn", - "horror", - "horse", - "hospital", - "host", - "hotel", - "hour", - "hover", - "hub", - "huge", - "human", - "humble", - "humor", - "hundred", - "hungry", - "hunt", - "hurdle", - "hurry", - "hurt", - "husband", - "hybrid", - "ice", - "icon", - "idea", - "identify", - "idle", - "ignore", - "ill", - "illegal", - "illness", - "image", - "imitate", - "immense", - "immune", - "impact", - "impose", - "improve", - "impulse", - "inch", - "include", - "income", - "increase", - "index", - "indicate", - "indoor", - "industry", - "infant", - "inflict", - "inform", - "inhale", - "inherit", - "initial", - "inject", - "injury", - "inmate", - "inner", - "innocent", - "input", - "inquiry", - "insane", - "insect", - "inside", - "inspire", - "install", - "intact", - "interest", - "into", - "invest", - "invite", - "involve", - "iron", - "island", - "isolate", - "issue", - "item", - "ivory", - "jacket", - "jaguar", - "jar", - "jazz", - "jealous", - "jeans", - "jelly", - "jewel", - "job", - "join", - "joke", - "journey", - "joy", - "judge", - "juice", - "jump", - "jungle", - "junior", - "junk", - "just", - "kangaroo", - "keen", - "keep", - "ketchup", - "key", - "kick", - "kid", - "kidney", - "kind", - "kingdom", - "kiss", - "kit", - "kitchen", - "kite", - "kitten", - "kiwi", - "knee", - "knife", - "knock", - "know", - "lab", - "label", - "labor", - "ladder", - "lady", - "lake", - "lamp", - "language", - "laptop", - "large", - "later", - "latin", - "laugh", - "laundry", - "lava", - "law", - "lawn", - "lawsuit", - "layer", - "lazy", - "leader", - "leaf", - "learn", - "leave", - "lecture", - "left", - "leg", - "legal", - "legend", - "leisure", - "lemon", - "lend", - "length", - "lens", - "leopard", - "lesson", - "letter", - "level", - "liar", - "liberty", - "library", - "license", - "life", - "lift", - "light", - "like", - "limb", - "limit", - "link", - "lion", - "liquid", - "list", - "little", - "live", - "lizard", - "load", - "loan", - "lobster", - "local", - "lock", - "logic", - "lonely", - "long", - "loop", - "lottery", - "loud", - "lounge", - "love", - "loyal", - "lucky", - "luggage", - "lumber", - "lunar", - "lunch", - "luxury", - "lyrics", - "machine", - "mad", - "magic", - "magnet", - "maid", - "mail", - "main", - "major", - "make", - "mammal", - "man", - "manage", - "mandate", - "mango", - "mansion", - "manual", - "maple", - "marble", - "march", - "margin", - "marine", - "market", - "marriage", - "mask", - "mass", - "master", - "match", - "material", - "math", - "matrix", - "matter", - "maximum", - "maze", - "meadow", - "mean", - "measure", - "meat", - "mechanic", - "medal", - "media", - "melody", - "melt", - "member", - "memory", - "mention", - "menu", - "mercy", - "merge", - "merit", - "merry", - "mesh", - "message", - "metal", - "method", - "middle", - "midnight", - "milk", - "million", - "mimic", - "mind", - "minimum", - "minor", - "minute", - "miracle", - "mirror", - "misery", - "miss", - "mistake", - "mix", - "mixed", - "mixture", - "mobile", - "model", - "modify", - "mom", - "moment", - "monitor", - "monkey", - "monster", - "month", - "moon", - "moral", - "more", - "morning", - "mosquito", - "mother", - "motion", - "motor", - "mountain", - "mouse", - "move", - "movie", - "much", - "muffin", - "mule", - "multiply", - "muscle", - "museum", - "mushroom", - "music", - "must", - "mutual", - "myself", - "mystery", - "myth", - "naive", - "name", - "napkin", - "narrow", - "nasty", - "nation", - "nature", - "near", - "neck", - "need", - "negative", - "neglect", - "neither", - "nephew", - "nerve", - "nest", - "net", - "network", - "neutral", - "never", - "news", - "next", - "nice", - "night", - "noble", - "noise", - "nominee", - "noodle", - "normal", - "north", - "nose", - "notable", - "note", - "nothing", - "notice", - "novel", - "now", - "nuclear", - "number", - "nurse", - "nut", - "oak", - "obey", - "object", - "oblige", - "obscure", - "observe", - "obtain", - "obvious", - "occur", - "ocean", - "october", - "odor", - "off", - "offer", - "office", - "often", - "oil", - "okay", - "old", - "olive", - "olympic", - "omit", - "once", - "one", - "onion", - "online", - "only", - "open", - "opera", - "opinion", - "oppose", - "option", - "orange", - "orbit", - "orchard", - "order", - "ordinary", - "organ", - "orient", - "original", - "orphan", - "ostrich", - "other", - "outdoor", - "outer", - "output", - "outside", - "oval", - "oven", - "over", - "own", - "owner", - "oxygen", - "oyster", - "ozone", - "pact", - "paddle", - "page", - "pair", - "palace", - "palm", - "panda", - "panel", - "panic", - "panther", - "paper", - "parade", - "parent", - "park", - "parrot", - "party", - "pass", - "patch", - "path", - "patient", - "patrol", - "pattern", - "pause", - "pave", - "payment", - "peace", - "peanut", - "pear", - "peasant", - "pelican", - "pen", - "penalty", - "pencil", - "people", - "pepper", - "perfect", - "permit", - "person", - "pet", - "phone", - "photo", - "phrase", - "physical", - "piano", - "picnic", - "picture", - "piece", - "pig", - "pigeon", - "pill", - "pilot", - "pink", - "pioneer", - "pipe", - "pistol", - "pitch", - "pizza", - "place", - "planet", - "plastic", - "plate", - "play", - "please", - "pledge", - "pluck", - "plug", - "plunge", - "poem", - "poet", - "point", - "polar", - "pole", - "police", - "pond", - "pony", - "pool", - "popular", - "portion", - "position", - "possible", - "post", - "potato", - "pottery", - "poverty", - "powder", - "power", - "practice", - "praise", - "predict", - "prefer", - "prepare", - "present", - "pretty", - "prevent", - "price", - "pride", - "primary", - "print", - "priority", - "prison", - "private", - "prize", - "problem", - "process", - "produce", - "profit", - "program", - "project", - "promote", - "proof", - "property", - "prosper", - "protect", - "proud", - "provide", - "public", - "pudding", - "pull", - "pulp", - "pulse", - "pumpkin", - "punch", - "pupil", - "puppy", - "purchase", - "purity", - "purpose", - "purse", - "push", - "put", - "puzzle", - "pyramid", - "quality", - "quantum", - "quarter", - "question", - "quick", - "quit", - "quiz", - "quote", - "rabbit", - "raccoon", - "race", - "rack", - "radar", - "radio", - "rail", - "rain", - "raise", - "rally", - "ramp", - "ranch", - "random", - "range", - "rapid", - "rare", - "rate", - "rather", - "raven", - "raw", - "razor", - "ready", - "real", - "reason", - "rebel", - "rebuild", - "recall", - "receive", - "recipe", - "record", - "recycle", - "reduce", - "reflect", - "reform", - "refuse", - "region", - "regret", - "regular", - "reject", - "relax", - "release", - "relief", - "rely", - "remain", - "remember", - "remind", - "remove", - "render", - "renew", - "rent", - "reopen", - "repair", - "repeat", - "replace", - "report", - "require", - "rescue", - "resemble", - "resist", - "resource", - "response", - "result", - "retire", - "retreat", - "return", - "reunion", - "reveal", - "review", - "reward", - "rhythm", - "rib", - "ribbon", - "rice", - "rich", - "ride", - "ridge", - "rifle", - "right", - "rigid", - "ring", - "riot", - "ripple", - "risk", - "ritual", - "rival", - "river", - "road", - "roast", - "robot", - "robust", - "rocket", - "romance", - "roof", - "rookie", - "room", - "rose", - "rotate", - "rough", - "round", - "route", - "royal", - "rubber", - "rude", - "rug", - "rule", - "run", - "runway", - "rural", - "sad", - "saddle", - "sadness", - "safe", - "sail", - "salad", - "salmon", - "salon", - "salt", - "salute", - "same", - "sample", - "sand", - "satisfy", - "satoshi", - "sauce", - "sausage", - "save", - "say", - "scale", - "scan", - "scare", - "scatter", - "scene", - "scheme", - "school", - "science", - "scissors", - "scorpion", - "scout", - "scrap", - "screen", - "script", - "scrub", - "sea", - "search", - "season", - "seat", - "second", - "secret", - "section", - "security", - "seed", - "seek", - "segment", - "select", - "sell", - "seminar", - "senior", - "sense", - "sentence", - "series", - "service", - "session", - "settle", - "setup", - "seven", - "shadow", - "shaft", - "shallow", - "share", - "shed", - "shell", - "sheriff", - "shield", - "shift", - "shine", - "ship", - "shiver", - "shock", - "shoe", - "shoot", - "shop", - "short", - "shoulder", - "shove", - "shrimp", - "shrug", - "shuffle", - "shy", - "sibling", - "sick", - "side", - "siege", - "sight", - "sign", - "silent", - "silk", - "silly", - "silver", - "similar", - "simple", - "since", - "sing", - "siren", - "sister", - "situate", - "six", - "size", - "skate", - "sketch", - "ski", - "skill", - "skin", - "skirt", - "skull", - "slab", - "slam", - "sleep", - "slender", - "slice", - "slide", - "slight", - "slim", - "slogan", - "slot", - "slow", - "slush", - "small", - "smart", - "smile", - "smoke", - "smooth", - "snack", - "snake", - "snap", - "sniff", - "snow", - "soap", - "soccer", - "social", - "sock", - "soda", - "soft", - "solar", - "soldier", - "solid", - "solution", - "solve", - "someone", - "song", - "soon", - "sorry", - "sort", - "soul", - "sound", - "soup", - "source", - "south", - "space", - "spare", - "spatial", - "spawn", - "speak", - "special", - "speed", - "spell", - "spend", - "sphere", - "spice", - "spider", - "spike", - "spin", - "spirit", - "split", - "spoil", - "sponsor", - "spoon", - "sport", - "spot", - "spray", - "spread", - "spring", - "spy", - "square", - "squeeze", - "squirrel", - "stable", - "stadium", - "staff", - "stage", - "stairs", - "stamp", - "stand", - "start", - "state", - "stay", - "steak", - "steel", - "stem", - "step", - "stereo", - "stick", - "still", - "sting", - "stock", - "stomach", - "stone", - "stool", - "story", - "stove", - "strategy", - "street", - "strike", - "strong", - "struggle", - "student", - "stuff", - "stumble", - "style", - "subject", - "submit", - "subway", - "success", - "such", - "sudden", - "suffer", - "sugar", - "suggest", - "suit", - "summer", - "sun", - "sunny", - "sunset", - "super", - "supply", - "supreme", - "sure", - "surface", - "surge", - "surprise", - "surround", - "survey", - "suspect", - "sustain", - "swallow", - "swamp", - "swap", - "swarm", - "swear", - "sweet", - "swift", - "swim", - "swing", - "switch", - "sword", - "symbol", - "symptom", - "syrup", - "system", - "table", - "tackle", - "tag", - "tail", - "talent", - "talk", - "tank", - "tape", - "target", - "task", - "taste", - "tattoo", - "taxi", - "teach", - "team", - "tell", - "ten", - "tenant", - "tennis", - "tent", - "term", - "test", - "text", - "thank", - "that", - "theme", - "then", - "theory", - "there", - "they", - "thing", - "this", - "thought", - "three", - "thrive", - "throw", - "thumb", - "thunder", - "ticket", - "tide", - "tiger", - "tilt", - "timber", - "time", - "tiny", - "tip", - "tired", - "tissue", - "title", - "toast", - "tobacco", - "today", - "toddler", - "toe", - "together", - "toilet", - "token", - "tomato", - "tomorrow", - "tone", - "tongue", - "tonight", - "tool", - "tooth", - "top", - "topic", - "topple", - "torch", - "tornado", - "tortoise", - "toss", - "total", - "tourist", - "toward", - "tower", - "town", - "toy", - "track", - "trade", - "traffic", - "tragic", - "train", - "transfer", - "trap", - "trash", - "travel", - "tray", - "treat", - "tree", - "trend", - "trial", - "tribe", - "trick", - "trigger", - "trim", - "trip", - "trophy", - "trouble", - "truck", - "true", - "truly", - "trumpet", - "trust", - "truth", - "try", - "tube", - "tuition", - "tumble", - "tuna", - "tunnel", - "turkey", - "turn", - "turtle", - "twelve", - "twenty", - "twice", - "twin", - "twist", - "two", - "type", - "typical", - "ugly", - "umbrella", - "unable", - "unaware", - "uncle", - "uncover", - "under", - "undo", - "unfair", - "unfold", - "unhappy", - "uniform", - "unique", - "unit", - "universe", - "unknown", - "unlock", - "until", - "unusual", - "unveil", - "update", - "upgrade", - "uphold", - "upon", - "upper", - "upset", - "urban", - "urge", - "usage", - "use", - "used", - "useful", - "useless", - "usual", - "utility", - "vacant", - "vacuum", - "vague", - "valid", - "valley", - "valve", - "van", - "vanish", - "vapor", - "various", - "vast", - "vault", - "vehicle", - "velvet", - "vendor", - "venture", - "venue", - "verb", - "verify", - "version", - "very", - "vessel", - "veteran", - "viable", - "vibrant", - "vicious", - "victory", - "video", - "view", - "village", - "vintage", - "violin", - "virtual", - "virus", - "visa", - "visit", - "visual", - "vital", - "vivid", - "vocal", - "voice", - "void", - "volcano", - "volume", - "vote", - "voyage", - "wage", - "wagon", - "wait", - "walk", - "wall", - "walnut", - "want", - "warfare", - "warm", - "warrior", - "wash", - "wasp", - "waste", - "water", - "wave", - "way", - "wealth", - "weapon", - "wear", - "weasel", - "weather", - "web", - "wedding", - "weekend", - "weird", - "welcome", - "west", - "wet", - "whale", - "what", - "wheat", - "wheel", - "when", - "where", - "whip", - "whisper", - "wide", - "width", - "wife", - "wild", - "will", - "win", - "window", - "wine", - "wing", - "wink", - "winner", - "winter", - "wire", - "wisdom", - "wise", - "wish", - "witness", - "wolf", - "woman", - "wonder", - "wood", - "wool", - "word", - "work", - "world", - "worry", - "worth", - "wrap", - "wreck", - "wrestle", - "wrist", - "write", - "wrong", - "yard", - "year", - "yellow", - "you", - "young", - "youth", - "zebra", - "zero", - "zone", - "zoo" + public fun isPasswordSeed(entropy: ByteArray): Boolean { + val pbdkf2Sha512 = PKCSS2ParametersGenerator( + digest = Digest("SHA-512"), + password = entropy, + salt = DEFAULT_PASSWORD_SALT.toByteArray(), + iterationCount = DEFAULT_PASSWORD_ITERATIONS ) + return pbdkf2Sha512.generateDerivedParameters(512).first() == 1.toByte() + } } } diff --git a/ton-kotlin-mnemonic/src/commonMain/kotlin/org/ton/mnemonic/MnemonicWordList.kt b/ton-kotlin-mnemonic/src/commonMain/kotlin/org/ton/mnemonic/MnemonicWordList.kt new file mode 100644 index 00000000..ae11302c --- /dev/null +++ b/ton-kotlin-mnemonic/src/commonMain/kotlin/org/ton/mnemonic/MnemonicWordList.kt @@ -0,0 +1,2052 @@ +package org.ton.mnemonic + +internal val MNEMONIC_WORD_LIST = arrayOf( + "abandon", + "ability", + "able", + "about", + "above", + "absent", + "absorb", + "abstract", + "absurd", + "abuse", + "access", + "accident", + "account", + "accuse", + "achieve", + "acid", + "acoustic", + "acquire", + "across", + "act", + "action", + "actor", + "actress", + "actual", + "adapt", + "add", + "addict", + "address", + "adjust", + "admit", + "adult", + "advance", + "advice", + "aerobic", + "affair", + "afford", + "afraid", + "again", + "age", + "agent", + "agree", + "ahead", + "aim", + "air", + "airport", + "aisle", + "alarm", + "album", + "alcohol", + "alert", + "alien", + "all", + "alley", + "allow", + "almost", + "alone", + "alpha", + "already", + "also", + "alter", + "always", + "amateur", + "amazing", + "among", + "amount", + "amused", + "analyst", + "anchor", + "ancient", + "anger", + "angle", + "angry", + "animal", + "ankle", + "announce", + "annual", + "another", + "answer", + "antenna", + "antique", + "anxiety", + "any", + "apart", + "apology", + "appear", + "apple", + "approve", + "april", + "arch", + "arctic", + "area", + "arena", + "argue", + "arm", + "armed", + "armor", + "army", + "around", + "arrange", + "arrest", + "arrive", + "arrow", + "art", + "artefact", + "artist", + "artwork", + "ask", + "aspect", + "assault", + "asset", + "assist", + "assume", + "asthma", + "athlete", + "atom", + "attack", + "attend", + "attitude", + "attract", + "auction", + "audit", + "august", + "aunt", + "author", + "auto", + "autumn", + "average", + "avocado", + "avoid", + "awake", + "aware", + "away", + "awesome", + "awful", + "awkward", + "axis", + "baby", + "bachelor", + "bacon", + "badge", + "bag", + "balance", + "balcony", + "ball", + "bamboo", + "banana", + "banner", + "bar", + "barely", + "bargain", + "barrel", + "base", + "basic", + "basket", + "battle", + "beach", + "bean", + "beauty", + "because", + "become", + "beef", + "before", + "begin", + "behave", + "behind", + "believe", + "below", + "belt", + "bench", + "benefit", + "best", + "betray", + "better", + "between", + "beyond", + "bicycle", + "bid", + "bike", + "bind", + "biology", + "bird", + "birth", + "bitter", + "black", + "blade", + "blame", + "blanket", + "blast", + "bleak", + "bless", + "blind", + "blood", + "blossom", + "blouse", + "blue", + "blur", + "blush", + "board", + "boat", + "body", + "boil", + "bomb", + "bone", + "bonus", + "book", + "boost", + "border", + "boring", + "borrow", + "boss", + "bottom", + "bounce", + "box", + "boy", + "bracket", + "brain", + "brand", + "brass", + "brave", + "bread", + "breeze", + "brick", + "bridge", + "brief", + "bright", + "bring", + "brisk", + "broccoli", + "broken", + "bronze", + "broom", + "brother", + "brown", + "brush", + "bubble", + "buddy", + "budget", + "buffalo", + "build", + "bulb", + "bulk", + "bullet", + "bundle", + "bunker", + "burden", + "burger", + "burst", + "bus", + "business", + "busy", + "butter", + "buyer", + "buzz", + "cabbage", + "cabin", + "cable", + "cactus", + "cage", + "cake", + "call", + "calm", + "camera", + "camp", + "can", + "canal", + "cancel", + "candy", + "cannon", + "canoe", + "canvas", + "canyon", + "capable", + "capital", + "captain", + "car", + "carbon", + "card", + "cargo", + "carpet", + "carry", + "cart", + "case", + "cash", + "casino", + "castle", + "casual", + "cat", + "catalog", + "catch", + "category", + "cattle", + "caught", + "cause", + "caution", + "cave", + "ceiling", + "celery", + "cement", + "census", + "century", + "cereal", + "certain", + "chair", + "chalk", + "champion", + "change", + "chaos", + "chapter", + "charge", + "chase", + "chat", + "cheap", + "check", + "cheese", + "chef", + "cherry", + "chest", + "chicken", + "chief", + "child", + "chimney", + "choice", + "choose", + "chronic", + "chuckle", + "chunk", + "churn", + "cigar", + "cinnamon", + "circle", + "citizen", + "city", + "civil", + "claim", + "clap", + "clarify", + "claw", + "clay", + "clean", + "clerk", + "clever", + "click", + "client", + "cliff", + "climb", + "clinic", + "clip", + "clock", + "clog", + "close", + "cloth", + "cloud", + "clown", + "club", + "clump", + "cluster", + "clutch", + "coach", + "coast", + "coconut", + "code", + "coffee", + "coil", + "coin", + "collect", + "color", + "column", + "combine", + "come", + "comfort", + "comic", + "common", + "company", + "concert", + "conduct", + "confirm", + "congress", + "connect", + "consider", + "control", + "convince", + "cook", + "cool", + "copper", + "copy", + "coral", + "core", + "corn", + "correct", + "cost", + "cotton", + "couch", + "country", + "couple", + "course", + "cousin", + "cover", + "coyote", + "crack", + "cradle", + "craft", + "cram", + "crane", + "crash", + "crater", + "crawl", + "crazy", + "cream", + "credit", + "creek", + "crew", + "cricket", + "crime", + "crisp", + "critic", + "crop", + "cross", + "crouch", + "crowd", + "crucial", + "cruel", + "cruise", + "crumble", + "crunch", + "crush", + "cry", + "crystal", + "cube", + "culture", + "cup", + "cupboard", + "curious", + "current", + "curtain", + "curve", + "cushion", + "custom", + "cute", + "cycle", + "dad", + "damage", + "damp", + "dance", + "danger", + "daring", + "dash", + "daughter", + "dawn", + "day", + "deal", + "debate", + "debris", + "decade", + "december", + "decide", + "decline", + "decorate", + "decrease", + "deer", + "defense", + "define", + "defy", + "degree", + "delay", + "deliver", + "demand", + "demise", + "denial", + "dentist", + "deny", + "depart", + "depend", + "deposit", + "depth", + "deputy", + "derive", + "describe", + "desert", + "design", + "desk", + "despair", + "destroy", + "detail", + "detect", + "develop", + "device", + "devote", + "diagram", + "dial", + "diamond", + "diary", + "dice", + "diesel", + "diet", + "differ", + "digital", + "dignity", + "dilemma", + "dinner", + "dinosaur", + "direct", + "dirt", + "disagree", + "discover", + "disease", + "dish", + "dismiss", + "disorder", + "display", + "distance", + "divert", + "divide", + "divorce", + "dizzy", + "doctor", + "document", + "dog", + "doll", + "dolphin", + "domain", + "donate", + "donkey", + "donor", + "door", + "dose", + "double", + "dove", + "draft", + "dragon", + "drama", + "drastic", + "draw", + "dream", + "dress", + "drift", + "drill", + "drink", + "drip", + "drive", + "drop", + "drum", + "dry", + "duck", + "dumb", + "dune", + "during", + "dust", + "dutch", + "duty", + "dwarf", + "dynamic", + "eager", + "eagle", + "early", + "earn", + "earth", + "easily", + "east", + "easy", + "echo", + "ecology", + "economy", + "edge", + "edit", + "educate", + "effort", + "egg", + "eight", + "either", + "elbow", + "elder", + "electric", + "elegant", + "element", + "elephant", + "elevator", + "elite", + "else", + "embark", + "embody", + "embrace", + "emerge", + "emotion", + "employ", + "empower", + "empty", + "enable", + "enact", + "end", + "endless", + "endorse", + "enemy", + "energy", + "enforce", + "engage", + "engine", + "enhance", + "enjoy", + "enlist", + "enough", + "enrich", + "enroll", + "ensure", + "enter", + "entire", + "entry", + "envelope", + "episode", + "equal", + "equip", + "era", + "erase", + "erode", + "erosion", + "error", + "erupt", + "escape", + "essay", + "essence", + "estate", + "eternal", + "ethics", + "evidence", + "evil", + "evoke", + "evolve", + "exact", + "example", + "excess", + "exchange", + "excite", + "exclude", + "excuse", + "execute", + "exercise", + "exhaust", + "exhibit", + "exile", + "exist", + "exit", + "exotic", + "expand", + "expect", + "expire", + "explain", + "expose", + "express", + "extend", + "extra", + "eye", + "eyebrow", + "fabric", + "face", + "faculty", + "fade", + "faint", + "faith", + "fall", + "false", + "fame", + "family", + "famous", + "fan", + "fancy", + "fantasy", + "farm", + "fashion", + "fat", + "fatal", + "father", + "fatigue", + "fault", + "favorite", + "feature", + "february", + "federal", + "fee", + "feed", + "feel", + "female", + "fence", + "festival", + "fetch", + "fever", + "few", + "fiber", + "fiction", + "field", + "figure", + "file", + "film", + "filter", + "final", + "find", + "fine", + "finger", + "finish", + "fire", + "firm", + "first", + "fiscal", + "fish", + "fit", + "fitness", + "fix", + "flag", + "flame", + "flash", + "flat", + "flavor", + "flee", + "flight", + "flip", + "float", + "flock", + "floor", + "flower", + "fluid", + "flush", + "fly", + "foam", + "focus", + "fog", + "foil", + "fold", + "follow", + "food", + "foot", + "force", + "forest", + "forget", + "fork", + "fortune", + "forum", + "forward", + "fossil", + "foster", + "found", + "fox", + "fragile", + "frame", + "frequent", + "fresh", + "friend", + "fringe", + "frog", + "front", + "frost", + "frown", + "frozen", + "fruit", + "fuel", + "fun", + "funny", + "furnace", + "fury", + "future", + "gadget", + "gain", + "galaxy", + "gallery", + "game", + "gap", + "garage", + "garbage", + "garden", + "garlic", + "garment", + "gas", + "gasp", + "gate", + "gather", + "gauge", + "gaze", + "general", + "genius", + "genre", + "gentle", + "genuine", + "gesture", + "ghost", + "giant", + "gift", + "giggle", + "ginger", + "giraffe", + "girl", + "give", + "glad", + "glance", + "glare", + "glass", + "glide", + "glimpse", + "globe", + "gloom", + "glory", + "glove", + "glow", + "glue", + "goat", + "goddess", + "gold", + "good", + "goose", + "gorilla", + "gospel", + "gossip", + "govern", + "gown", + "grab", + "grace", + "grain", + "grant", + "grape", + "grass", + "gravity", + "great", + "green", + "grid", + "grief", + "grit", + "grocery", + "group", + "grow", + "grunt", + "guard", + "guess", + "guide", + "guilt", + "guitar", + "gun", + "gym", + "habit", + "hair", + "half", + "hammer", + "hamster", + "hand", + "happy", + "harbor", + "hard", + "harsh", + "harvest", + "hat", + "have", + "hawk", + "hazard", + "head", + "health", + "heart", + "heavy", + "hedgehog", + "height", + "hello", + "helmet", + "help", + "hen", + "hero", + "hidden", + "high", + "hill", + "hint", + "hip", + "hire", + "history", + "hobby", + "hockey", + "hold", + "hole", + "holiday", + "hollow", + "home", + "honey", + "hood", + "hope", + "horn", + "horror", + "horse", + "hospital", + "host", + "hotel", + "hour", + "hover", + "hub", + "huge", + "human", + "humble", + "humor", + "hundred", + "hungry", + "hunt", + "hurdle", + "hurry", + "hurt", + "husband", + "hybrid", + "ice", + "icon", + "idea", + "identify", + "idle", + "ignore", + "ill", + "illegal", + "illness", + "image", + "imitate", + "immense", + "immune", + "impact", + "impose", + "improve", + "impulse", + "inch", + "include", + "income", + "increase", + "index", + "indicate", + "indoor", + "industry", + "infant", + "inflict", + "inform", + "inhale", + "inherit", + "initial", + "inject", + "injury", + "inmate", + "inner", + "innocent", + "input", + "inquiry", + "insane", + "insect", + "inside", + "inspire", + "install", + "intact", + "interest", + "into", + "invest", + "invite", + "involve", + "iron", + "island", + "isolate", + "issue", + "item", + "ivory", + "jacket", + "jaguar", + "jar", + "jazz", + "jealous", + "jeans", + "jelly", + "jewel", + "job", + "join", + "joke", + "journey", + "joy", + "judge", + "juice", + "jump", + "jungle", + "junior", + "junk", + "just", + "kangaroo", + "keen", + "keep", + "ketchup", + "key", + "kick", + "kid", + "kidney", + "kind", + "kingdom", + "kiss", + "kit", + "kitchen", + "kite", + "kitten", + "kiwi", + "knee", + "knife", + "knock", + "know", + "lab", + "label", + "labor", + "ladder", + "lady", + "lake", + "lamp", + "language", + "laptop", + "large", + "later", + "latin", + "laugh", + "laundry", + "lava", + "law", + "lawn", + "lawsuit", + "layer", + "lazy", + "leader", + "leaf", + "learn", + "leave", + "lecture", + "left", + "leg", + "legal", + "legend", + "leisure", + "lemon", + "lend", + "length", + "lens", + "leopard", + "lesson", + "letter", + "level", + "liar", + "liberty", + "library", + "license", + "life", + "lift", + "light", + "like", + "limb", + "limit", + "link", + "lion", + "liquid", + "list", + "little", + "live", + "lizard", + "load", + "loan", + "lobster", + "local", + "lock", + "logic", + "lonely", + "long", + "loop", + "lottery", + "loud", + "lounge", + "love", + "loyal", + "lucky", + "luggage", + "lumber", + "lunar", + "lunch", + "luxury", + "lyrics", + "machine", + "mad", + "magic", + "magnet", + "maid", + "mail", + "main", + "major", + "make", + "mammal", + "man", + "manage", + "mandate", + "mango", + "mansion", + "manual", + "maple", + "marble", + "march", + "margin", + "marine", + "market", + "marriage", + "mask", + "mass", + "master", + "match", + "material", + "math", + "matrix", + "matter", + "maximum", + "maze", + "meadow", + "mean", + "measure", + "meat", + "mechanic", + "medal", + "media", + "melody", + "melt", + "member", + "memory", + "mention", + "menu", + "mercy", + "merge", + "merit", + "merry", + "mesh", + "message", + "metal", + "method", + "middle", + "midnight", + "milk", + "million", + "mimic", + "mind", + "minimum", + "minor", + "minute", + "miracle", + "mirror", + "misery", + "miss", + "mistake", + "mix", + "mixed", + "mixture", + "mobile", + "model", + "modify", + "mom", + "moment", + "monitor", + "monkey", + "monster", + "month", + "moon", + "moral", + "more", + "morning", + "mosquito", + "mother", + "motion", + "motor", + "mountain", + "mouse", + "move", + "movie", + "much", + "muffin", + "mule", + "multiply", + "muscle", + "museum", + "mushroom", + "music", + "must", + "mutual", + "myself", + "mystery", + "myth", + "naive", + "name", + "napkin", + "narrow", + "nasty", + "nation", + "nature", + "near", + "neck", + "need", + "negative", + "neglect", + "neither", + "nephew", + "nerve", + "nest", + "net", + "network", + "neutral", + "never", + "news", + "next", + "nice", + "night", + "noble", + "noise", + "nominee", + "noodle", + "normal", + "north", + "nose", + "notable", + "note", + "nothing", + "notice", + "novel", + "now", + "nuclear", + "number", + "nurse", + "nut", + "oak", + "obey", + "object", + "oblige", + "obscure", + "observe", + "obtain", + "obvious", + "occur", + "ocean", + "october", + "odor", + "off", + "offer", + "office", + "often", + "oil", + "okay", + "old", + "olive", + "olympic", + "omit", + "once", + "one", + "onion", + "online", + "only", + "open", + "opera", + "opinion", + "oppose", + "option", + "orange", + "orbit", + "orchard", + "order", + "ordinary", + "organ", + "orient", + "original", + "orphan", + "ostrich", + "other", + "outdoor", + "outer", + "output", + "outside", + "oval", + "oven", + "over", + "own", + "owner", + "oxygen", + "oyster", + "ozone", + "pact", + "paddle", + "page", + "pair", + "palace", + "palm", + "panda", + "panel", + "panic", + "panther", + "paper", + "parade", + "parent", + "park", + "parrot", + "party", + "pass", + "patch", + "path", + "patient", + "patrol", + "pattern", + "pause", + "pave", + "payment", + "peace", + "peanut", + "pear", + "peasant", + "pelican", + "pen", + "penalty", + "pencil", + "people", + "pepper", + "perfect", + "permit", + "person", + "pet", + "phone", + "photo", + "phrase", + "physical", + "piano", + "picnic", + "picture", + "piece", + "pig", + "pigeon", + "pill", + "pilot", + "pink", + "pioneer", + "pipe", + "pistol", + "pitch", + "pizza", + "place", + "planet", + "plastic", + "plate", + "play", + "please", + "pledge", + "pluck", + "plug", + "plunge", + "poem", + "poet", + "point", + "polar", + "pole", + "police", + "pond", + "pony", + "pool", + "popular", + "portion", + "position", + "possible", + "post", + "potato", + "pottery", + "poverty", + "powder", + "power", + "practice", + "praise", + "predict", + "prefer", + "prepare", + "present", + "pretty", + "prevent", + "price", + "pride", + "primary", + "print", + "priority", + "prison", + "private", + "prize", + "problem", + "process", + "produce", + "profit", + "program", + "project", + "promote", + "proof", + "property", + "prosper", + "protect", + "proud", + "provide", + "public", + "pudding", + "pull", + "pulp", + "pulse", + "pumpkin", + "punch", + "pupil", + "puppy", + "purchase", + "purity", + "purpose", + "purse", + "push", + "put", + "puzzle", + "pyramid", + "quality", + "quantum", + "quarter", + "question", + "quick", + "quit", + "quiz", + "quote", + "rabbit", + "raccoon", + "race", + "rack", + "radar", + "radio", + "rail", + "rain", + "raise", + "rally", + "ramp", + "ranch", + "random", + "range", + "rapid", + "rare", + "rate", + "rather", + "raven", + "raw", + "razor", + "ready", + "real", + "reason", + "rebel", + "rebuild", + "recall", + "receive", + "recipe", + "record", + "recycle", + "reduce", + "reflect", + "reform", + "refuse", + "region", + "regret", + "regular", + "reject", + "relax", + "release", + "relief", + "rely", + "remain", + "remember", + "remind", + "remove", + "render", + "renew", + "rent", + "reopen", + "repair", + "repeat", + "replace", + "report", + "require", + "rescue", + "resemble", + "resist", + "resource", + "response", + "result", + "retire", + "retreat", + "return", + "reunion", + "reveal", + "review", + "reward", + "rhythm", + "rib", + "ribbon", + "rice", + "rich", + "ride", + "ridge", + "rifle", + "right", + "rigid", + "ring", + "riot", + "ripple", + "risk", + "ritual", + "rival", + "river", + "road", + "roast", + "robot", + "robust", + "rocket", + "romance", + "roof", + "rookie", + "room", + "rose", + "rotate", + "rough", + "round", + "route", + "royal", + "rubber", + "rude", + "rug", + "rule", + "run", + "runway", + "rural", + "sad", + "saddle", + "sadness", + "safe", + "sail", + "salad", + "salmon", + "salon", + "salt", + "salute", + "same", + "sample", + "sand", + "satisfy", + "satoshi", + "sauce", + "sausage", + "save", + "say", + "scale", + "scan", + "scare", + "scatter", + "scene", + "scheme", + "school", + "science", + "scissors", + "scorpion", + "scout", + "scrap", + "screen", + "script", + "scrub", + "sea", + "search", + "season", + "seat", + "second", + "secret", + "section", + "security", + "seed", + "seek", + "segment", + "select", + "sell", + "seminar", + "senior", + "sense", + "sentence", + "series", + "service", + "session", + "settle", + "setup", + "seven", + "shadow", + "shaft", + "shallow", + "share", + "shed", + "shell", + "sheriff", + "shield", + "shift", + "shine", + "ship", + "shiver", + "shock", + "shoe", + "shoot", + "shop", + "short", + "shoulder", + "shove", + "shrimp", + "shrug", + "shuffle", + "shy", + "sibling", + "sick", + "side", + "siege", + "sight", + "sign", + "silent", + "silk", + "silly", + "silver", + "similar", + "simple", + "since", + "sing", + "siren", + "sister", + "situate", + "six", + "size", + "skate", + "sketch", + "ski", + "skill", + "skin", + "skirt", + "skull", + "slab", + "slam", + "sleep", + "slender", + "slice", + "slide", + "slight", + "slim", + "slogan", + "slot", + "slow", + "slush", + "small", + "smart", + "smile", + "smoke", + "smooth", + "snack", + "snake", + "snap", + "sniff", + "snow", + "soap", + "soccer", + "social", + "sock", + "soda", + "soft", + "solar", + "soldier", + "solid", + "solution", + "solve", + "someone", + "song", + "soon", + "sorry", + "sort", + "soul", + "sound", + "soup", + "source", + "south", + "space", + "spare", + "spatial", + "spawn", + "speak", + "special", + "speed", + "spell", + "spend", + "sphere", + "spice", + "spider", + "spike", + "spin", + "spirit", + "split", + "spoil", + "sponsor", + "spoon", + "sport", + "spot", + "spray", + "spread", + "spring", + "spy", + "square", + "squeeze", + "squirrel", + "stable", + "stadium", + "staff", + "stage", + "stairs", + "stamp", + "stand", + "start", + "state", + "stay", + "steak", + "steel", + "stem", + "step", + "stereo", + "stick", + "still", + "sting", + "stock", + "stomach", + "stone", + "stool", + "story", + "stove", + "strategy", + "street", + "strike", + "strong", + "struggle", + "student", + "stuff", + "stumble", + "style", + "subject", + "submit", + "subway", + "success", + "such", + "sudden", + "suffer", + "sugar", + "suggest", + "suit", + "summer", + "sun", + "sunny", + "sunset", + "super", + "supply", + "supreme", + "sure", + "surface", + "surge", + "surprise", + "surround", + "survey", + "suspect", + "sustain", + "swallow", + "swamp", + "swap", + "swarm", + "swear", + "sweet", + "swift", + "swim", + "swing", + "switch", + "sword", + "symbol", + "symptom", + "syrup", + "system", + "table", + "tackle", + "tag", + "tail", + "talent", + "talk", + "tank", + "tape", + "target", + "task", + "taste", + "tattoo", + "taxi", + "teach", + "team", + "tell", + "ten", + "tenant", + "tennis", + "tent", + "term", + "test", + "text", + "thank", + "that", + "theme", + "then", + "theory", + "there", + "they", + "thing", + "this", + "thought", + "three", + "thrive", + "throw", + "thumb", + "thunder", + "ticket", + "tide", + "tiger", + "tilt", + "timber", + "time", + "tiny", + "tip", + "tired", + "tissue", + "title", + "toast", + "tobacco", + "today", + "toddler", + "toe", + "together", + "toilet", + "token", + "tomato", + "tomorrow", + "tone", + "tongue", + "tonight", + "tool", + "tooth", + "top", + "topic", + "topple", + "torch", + "tornado", + "tortoise", + "toss", + "total", + "tourist", + "toward", + "tower", + "town", + "toy", + "track", + "trade", + "traffic", + "tragic", + "train", + "transfer", + "trap", + "trash", + "travel", + "tray", + "treat", + "tree", + "trend", + "trial", + "tribe", + "trick", + "trigger", + "trim", + "trip", + "trophy", + "trouble", + "truck", + "true", + "truly", + "trumpet", + "trust", + "truth", + "try", + "tube", + "tuition", + "tumble", + "tuna", + "tunnel", + "turkey", + "turn", + "turtle", + "twelve", + "twenty", + "twice", + "twin", + "twist", + "two", + "type", + "typical", + "ugly", + "umbrella", + "unable", + "unaware", + "uncle", + "uncover", + "under", + "undo", + "unfair", + "unfold", + "unhappy", + "uniform", + "unique", + "unit", + "universe", + "unknown", + "unlock", + "until", + "unusual", + "unveil", + "update", + "upgrade", + "uphold", + "upon", + "upper", + "upset", + "urban", + "urge", + "usage", + "use", + "used", + "useful", + "useless", + "usual", + "utility", + "vacant", + "vacuum", + "vague", + "valid", + "valley", + "valve", + "van", + "vanish", + "vapor", + "various", + "vast", + "vault", + "vehicle", + "velvet", + "vendor", + "venture", + "venue", + "verb", + "verify", + "version", + "very", + "vessel", + "veteran", + "viable", + "vibrant", + "vicious", + "victory", + "video", + "view", + "village", + "vintage", + "violin", + "virtual", + "virus", + "visa", + "visit", + "visual", + "vital", + "vivid", + "vocal", + "voice", + "void", + "volcano", + "volume", + "vote", + "voyage", + "wage", + "wagon", + "wait", + "walk", + "wall", + "walnut", + "want", + "warfare", + "warm", + "warrior", + "wash", + "wasp", + "waste", + "water", + "wave", + "way", + "wealth", + "weapon", + "wear", + "weasel", + "weather", + "web", + "wedding", + "weekend", + "weird", + "welcome", + "west", + "wet", + "whale", + "what", + "wheat", + "wheel", + "when", + "where", + "whip", + "whisper", + "wide", + "width", + "wife", + "wild", + "will", + "win", + "window", + "wine", + "wing", + "wink", + "winner", + "winter", + "wire", + "wisdom", + "wise", + "wish", + "witness", + "wolf", + "woman", + "wonder", + "wood", + "wool", + "word", + "work", + "world", + "worry", + "worth", + "wrap", + "wreck", + "wrestle", + "wrist", + "write", + "wrong", + "yard", + "year", + "yellow", + "you", + "young", + "youth", + "zebra", + "zero", + "zone", + "zoo" +) diff --git a/ton-kotlin-mnemonic/src/commonTest/kotlin/org/ton/mnemonic/MnemonicTest.kt b/ton-kotlin-mnemonic/src/commonTest/kotlin/org/ton/mnemonic/MnemonicTest.kt index d6c99c15..e1ce9530 100644 --- a/ton-kotlin-mnemonic/src/commonTest/kotlin/org/ton/mnemonic/MnemonicTest.kt +++ b/ton-kotlin-mnemonic/src/commonTest/kotlin/org/ton/mnemonic/MnemonicTest.kt @@ -25,7 +25,7 @@ class MnemonicTest { } @Test - fun `mnemonic validation`() = runBlocking { + fun `mnemonic validation`() = runBlocking{ assertTrue(Mnemonic.isValid(arrayOf("kangaroo", "hen", "toddler", "resist"))) assertTrue(Mnemonic.isValid(arrayOf("disease", "adult", "device", "grit"))) assertFalse(Mnemonic.isValid(arrayOf("disease", "adult", "device", "grit"), "password")) diff --git a/ton-kotlin-tl/src/commonMain/kotlin/org/ton/tl/TlEncoder.kt b/ton-kotlin-tl/src/commonMain/kotlin/org/ton/tl/TlEncoder.kt index 0a1a992b..336bdb6a 100644 --- a/ton-kotlin-tl/src/commonMain/kotlin/org/ton/tl/TlEncoder.kt +++ b/ton-kotlin-tl/src/commonMain/kotlin/org/ton/tl/TlEncoder.kt @@ -1,7 +1,7 @@ package org.ton.tl import io.ktor.utils.io.core.* -import org.ton.crypto.sha256 +import org.ton.crypto.digest.sha256 public interface TlEncoder { public fun encode(output: Output, value: T): Unit = encode(TlWriter(output), value)