7

I have following code in C#

PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(32);

I am using "SHA1" hashing algorithm.

According to SHA1 definition, its generate 160 bits (20 bytes) key. My question is how GetBytes method get 32 bytes from DerivedPassword, what algorithm used behind GetBytes method?

Siddiqui
  • 7,662
  • 17
  • 81
  • 129

3 Answers3

11

Microsoft's implementation of original PKCS#5 (aka PBKDF1) include insecure extensions to provide more bytes than the hash function can provide (see bug reports here and here).

Even if it was not buggy you should avoid undocumented, proprietary extensions to standards (or you might never be able to decrypt your data in the future - at least not outside Windows.)

I strongly suggest you to use the newer Rfc2898DeriveBytes which implements PBKDF2 (PKCS#5 v2) which is available since .NET 2.0.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
poupou
  • 43,413
  • 6
  • 77
  • 174
5

what algorithm used behind GetBytes method?

It uses the algorithm PBKDF1, which is slightly modified to allow arbitrary key length. A replacement class, Rfc2898DeriveBytes uses PBKDF2.

You can read the Wikipedia Article on PBKDF2 for a general idea of what underlying concepts are making this work.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
4

The key derivation function uses a feature called Key Stretching. (Don't bother looking it up on Wikipedia, because the current article confuses the concept with Key Strengthening, which is something completely different.)

Key stretching is commonly done by applying a PRF (such as a hash function or a cipher) in either CTR mode, or by iterating it and concatenating the intermediate outputs.

For instance, if you use the CTR procedure, SHA-1 as PRF, and want 32 bytes of pseudo random output, you concatenate SHA1(keymaterial,0) with the first 12 bytes of SHA1(keymaterial,1).

Henrick Hellström
  • 2,556
  • 16
  • 18
  • thanks for your replay, can you give me little more explanation about CTR procedure. – Siddiqui Feb 11 '12 at 10:19
  • 1
    In this case, the numbers 0 and 1 could be represented by a single bit (remember SHA-1 operates on strings of bits as input), but usually (keymaterial,0) etc is defined as e.g. (a) keymaterial with a single byte (or word) 0 appended at the end, or (b) a full 64 byte input block with keymaterial first, some padding (usually bytes with value zero), and a single byte with value 0 at the end. – Henrick Hellström Feb 11 '12 at 10:28