Archived Forum Post

Index of archived forum posts

Question:

How to Duplicate .NET's PasswordDeriveBytes?

Oct 15 '14 at 10:04

How can this C# code be duplicated in Chilkat?

string password = "abc123";

PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, new byte[] { 0x50, 0x66, 0x61, 0x6f, 0x20, 0x3d, 0x65, 0x64, 0x76, 0x66, 0x64, 0x65, 0x65 });

byte[] key = pdb.GetBytes(32); byte[] IV = pdb.GetBytes(16);


Answer

PasswordDerivedBytes is supposed to implement PBKDF1 as specified in RFC 2898. It turns out there's a bug in Microsoft's implementation because the output of PBKDF1 cannot be more than the size of the output of the hash function (which is 20 bytes for the default SHA1 hash function).

See http://stackoverflow.com/questions/9231754/c-sharp-passwordderivebytes-confusion
and also see https://bugzilla.novell.com/show_bug.cgi?id=316364

PBKDF1 is defined as follows in RFC 2898:

5.1 PBKDF1

PBKDF1 applies a hash function, which shall be MD2 [6], MD5 [19] or SHA-1 [18], to derive keys. The length of the derived key is bounded by the length of the hash function output, which is 16 octets for MD2 and MD5 and 20 octets for SHA-1. PBKDF1 is compatible with the key derivation process in PKCS #5 v1.5.

PBKDF1 is recommended only for compatibility with existing applications since the keys it produces may not be large enough for some applications.

PBKDF1 (P, S, c, dkLen)

Options: Hash underlying hash function

Input: P password, an octet string S salt, an eight-octet string c iteration count, a positive integer dkLen intended length in octets of derived key, a positive integer, at most 16 for MD2 or MD5 and 20 for SHA-1

Output: DK derived key, a dkLen-octet string

Steps:

  1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output
     "derived key too long" and stop.

  2. Apply the underlying hash function Hash for c iterations to the
     concatenation of the password P and the salt S, then extract
     the first dkLen octets to produce a derived key DK:

               T_1 = Hash (P || S) ,
               T_2 = Hash (T_1) ,
               ...
               T_c = Hash (T_{c-1}) ,
               DK = Tc<0..dkLen-1>

  3. Output the derived key DK.
</pre>