0

I wrote a program in Python which is able to encrypt files with a key using the cryptography-fernet module. I also wrote a client in kotlin which is able to decrypt files (or at least text files, having trouble with images, see my other questions) which have been encrypted with the same key. When using one predefined key in both the kotlin and the python program, everything works perfectly, but when I try to use a key which has been derived from a password, python and kotlin generate different passwords even when using the same data. Here is my code:

import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import time, sys, os
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=b"2Yb8EwpYkMlycHxoKcmHuA==",iterations=100000)
k=base64.urlsafe_b64encode(kdf.derive("ductTapeIsMagic".encode()))
print(k)

And here the kotlin code:

val salt = Base64.getUrlDecoder().decode("2Yb8EwpYkMlycHxoKcmHuA==")
println(deriveKey("ductTapeIsMagic", salt))
@RequiresApi(Build.VERSION_CODES.O)
    fun deriveKey(password: String, salt: ByteArray): String {
        val iterations = 100000
        val derivedKeyLength = 256
        val spec = PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength)
        val secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
        val key = secretKeyFactory.generateSecret(spec).encoded
        return Base64.getUrlEncoder().encodeToString(key)
    }

I used the code provided here: Fernet encryption/decryption with python and kotlin Where it seemed to have worked, but in my case, the python script generates this output:

b'RKUatSkW3CFBd7F-lOfFfcmNVdQYEWn4xg3cHPdyHMk='

while kotlin generates this:

U4P0bVIGQaRxenH6tRRDChFsKU4s0A82ayul3RsbXxI=

Any ideas why these two generate different keys and what I can do to fix that? I can provide any additional information if needed. Any help would be greatly appreciated. Thanks in advance.

ductTapeIsMagic
  • 113
  • 1
  • 8
  • `32 != 256` for keylength ? – azro May 08 '23 at 09:01
  • The problem is, changing the keylength in kotlin to 32 results in an array out of bounds exception somewhere deep within the base64-module. Changing the keylength in python results in a much longer key in which the first 32 characters are still the same. Also, both generated keys have a length of 32 when printing, and it worked in the question from which i got the code. – ductTapeIsMagic May 08 '23 at 09:04
  • 2
    The `salt` in Python is base64 encoded while in Kotlin it is decoded first. – Michael Butscher May 08 '23 at 09:31
  • Well thank you very much that was it, now it works. I replaced the line in the kotlin program which decodes the salt with a simple "SALTSALTSALT".toByteArray(), now everything works perfectly. – ductTapeIsMagic May 08 '23 at 10:12

0 Answers0