Convert Python PBKDF2HMAC to Ruby

262 views Asked by At

I have the following in python and want to transfer this to ruby. but i don't get it working. The original source is from here: https://github.com/HurricaneLabs/splunksecrets/blob/177d350a9164791c66139d11b4c63f5db83710b6/splunksecrets.py#L112

My "secret" is : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Python

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=b"disk-encryption",
    iterations=1,
    backend=default_backend()
)
key = kdf.derive(secret[:254])

print("KDF: %s" % key)

Ruby

  require 'openssl'

  kdf = OpenSSL::KDF.pbkdf2_hmac(
    secret,
    salt: 'disk-encryption',
    iterations: 1,
    length: 32,
    hash: 'SHA256'
  )

  puts "KDF: #{kdf.unpack1('H*')}"

Start and end are somehow the same, but the middle is not matching at all. I removed the \x from the python string to better read it.

org py KDF: b'\x0e\x04\xc2^Z\x04t\xddCh\x97E\xf7\xc9%o\xff\xb8o\x96\x0f\x8aA\xablg\x06\x85\\\xc0\xa3\xde'
Python KDF: b'0e04c2 ^Z04tddCh97Ef7c9%offb8o960f8aAablg0685\\             c0a3de'
Ruby   KDF:   0e04c2 5e5a0474dd43689745f7c9256fffb86f960f8a41ab6c6706855c c0a3de
1

There are 1 answers

0
rwaffen On

as Topaco said in the comments: everything is okay, its only the printout format which was misleading.

The interpretation of Ruby unpack1('H*') in Python is .hex(). So it should be:

print("KDF: %s" % key.hex())

So the KDF implementation in Ruby was ok and working all the time. Only got confused by printing out the values in the wrong format.