From 0222b967bc900e97daba24a41cd1714b398f0b0c Mon Sep 17 00:00:00 2001 From: Ugljesa Jovanovic Date: Mon, 22 Feb 2021 22:55:14 +0100 Subject: [PATCH] Make sample use box --- .../kotlin/crypto/sample/MainActivity.kt | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/sample/src/androidMain/kotlin/com/ionspin/kotlin/crypto/sample/MainActivity.kt b/sample/src/androidMain/kotlin/com/ionspin/kotlin/crypto/sample/MainActivity.kt index aad7e8c..938802d 100644 --- a/sample/src/androidMain/kotlin/com/ionspin/kotlin/crypto/sample/MainActivity.kt +++ b/sample/src/androidMain/kotlin/com/ionspin/kotlin/crypto/sample/MainActivity.kt @@ -8,10 +8,17 @@ import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.ionspin.kotlin.crypto.LibsodiumInitializer.sodiumJna import com.ionspin.kotlin.crypto.TmpAccessor +import com.ionspin.kotlin.crypto.box.Box +import com.ionspin.kotlin.crypto.box.BoxCorruptedOrTamperedDataException +import com.ionspin.kotlin.crypto.box.crypto_box_NONCEBYTES import com.ionspin.kotlin.crypto.hash.Hash +import com.ionspin.kotlin.crypto.util.decodeFromUByteArray import com.ionspin.kotlin.crypto.util.encodeToUByteArray import com.ionspin.kotlin.crypto.util.toHexString import kotlinx.android.synthetic.main.activity_main.* +import java.lang.StringBuilder +import kotlin.random.Random +import kotlin.random.nextUBytes class MainActivity : AppCompatActivity() { @@ -20,9 +27,23 @@ class MainActivity : AppCompatActivity() { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val hash = Hash.sha512("123".encodeToUByteArray()) - helloWorldTextView.setText("Hash (SHA512) of 123: ${hash.toHexString()} \nSodium version: ${TmpAccessor.getVersion()}") - + val message = "Message message message".encodeToUByteArray() + val senderKeypair = Box.keypair() + val recipientKeypair = Box.keypair() + val messageNonce = Random(0).nextUBytes(crypto_box_NONCEBYTES) + val encrypted = Box.easy(message, messageNonce, recipientKeypair.publicKey, senderKeypair.secretKey) + val decrypted = Box.openEasy(encrypted, messageNonce, senderKeypair.publicKey, recipientKeypair.secretKey) + val builder = StringBuilder() + builder.appendLine("Decrypted: ${decrypted.decodeFromUByteArray()}") + try { + val tampered = encrypted.copyOf() + tampered[1] = 0U + Box.openEasy(tampered, messageNonce, senderKeypair.publicKey, recipientKeypair.secretKey) + } catch (exception : Exception) { + builder.appendLine("And caught tamper") + } + helloWorldTextView.setText(builder.toString()) } }