From C# encryption key derivation to Ruby (PBKDF2)

570 Views Asked by At

I'm trying to rewrite the following key generation method written in C# into its Ruby equivalent:

        private static byte[] CreateKey(string password, int length)
        {
            var salt = new byte[] { 0x01, 0x02, 0x23, 0x34, 0x37, 0x48, 0x24, 0x63, 0x99, 0x04 };

            const int Iterations = 1000;
            using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, Iterations))
                return rfc2898DeriveBytes.GetBytes(length);
        }

I'm using PBKDF2 implementation. And here's my Ruby code:

def create_key password, length
    salt_a = [0x01, 0x02, 0x23, 0x34, 0x37, 0x48, 0x24, 0x63, 0x99, 0x04]
    salt = salt_a.pack('C*') # Think here there is something to change
    iterations = 1000
    derived_b = PBKDF2.new do |p| 
      p.password = password
      p.salt = salt
      p.iterations = iterations
      p.key_length = length
      p.hash_function = OpenSSL::Digest::SHA1
    end
    derived_b.bin_string # and here too
end

In order to work those two methods should return the same output. The problem is that I can't figure out how to do this. PBKDF2 implementations takes salt as String, but C# takes a byte array... I think the problem is there.

1

There are 1 best solutions below

0
On

If you can use a recent version of OpenSSL, then this worked for me:

SALT = [ 0x94, 0x67, 0x16, 0xe6, 0x20, 0xd4, 0x56, 0x46, 0x67, 0x56, 0x46, 0x56, 0x23 ].pack("c*")
PBKDF2_ITERATIONS = 1000

def create_key(password, length)
  OpenSSL::PKCS5::pbkdf2_hmac_sha1(password, SALT, PBKDF2_ITERATIONS, length)
end