Make sample use box

This commit is contained in:
Ugljesa Jovanovic 2021-02-22 22:55:14 +01:00
parent f7815d009e
commit 0222b967bc
No known key found for this signature in database
GPG Key ID: 178E6DFCECCB0E0F

View File

@ -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())
}
}