Export (0) Print
Expand All

Rfc2898DeriveBytes.GetBytes Method

Returns a pseudo-random key from a password, salt and iteration count.

Namespace: System.Security.Cryptography
Assembly: mscorlib (in mscorlib.dll)

public:
virtual array<unsigned char>^ GetBytes (
	int cb
) override
public byte[] GetBytes (
	int cb
)
public override function GetBytes (
	cb : int
) : byte[]
Not applicable.

Parameters

cb

The number of pseudo-random key bytes to generate.

Return Value

A byte array filled with pseudo-random key bytes.

Exception typeCondition

ArgumentOutOfRangeException

cb is out of range. This parameter requires a non-negative number.

The Rfc2898DeriveBytes class implements PBKDF2 functionality by using a pseudorandom number generator based on HMACSHA1. The Rfc2898DeriveBytes class takes a password, a salt, and an iteration count, and then generates keys through calls to the GetBytes method. Repeated calls to this method will not generate the same key; instead, appending two calls of the GetBytes method with a cb parameter value of 20 is the equivalent of calling the GetBytes method once with a cb parameter value of 40.

The following code example uses the Rfc2898DeriveBytes class to create two identical keys for the TripleDES class. It then encrypts and decrypts some data using the keys.

try
{
   Rfc2898DeriveBytes ^ k1 = gcnew Rfc2898DeriveBytes( pwd1,salt1,myIterations );
   Rfc2898DeriveBytes ^ k2 = gcnew Rfc2898DeriveBytes( pwd1,salt1 );

   // Encrypt the data.
   TripleDES^ encAlg = TripleDES::Create();
   encAlg->Key = k1->GetBytes( 16 );
   MemoryStream^ encryptionStream = gcnew MemoryStream;
   CryptoStream^ encrypt = gcnew CryptoStream( encryptionStream,encAlg->CreateEncryptor(),CryptoStreamMode::Write );
   array<Byte>^utfD1 = (gcnew System::Text::UTF8Encoding( false ))->GetBytes( data1 );

try {
    Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes(pwd1, salt1,
        myIterations);
    Rfc2898DeriveBytes k2 = new Rfc2898DeriveBytes(pwd1, salt1);
    // Encrypt the data.
    TripleDES encAlg = TripleDES.Create();
    encAlg.set_Key(k1.GetBytes(16));
    MemoryStream encryptionStream = new MemoryStream();
    CryptoStream encrypt = new CryptoStream(encryptionStream, 
        encAlg.CreateEncryptor(), CryptoStreamMode.Write);
    ubyte utfD1[] = (new System.Text.UTF8Encoding(false)).
        GetBytes(data1);

Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

Community Additions

ADD
Show:
© 2014 Microsoft