mirror of
https://github.com/vitorpamplona/amethyst.git
synced 2025-03-17 21:31:57 +01:00
Refactors SHA-256 methods to its own class
This commit is contained in:
parent
0971b716e1
commit
5f577df819
@ -24,7 +24,7 @@ import androidx.benchmark.junit4.BenchmarkRule
|
||||
import androidx.benchmark.junit4.measureRepeated
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
|
||||
import com.vitorpamplona.quartz.crypto.CryptoUtils
|
||||
import com.vitorpamplona.quartz.crypto.sha256Hash
|
||||
import com.vitorpamplona.quartz.encoders.Nip01Serializer
|
||||
import com.vitorpamplona.quartz.events.Event
|
||||
import com.vitorpamplona.quartz.events.EventFactory
|
||||
@ -181,12 +181,12 @@ class EventBenchmark {
|
||||
|
||||
benchmarkRule.measureRepeated {
|
||||
// Should pass
|
||||
assertNotNull(CryptoUtils.sha256(byteArray))
|
||||
assertNotNull(sha256Hash(byteArray))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun checkIDHashPayload2Slow() {
|
||||
fun checkIDHashPayload2() {
|
||||
val event = Event.fromJson(payload2)
|
||||
benchmarkRule.measureRepeated {
|
||||
// Should pass
|
||||
@ -194,15 +194,6 @@ class EventBenchmark {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun checkIDHashPayload2Fast() {
|
||||
val event = Event.fromJson(payload2)
|
||||
benchmarkRule.measureRepeated {
|
||||
// Should pass
|
||||
assertTrue(event.hasCorrectIDHash2())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun eventSerializerTest() {
|
||||
val event = Event.fromJson(payload2)
|
||||
|
@ -21,6 +21,7 @@
|
||||
package com.vitorpamplona.quartz.crypto.nip01
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.vitorpamplona.quartz.crypto.sha256Hash
|
||||
import com.vitorpamplona.quartz.encoders.hexToByteArray
|
||||
import com.vitorpamplona.quartz.encoders.toHexKey
|
||||
import fr.acinq.secp256k1.Secp256k1
|
||||
@ -66,7 +67,7 @@ class Nip01Test {
|
||||
fun testDeterministicSign() {
|
||||
assertEquals(
|
||||
"1484d0e0bd62165e822e31f1f4cc8e1ce8e20c30a060e24fb0ecd7baf7c624f661fb7a3e4f0ddb43018e5f0b4892c929af64d8b7a86021aa081ec8231e3dfa37",
|
||||
nip01.signDeterministic(nip01.sha256("Test".toByteArray()), privateKey).toHexKey(),
|
||||
nip01.signDeterministic(sha256Hash("Test".toByteArray()), privateKey).toHexKey(),
|
||||
)
|
||||
}
|
||||
|
||||
@ -74,7 +75,7 @@ class Nip01Test {
|
||||
fun testSha256() {
|
||||
assertEquals(
|
||||
"532eaabd9574880dbf76b9b8cc00832c20a6ec113d682299550d7a6e0f345e25",
|
||||
nip01.sha256("Test".toByteArray()).toHexKey(),
|
||||
sha256Hash("Test".toByteArray()).toHexKey(),
|
||||
)
|
||||
}
|
||||
|
||||
@ -83,7 +84,7 @@ class Nip01Test {
|
||||
assertTrue(
|
||||
nip01.verify(
|
||||
"1484d0e0bd62165e822e31f1f4cc8e1ce8e20c30a060e24fb0ecd7baf7c624f661fb7a3e4f0ddb43018e5f0b4892c929af64d8b7a86021aa081ec8231e3dfa37".hexToByteArray(),
|
||||
nip01.sha256("Test".toByteArray()),
|
||||
sha256Hash("Test".toByteArray()),
|
||||
nip01.pubkeyCreate(privateKey),
|
||||
),
|
||||
)
|
||||
@ -93,17 +94,17 @@ class Nip01Test {
|
||||
fun testNonDeterministicSign() {
|
||||
assertNotEquals(
|
||||
"1484d0e0bd62165e822e31f1f4cc8e1ce8e20c30a060e24fb0ecd7baf7c624f661fb7a3e4f0ddb43018e5f0b4892c929af64d8b7a86021aa081ec8231e3dfa37",
|
||||
nip01.sign(nip01.sha256("Test".toByteArray()), privateKey).toHexKey(),
|
||||
nip01.sign(sha256Hash("Test".toByteArray()), privateKey).toHexKey(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testNonDeterministicSignVerify() {
|
||||
val signature = nip01.sign(nip01.sha256("Test".toByteArray()), privateKey)
|
||||
val signature = nip01.sign(sha256Hash("Test".toByteArray()), privateKey)
|
||||
assertTrue(
|
||||
nip01.verify(
|
||||
signature,
|
||||
nip01.sha256("Test".toByteArray()),
|
||||
sha256Hash("Test".toByteArray()),
|
||||
nip01.pubkeyCreate(privateKey),
|
||||
),
|
||||
)
|
||||
|
@ -25,6 +25,7 @@ import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
|
||||
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
|
||||
import com.vitorpamplona.quartz.crypto.KeyPair
|
||||
import com.vitorpamplona.quartz.crypto.nip01.Nip01
|
||||
import com.vitorpamplona.quartz.crypto.sha256Hash
|
||||
import com.vitorpamplona.quartz.encoders.hexToByteArray
|
||||
import com.vitorpamplona.quartz.encoders.toHexKey
|
||||
import fr.acinq.secp256k1.Secp256k1
|
||||
@ -34,7 +35,6 @@ import junit.framework.TestCase.assertNull
|
||||
import junit.framework.TestCase.fail
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@ -185,8 +185,5 @@ class NIP44v2Test {
|
||||
}
|
||||
}
|
||||
|
||||
private fun sha256Hex(data: ByteArray): String {
|
||||
// Creates a new buffer every time
|
||||
return MessageDigest.getInstance("SHA-256").digest(data).toHexKey()
|
||||
}
|
||||
private fun sha256Hex(data: ByteArray) = sha256Hash(data).toHexKey()
|
||||
}
|
||||
|
@ -74,7 +74,7 @@ object CryptoUtils {
|
||||
|
||||
fun sha256(data: ByteArray): ByteArray {
|
||||
// Creates a new buffer every time
|
||||
return nip01.sha256(data)
|
||||
return sha256Hash(data)
|
||||
}
|
||||
|
||||
fun decrypt(
|
||||
|
@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Copyright (c) 2024 Vitor Pamplona
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to use,
|
||||
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
|
||||
* Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
|
||||
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package com.vitorpamplona.quartz.crypto
|
||||
|
||||
import java.security.MessageDigest
|
||||
|
||||
fun sha256Hash(data: ByteArray): ByteArray {
|
||||
// Creates a new buffer every time
|
||||
return MessageDigest.getInstance("SHA-256").digest(data)
|
||||
}
|
@ -22,8 +22,8 @@ package com.vitorpamplona.quartz.crypto.nip01
|
||||
|
||||
import com.vitorpamplona.quartz.crypto.CryptoUtils
|
||||
import com.vitorpamplona.quartz.crypto.nextBytes
|
||||
import com.vitorpamplona.quartz.crypto.sha256Hash
|
||||
import fr.acinq.secp256k1.Secp256k1
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
|
||||
class Nip01(
|
||||
@ -54,10 +54,7 @@ class Nip01(
|
||||
pubKey: ByteArray,
|
||||
): Boolean = secp256k1.verifySchnorr(signature, hash, pubKey)
|
||||
|
||||
fun sha256(data: ByteArray): ByteArray {
|
||||
// Creates a new buffer every time
|
||||
return MessageDigest.getInstance("SHA-256").digest(data)
|
||||
}
|
||||
fun sha256(data: ByteArray) = sha256Hash(data)
|
||||
|
||||
fun signString(
|
||||
message: String,
|
||||
|
@ -21,7 +21,7 @@
|
||||
package com.vitorpamplona.quartz.crypto.nip06
|
||||
|
||||
import com.vitorpamplona.quartz.crypto.nip49.PBKDF
|
||||
import java.security.MessageDigest
|
||||
import com.vitorpamplona.quartz.crypto.sha256Hash
|
||||
|
||||
// CODE FROM: https://github.com/ACINQ/bitcoin-kmp/
|
||||
|
||||
@ -37,11 +37,6 @@ object Bip39Mnemonics {
|
||||
return zeroes + digits
|
||||
}
|
||||
|
||||
fun sha256(data: ByteArray): ByteArray {
|
||||
// Creates a new buffer every time
|
||||
return MessageDigest.getInstance("SHA-256").digest(data)
|
||||
}
|
||||
|
||||
private fun toBinary(x: ByteArray): List<Boolean> = x.map(Bip39Mnemonics::toBinary).flatten()
|
||||
|
||||
private fun fromBinary(bin: List<Boolean>): Int = bin.fold(0) { acc, flag -> if (flag) 2 * acc + 1 else 2 * acc }
|
||||
@ -84,7 +79,7 @@ object Bip39Mnemonics {
|
||||
val databits = bits.subList(0, bitlength)
|
||||
val checksumbits = bits.subList(bitlength, bits.size)
|
||||
val data = group(databits, 8).map { fromBinary(it) }.map { it.toByte() }.toByteArray()
|
||||
val check = toBinary(sha256(data)).take(data.size / 4)
|
||||
val check = toBinary(sha256Hash(data)).take(data.size / 4)
|
||||
require(check == checksumbits) { "invalid checksum" }
|
||||
}
|
||||
|
||||
@ -111,7 +106,7 @@ object Bip39Mnemonics {
|
||||
wordlist: Array<String>,
|
||||
): List<String> {
|
||||
require(wordlist.size == 2048) { "invalid word list (size should be 2048)" }
|
||||
val digits = toBinary(entropy) + toBinary(sha256(entropy)).take(entropy.size / 4)
|
||||
val digits = toBinary(entropy) + toBinary(sha256Hash(entropy)).take(entropy.size / 4)
|
||||
|
||||
return group(digits, 11).map(Bip39Mnemonics::fromBinary).map { wordlist[it] }
|
||||
}
|
||||
|
@ -24,9 +24,9 @@ import android.util.Log
|
||||
import com.goterl.lazysodium.SodiumAndroid
|
||||
import com.goterl.lazysodium.utils.Key
|
||||
import com.vitorpamplona.quartz.crypto.SharedKeyCache
|
||||
import com.vitorpamplona.quartz.crypto.sha256Hash
|
||||
import com.vitorpamplona.quartz.encoders.Hex
|
||||
import fr.acinq.secp256k1.Secp256k1
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
|
||||
@ -126,15 +126,10 @@ class Nip44v1(
|
||||
privateKey: ByteArray,
|
||||
pubKey: ByteArray,
|
||||
): ByteArray =
|
||||
sha256(
|
||||
sha256Hash(
|
||||
secp256k1.pubKeyTweakMul(h02 + pubKey, privateKey).copyOfRange(1, 33),
|
||||
)
|
||||
|
||||
fun sha256(data: ByteArray): ByteArray {
|
||||
// Creates a new buffer every time
|
||||
return MessageDigest.getInstance("SHA-256").digest(data)
|
||||
}
|
||||
|
||||
class EncryptedInfo(
|
||||
val ciphertext: ByteArray,
|
||||
val nonce: ByteArray,
|
||||
|
@ -35,10 +35,10 @@ import com.fasterxml.jackson.databind.module.SimpleModule
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer
|
||||
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
|
||||
import com.vitorpamplona.quartz.crypto.CryptoUtils
|
||||
import com.vitorpamplona.quartz.crypto.sha256Hash
|
||||
import com.vitorpamplona.quartz.encoders.ATag
|
||||
import com.vitorpamplona.quartz.encoders.Hex
|
||||
import com.vitorpamplona.quartz.encoders.HexKey
|
||||
import com.vitorpamplona.quartz.encoders.Nip01Serializer
|
||||
import com.vitorpamplona.quartz.encoders.Nip19Bech32
|
||||
import com.vitorpamplona.quartz.encoders.PoWRank
|
||||
import com.vitorpamplona.quartz.encoders.toHexKey
|
||||
@ -52,7 +52,6 @@ import com.vitorpamplona.quartz.utils.pointerSizeInBytes
|
||||
import com.vitorpamplona.quartz.utils.remove
|
||||
import com.vitorpamplona.quartz.utils.startsWith
|
||||
import java.math.BigDecimal
|
||||
import java.security.MessageDigest
|
||||
|
||||
@Immutable
|
||||
open class Event(
|
||||
@ -312,11 +311,6 @@ open class Event(
|
||||
return id.equals(generateId())
|
||||
}
|
||||
|
||||
fun hasCorrectIDHash2(): Boolean {
|
||||
if (id.isEmpty()) return false
|
||||
return id.equals(generateId2())
|
||||
}
|
||||
|
||||
fun hasVerifiedSignature(): Boolean {
|
||||
if (id.isEmpty() || sig.isEmpty()) return false
|
||||
return CryptoUtils.verifySignature(Hex.decode(sig), Hex.decode(id), Hex.decode(pubKey))
|
||||
@ -349,13 +343,7 @@ open class Event(
|
||||
|
||||
fun makeJsonForId(): String = makeJsonForId(pubKey, createdAt, kind, tags, content)
|
||||
|
||||
fun generateId(): String = CryptoUtils.sha256(makeJsonForId().toByteArray()).toHexKey()
|
||||
|
||||
fun generateId2(): String {
|
||||
val sha256 = MessageDigest.getInstance("SHA-256")
|
||||
Nip01Serializer().serializeEventInto(this, Nip01Serializer.BufferedDigestWriter(sha256))
|
||||
return sha256.digest().toHexKey()
|
||||
}
|
||||
fun generateId(): String = sha256Hash(makeJsonForId().toByteArray()).toHexKey()
|
||||
|
||||
private class EventDeserializer : StdDeserializer<Event>(Event::class.java) {
|
||||
override fun deserialize(
|
||||
|
@ -121,7 +121,7 @@ class Nip01SerializerTest {
|
||||
fun fastEventIdCheckTest() {
|
||||
val event = Event.fromJson(payload2)
|
||||
|
||||
assertEquals("98b574c3527f0ffb30b7271084e3f07480733c7289f8de424d29eae82e36c758", event.generateId2())
|
||||
assertEquals("98b574c3527f0ffb30b7271084e3f07480733c7289f8de424d29eae82e36c758", event.generateId())
|
||||
}
|
||||
|
||||
val payload3 = """
|
||||
@ -157,7 +157,7 @@ class Nip01SerializerTest {
|
||||
fun fastEventIdCheckTestPayload3() {
|
||||
val event = Event.fromJson(payload3)
|
||||
|
||||
assertEquals("6cccb576158965cf0f06fb4e476f85a02f0011ae783a4e905126a3db3871e43d", event.generateId2())
|
||||
assertEquals("6cccb576158965cf0f06fb4e476f85a02f0011ae783a4e905126a3db3871e43d", event.generateId())
|
||||
}
|
||||
|
||||
val payload4 = "{\"id\":\"5fd48fd3fb2890a00538067869306d788ff4331896360dc9c7e43d43e01b481b\",\"pubkey\":\"9770fb48aa3861dd393eb857e740f2df6f18e0ead43bad1d30c65e5c198200a6\",\"created_at\":1701673247,\"kind\":1,\"tags\":[[\"imeta\",\"url https://image.nostr.build/790b061d9661df88b06feb7448694cc421671da42217ca8381f02b4def63707f.jpg\",\"blurhash enF~?FRpNbkBjG.AkCbHfkafx_R+V^V_WVt9WBf6axoeoJf4bXWBaz\",\"dim 1536x2048\"],[\"imeta\",\"url https://video.nostr.build/3dd8562e8306c3128a72dee888c0fe587c2b24b8b643ae19b82010aaab95c37c.mp4\",\"blurhash e5A0~^S4R#W,j]~XR%s;o4j?s*M|t3t6ayxot9RiV[RjEH%3WBR%xb\",\"dim 720x1280\"],[\"imeta\",\"url https://image.nostr.build/9249f13cb8df68e00706f4f1434b8f0cd731b0515479df06353a0aef7a798619.jpg\",\"blurhash egFFpp\$LV?kCjs.TRiaej[fP9xIpoKf6fksls+WBbHj[xZn\$WWofjt\",\"dim 1920x3412\"],[\"t\",\"iceland\"],[\"r\",\"https://image.nostr.build/790b061d9661df88b06feb7448694cc421671da42217ca8381f02b4def63707f.jpg\"],[\"r\",\"https://video.nostr.build/3dd8562e8306c3128a72dee888c0fe587c2b24b8b643ae19b82010aaab95c37c.mp4\"],[\"r\",\"https://image.nostr.build/9249f13cb8df68e00706f4f1434b8f0cd731b0515479df06353a0aef7a798619.jpg\"]],\"content\":\"Icelandic calm to your heart \uD83D\uDC9A\uD83D\uDE0C\\n\\n(Memories from this summer)\\n\\n#Iceland , 2023 https://image.nostr.build/790b061d9661df88b06feb7448694cc421671da42217ca8381f02b4def63707f.jpg https://video.nostr.build/3dd8562e8306c3128a72dee888c0fe587c2b24b8b643ae19b82010aaab95c37c.mp4 https://image.nostr.build/9249f13cb8df68e00706f4f1434b8f0cd731b0515479df06353a0aef7a798619.jpg \",\"sig\":\"d6410be4b47bc97fca486eb619dd2507e7332bcd1049e405a047c90eedd2be46007c09d7702361b8442df78932e5da4055ee1c5fef08f938a4d39d828dc20957\"}"
|
||||
@ -180,7 +180,7 @@ class Nip01SerializerTest {
|
||||
val event = Event.fromJson(payload4)
|
||||
|
||||
// assertEquals(event.generateId(), event.generateId2())
|
||||
assertEquals("5fd48fd3fb2890a00538067869306d788ff4331896360dc9c7e43d43e01b481b", event.generateId2())
|
||||
assertEquals("5fd48fd3fb2890a00538067869306d788ff4331896360dc9c7e43d43e01b481b", event.generateId())
|
||||
}
|
||||
|
||||
val payload5 = "{\"id\":\"d1f097d3d9fcfb00df0c8ab5469be6484b14707d1e947c574ed636281d8dfd26\",\"pubkey\":\"dd664d5e4016433a8cd69f005ae1480804351789b59de5af06276de65633d319\",\"created_at\":1706435280,\"kind\":4550,\"tags\":[[\"a\",\"34550:026d8b7e7bcc2b417a84f10edb71b427fe76069905090b147b401a6cf60c3f27:Catholic\",\"wss://christpill.nostr1.com\"],[\"e\",\"0b8e4fade30fdb57f3887da224682fe9756ee79c408961e46393555bb0367022\"],[\"p\",\"026d8b7e7bcc2b417a84f10edb71b427fe76069905090b147b401a6cf60c3f27\"],[\"k\",\"1\"]],\"content\":\"{\\\"id\\\":\\\"0b8e4fade30fdb57f3887da224682fe9756ee79c408961e46393555bb0367022\\\",\\\"pubkey\\\":\\\"026d8b7e7bcc2b417a84f10edb71b427fe76069905090b147b401a6cf60c3f27\\\",\\\"created_at\\\":1698838786,\\\"kind\\\":1,\\\"tags\\\":[[\\\"a\\\",\\\"34550:026d8b7e7bcc2b417a84f10edb71b427fe76069905090b147b401a6cf60c3f27:Catholic\\\",\\\"\\\",\\\"reply\\\"],[\\\"t\\\",\\\"catholic\\\"],[\\\"t\\\",\\\"catholic\\\"]],\\\"content\\\":\\\"It's so funny at Mass, when you're a sacristan or something because everyone watches and emulates you, so if you forget to stand or kneel at the right moment, everyone remains seated.\\\\n\\\\nAnd when you're like, Oh woops! And stand up, there's a loud wave of people suddenly standing up, too. \uD83D\uDE02\\\\n\\\\n#catholic\\\",\\\"sig\\\":\\\"92c087e6364dd6c1fbf3bf5baddd66f0d86019fb3ba95e36135345d7c8b137f2147de8d628ec974eb493c2dbce2ca581c56c146d282f06a930280c7addc4d021\\\"}\",\"sig\":\"d67c067a08879138989275cb6f062f58e8a523b192bff5e65340becbac05060bb9c7ac6f75727c8fd2229f95a54fe404d18971950a72c1f17618535e7495e09d\"}"
|
||||
@ -203,6 +203,6 @@ class Nip01SerializerTest {
|
||||
val event = Event.fromJson(payload5)
|
||||
|
||||
// assertEquals(event.generateId(), event.generateId2())
|
||||
assertEquals("d1f097d3d9fcfb00df0c8ab5469be6484b14707d1e947c574ed636281d8dfd26", event.generateId2())
|
||||
assertEquals("d1f097d3d9fcfb00df0c8ab5469be6484b14707d1e947c574ed636281d8dfd26", event.generateId())
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user