Bewerken

Delen via


Rfc2898DeriveBytes.GetBytes(Int32) Method

Definition

Returns the pseudo-random key for this object.

public:
 override cli::array <System::Byte> ^ GetBytes(int cb);
public override byte[] GetBytes (int cb);
override this.GetBytes : int -> byte[]
Public Overrides Function GetBytes (cb As Integer) As Byte()

Parameters

cb
Int32

The number of pseudo-random key bytes to generate.

Returns

Byte[]

A byte array filled with pseudo-random key bytes.

Exceptions

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

Examples

The following example shows how to use the GetBytes method to get the key for an instance of Rfc2898DeriveBytes. This code example is part of a larger example provided for the Rfc2898DeriveBytes class.

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

   // Encrypt the data.
   Aes^ encAlg = Aes::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.
                Aes encAlg = Aes.Create();
                encAlg.Key = k1.GetBytes(16);
                MemoryStream encryptionStream = new MemoryStream();
                CryptoStream encrypt = new CryptoStream(encryptionStream,
encAlg.CreateEncryptor(), CryptoStreamMode.Write);
                byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(
data1);
Try
    Dim k1 As New Rfc2898DeriveBytes(pwd1, salt1, myIterations)
    Dim k2 As New Rfc2898DeriveBytes(pwd1, salt1)
    ' Encrypt the data.
    Dim encAlg As Aes = Aes.Create()
    encAlg.Key = k1.GetBytes(16)
    Dim encryptionStream As New MemoryStream()
    Dim encrypt As New CryptoStream(encryptionStream, encAlg.CreateEncryptor(), CryptoStreamMode.Write)
    Dim utfD1 As Byte() = New System.Text.UTF8Encoding(False).GetBytes(data1)

Remarks

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.

Applies to

See also