Correctly managing Shared Secrets

This commit is contained in:
Vitor Pamplona
2023-07-29 15:29:51 -04:00
parent 2fdb4e47b0
commit 16a7fdffcf
5 changed files with 118 additions and 15 deletions
@@ -65,7 +65,7 @@ object CryptoUtils {
}
fun encryptXChaCha(msg: String, privateKey: ByteArray, pubKey: ByteArray): EncryptedInfo {
val sharedSecret = getSharedSecret(privateKey, pubKey)
val sharedSecret = getSharedSecretXChaCha(privateKey, pubKey)
return encryptXChaCha(msg, sharedSecret)
}
@@ -94,7 +94,7 @@ object CryptoUtils {
}
fun decryptXChaCha(encryptedInfo: EncryptedInfo, privateKey: ByteArray, pubKey: ByteArray): String {
val sharedSecret = getSharedSecret(privateKey, pubKey)
val sharedSecret = getSharedSecretXChaCha(privateKey, pubKey)
return decryptXChaCha(encryptedInfo, sharedSecret)
}
@@ -132,6 +132,12 @@ object CryptoUtils {
*/
fun getSharedSecret(privateKey: ByteArray, pubKey: ByteArray): ByteArray =
secp256k1.pubKeyTweakMul(Hex.decode("02") + pubKey, privateKey).copyOfRange(1, 33)
/**
* @return 32B shared secret
*/
fun getSharedSecretXChaCha(privateKey: ByteArray, pubKey: ByteArray): ByteArray =
sha256(secp256k1.pubKeyTweakMul(Hex.decode("02") + pubKey, privateKey).copyOfRange(1, 33))
}
fun Int.toByteArray(): ByteArray {
@@ -3,7 +3,6 @@ package com.vitorpamplona.amethyst.service
import com.vitorpamplona.amethyst.ui.actions.ImmutableListOfLists
fun String.isUTF16Char(pos: Int): Boolean {
println("Test $pos ${Character.charCount(this.codePointAt(pos))}")
return Character.charCount(this.codePointAt(pos)) == 2
}
@@ -30,7 +30,7 @@ class GiftWrapEvent(
}
fun unwrap(privKey: ByteArray) = try {
plainContent(privKey)?.let { println("$it"); fromJson(it, Client.lenient) }
plainContent(privKey)?.let { fromJson(it, Client.lenient) }
} catch (e: Exception) {
Log.e("UnwrapError", "Couldn't Decrypt the content", e)
null
@@ -40,17 +40,13 @@ class GiftWrapEvent(
if (content.isBlank()) return null
return try {
val sharedSecret = CryptoUtils.getSharedSecret(privKey, pubKey.hexToByteArray())
val sharedSecret = CryptoUtils.getSharedSecretXChaCha(privKey, pubKey.hexToByteArray())
val toDecrypt = gson.fromJson<EncryptedInfo>(
content,
EncryptedInfo::class.java
)
println(toDecrypt.ciphertext)
println(toDecrypt.nonce)
println(toDecrypt.v)
return CryptoUtils.decryptXChaCha(toDecrypt, sharedSecret)
} catch (e: Exception) {
Log.w("GeneralList", "Error decrypting the message ${e.message}")
@@ -69,7 +65,7 @@ class GiftWrapEvent(
createdAt: Long = TimeUtils.now()
): GiftWrapEvent {
val privateKey = CryptoUtils.privkeyCreate() // GiftWrap is always a random key
val sharedSecret = CryptoUtils.getSharedSecret(privateKey, recipientPubKey.hexToByteArray())
val sharedSecret = CryptoUtils.getSharedSecretXChaCha(privateKey, recipientPubKey.hexToByteArray())
val content = gson.toJson(
CryptoUtils.encryptXChaCha(