whyoleg/cryptography-kotlin

Conversion to cryptography-kotlin

Closed this issue · 3 comments

if have this code in android kotlin that must convert to this library exactly.

I don't see a direct equivalent set of methods.

import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.Arrays
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

// other code

	private var secretKey: SecretKeySpec? = null
	private lateinit var key: ByteArray
	private const val ALGORITHM = "AES_256/ECB/PKCS5Padding"

	private fun prepareSecreteKey(myKey: String)
	{
		var sha: MessageDigest?
		try
		{
			key = myKey.toByteArray(StandardCharsets.UTF_8)
			sha = MessageDigest.getInstance("SHA-256")
			key = sha.digest(key)
			key = Arrays.copyOf(key, 32)
			secretKey = SecretKeySpec(
					key, ALGORITHM
									 )
		}
		catch (e: NoSuchAlgorithmException)
		{
			e.printStackTrace()
		}
	}

Hey, yes, API is rather different, but it's possible
Something like this should work:

@OptIn(
    // because of AES.ECB - you were warned
    DelicateCryptographyApi::class
)
private fun prepareSecreteKey(myKey: String) {
    val provider = CryptographyProvider.Default
    val sha = provider.get(SHA256)
    val aes = provider.get(AES.ECB)

    val rawKey = sha.hasher().hashBlocking(myKey.encodeToByteArray()).copyOf(32)
    val aesKey = aes.keyDecoder().decodeFromByteArrayBlocking(AES.Key.Format.RAW, rawKey)
    val cipher = aesKey.cipher(padding = true)

    // now you can use cipher
    val plaintext: ByteArray = "Hello world".encodeToByteArray()
    val ciphertext: ByteArray = cipher.encryptBlocking(plaintext)
}

Is there an option to specify the padding?
My algorithm is AES_256/ECB/PKCS5Padding

Yes, aesKey.cipher(padding = true) specifically says to use padding, and in case of AES it's PKCS5.
Could you create a self-contained example on what doesn't work at your side? May be there is some API usage error?