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.