CryptDeriveKey fails for AES algorithm name
I'm trying to implement AES encryption in my application. I have the following code to create a hashed version of the user password.
PasswordDeriveBytes passwdHash = new PasswordDeriveBytes( p开发者_运维百科assword, salt,
"SHA1", 128 );
byte[] keyBytes = passwdHash.CryptDeriveKey( "AES", "SHA1",
192, iv );
The second line throws a System.Security.Cryptography.CryptographicException
with the error message Object identifier (OID) is unknown
. I used Reflector to verify that the error is being thrown because CryptDeriveKey()
does not like the "AES" algorithm name (I'm using AesCryptoServiceProvider()
to perform the encryption). I tried changing the name to "AESManaged", "AES192" and "Rijndael" but they all throw the same exception.
How do I get this to work? Or is there an alternative method of deriving the key bytes? Also, is there any documentation on what the allowed algorithm name strings are? I can't find anything on the MSDN docs for that function.
I'm using Visual Studio 2008 and target .NET framework 3.5
Thanks in advance for your help!
Why do you want to derive a key from a password salt rather than the password itself? Usually you use the "raw" password and a salt; indeed in my book (grin) chapter 6 has the following sample.
private void GetKeyAndIVFromPasswordAndSalt(
string password,
byte[] salt,
SymmetricAlgorithm symmetricAlgorithm,
ref byte[] key,
ref byte[] iv)
{
Rfc2898DeriveBytes rfc2898DeriveBytes =
new Rfc2898DeriveBytes(password, salt);
key = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.KeySize / 8);
iv = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.BlockSize / 8);
}
Of course salt should be a cryptographically secure random byte array;
private static byte[] GenerateKeyGenerateRandomBytes(int length)
{
byte[] key = new byte[length];
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
provider.GetBytes(key);
return key;
}
Looks like this doesn't support AES: http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/61d85001-2eae-4419-b4bf-ce98d46f4d21/
I also found this: http://www.koders.com/csharp/fidDDE5F3FF54C91BC673350363EAECC0D815A68F92.aspx
It looks like Rijndael should work. It appears that the key size is only set to 16 though...
精彩评论