whyoleg/cryptography-kotlin

AES/GCM Key based on UUID

Closed this issue · 8 comments

Hello, is it possible to use a UUID (java.util.UUID) for a AES Key?

Hey!
Technically, yes, as a UUID is just 128 bits, it could be used as an AES 128-bit key.
Practically, no, as a UUID is not really cryptographically strong random bits. You can hash the UUID first, via SHA-256 or other KDFs, to get a better key material for AES 256.

Thanks for the fast answer!

Do you mean it like this?

fun uuidToAESKey(uuid: UUID): AES.GCM.Key {
    val provider = CryptographyProvider.Default
    val sha = provider.get(SHA256)
    val aes = provider.get(AES.GCM)

    val rawKey = sha.hasher().hashBlocking(uuid.toByteArray()).copyOf(32)
    val aesKey = aes.keyDecoder().decodeFromByteArrayBlocking(AES.Key.Format.RAW, rawKey)
    
    return aesKey;
}
fun UUID.toByteArray(): ByteArray {
    val buffer = ByteBuffer.allocate(16)
    buffer.putLong(this.mostSignificantBits)
    buffer.putLong(this.leastSignificantBits)
    return buffer.array()
}

Yeah, something like this.
Minor:

  • There is no need to call copyOf(32) as the output of SHA256 is already 256 bits
  • You can use kotlin.uuid.Uuid which provides toByteArray() out of the box :)

Thank you. :>

I also want to encrypt json files and decrypt them using a pin. I hashed the pin via argon2 (spring-security) should I use the argon2 hash to create the key or should I hash the bare pin with sha256 again?

It's hard for me to suggest the best way, but overall, there is no need to hash pin before, as argon2 is KDF that takes password as an input and outputs a high-entropy value that could be used as a key directly.

Also, I wanted to note that using just sha256 over UUID is fine only if you are not exposing this UUID to external users.

So basically just this for using the argon2 hash as the key? Btw which library would you suggest for Argon2id on KMP?

        val provider = CryptographyProvider.Default
        val aes = provider.get(AES.GCM)
        val aesKey = aes.keyDecoder().decodeFromByteArray(AES.Key.Format.RAW, hashedPin.toByteArray())

What should I do instead of just using sha256?

Hey there, I couldn't find or think of any different way. What would you suggest?

So basically just this for using the argon2 hash as the key?

Yeah, that could work.

Btw which library would you suggest for Argon2id on KMP?

I don't know about such libraries.

BouncyCastle and OpenSSL support argon2, and so someday they will be available in this library, but I have no dates. (#65)

Also, I will close the issue, as I feel like the question is answered :)
Feel free to start discussions in the future, if you want to ask a question, and not to report a bug/feature request, so that it will be easier to track issues that could be fixed somehow.