Rfc2898DeriveBytes Class

Definition

Implements password-based key derivation functionality, PBKDF2, by using a pseudo-random number generator based on HMACSHA1.

C#
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes
C#
public class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes
C#
[System.Runtime.InteropServices.ComVisible(true)]
public class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes
Inheritance
Rfc2898DeriveBytes
Attributes

Examples

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

C#
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public class rfc2898test
{
    // Generate a key k1 with password pwd1 and salt salt1.
    // Generate a key k2 with password pwd1 and salt salt1.
    // Encrypt data1 with key k1 using symmetric encryption, creating edata1.
    // Decrypt edata1 with key k2 using symmetric decryption, creating data2.
    // data2 should equal data1.

    private const string usageText = "Usage: RFC2898 <password>\nYou must specify the password for encryption.\n";
    public static void Main(string[] passwordargs)
    {
        //If no file name is specified, write usage text.
        if (passwordargs.Length == 0)
        {
            Console.WriteLine(usageText);
        }
        else
        {
            string pwd1 = passwordargs[0];
            // Create a byte array to hold the random value.
            byte[] salt1 = new byte[8];
            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
            {
                // Fill the array with a random value.
                rng.GetBytes(salt1);
            }

            //data1 can be a string or contents of a file.
            string data1 = "Some test data";
            //The default iteration count is 1000 so the two methods use the same iteration count.
            int myIterations = 1000;
            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);

                encrypt.Write(utfD1, 0, utfD1.Length);
                encrypt.FlushFinalBlock();
                encrypt.Close();
                byte[] edata1 = encryptionStream.ToArray();
                k1.Reset();

                // Try to decrypt, thus showing it can be round-tripped.
                Aes decAlg = Aes.Create();
                decAlg.Key = k2.GetBytes(16);
                decAlg.IV = encAlg.IV;
                MemoryStream decryptionStreamBacking = new MemoryStream();
                CryptoStream decrypt = new CryptoStream(
decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
                decrypt.Write(edata1, 0, edata1.Length);
                decrypt.Flush();
                decrypt.Close();
                k2.Reset();
                string data2 = new UTF8Encoding(false).GetString(
decryptionStreamBacking.ToArray());

                if (!data1.Equals(data2))
                {
                    Console.WriteLine("Error: The two values are not equal.");
                }
                else
                {
                    Console.WriteLine("The two values are equal.");
                    Console.WriteLine("k1 iterations: {0}", k1.IterationCount);
                    Console.WriteLine("k2 iterations: {0}", k2.IterationCount);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
            }
        }
    }
}

Remarks

Rfc2898DeriveBytes takes a password, a salt, and an iteration count, and then generates keys through calls to the GetBytes method.

RFC 2898 includes methods for creating a key and initialization vector (IV) from a password and salt. You can use PBKDF2, a password-based key derivation function, to derive keys using a pseudo-random function that allows keys of virtually unlimited length to be generated. The Rfc2898DeriveBytes class can be used to produce a derived key from a base key and other parameters. In a password-based key derivation function, the base key is a password and the other parameters are a salt value and an iteration count.

For more information about PBKDF2, see RFC 2898, titled "PKCS #5: Password-Based Cryptography Specification Version 2.0". See section 5.2, "PBKDF2," for complete details.

Important

Never hard-code a password within your source code. Hard-coded passwords can be retrieved from an assembly by using the Ildasm.exe (IL Disassembler), by using a hexadecimal editor, or by simply opening up the assembly in a text editor such as Notepad.exe.

Constructors

Rfc2898DeriveBytes(Byte[], Byte[], Int32, HashAlgorithmName)

Initializes a new instance of the Rfc2898DeriveBytes class using the specified password, salt, number of iterations and the hash algorithm name to derive the key.

Rfc2898DeriveBytes(Byte[], Byte[], Int32)
Obsolete.

Initializes a new instance of the Rfc2898DeriveBytes class using a password, a salt, and number of iterations to derive the key.

Rfc2898DeriveBytes(String, Byte[], Int32, HashAlgorithmName)

Initializes a new instance of the Rfc2898DeriveBytes class using the specified password, salt, number of iterations and the hash algorithm name to derive the key.

Rfc2898DeriveBytes(String, Byte[], Int32)
Obsolete.

Initializes a new instance of the Rfc2898DeriveBytes class using a password, a salt, and number of iterations to derive the key.

Rfc2898DeriveBytes(String, Byte[])
Obsolete.

Initializes a new instance of the Rfc2898DeriveBytes class using a password and salt to derive the key.

Rfc2898DeriveBytes(String, Int32, Int32, HashAlgorithmName)

Initializes a new instance of the Rfc2898DeriveBytes class using the specified password, salt size, number of iterations and the hash algorithm name to derive the key.

Rfc2898DeriveBytes(String, Int32, Int32)
Obsolete.

Initializes a new instance of the Rfc2898DeriveBytes class using a password, a salt size, and number of iterations to derive the key.

Rfc2898DeriveBytes(String, Int32)
Obsolete.

Initializes a new instance of the Rfc2898DeriveBytes class using the password and salt size to derive the key.

Properties

HashAlgorithm

Gets the hash algorithm used for byte derivation.

IterationCount

Gets or sets the number of iterations for the operation.

Salt

Gets or sets the key salt value for the operation.

Methods

CryptDeriveKey(String, String, Int32, Byte[])
Obsolete.

Derives a cryptographic key from the Rfc2898DeriveBytes object.

Dispose()

When overridden in a derived class, releases all resources used by the current instance of the DeriveBytes class.

(Inherited from DeriveBytes)
Dispose(Boolean)

Releases the unmanaged resources used by the Rfc2898DeriveBytes class and optionally releases the managed resources.

Dispose(Boolean)

When overridden in a derived class, releases the unmanaged resources used by the DeriveBytes class and optionally releases the managed resources.

(Inherited from DeriveBytes)
Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBytes(Int32)

Returns the pseudo-random key for this object.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
Pbkdf2(Byte[], Byte[], Int32, HashAlgorithmName, Int32)

Creates a PBKDF2 derived key from password bytes.

Pbkdf2(ReadOnlySpan<Byte>, ReadOnlySpan<Byte>, Int32, HashAlgorithmName, Int32)

Creates a PBKDF2 derived key from password bytes.

Pbkdf2(ReadOnlySpan<Byte>, ReadOnlySpan<Byte>, Span<Byte>, Int32, HashAlgorithmName)

Fills a buffer with a PBKDF2 derived key.

Pbkdf2(ReadOnlySpan<Char>, ReadOnlySpan<Byte>, Int32, HashAlgorithmName, Int32)

Creates a PBKDF2 derived key from a password.

Pbkdf2(ReadOnlySpan<Char>, ReadOnlySpan<Byte>, Span<Byte>, Int32, HashAlgorithmName)

Fills a buffer with a PBKDF2 derived key.

Pbkdf2(String, Byte[], Int32, HashAlgorithmName, Int32)

Creates a PBKDF2 derived key from a password.

Reset()

Resets the state of the operation.

ToString()

Returns a string that represents the current object.

(Inherited from Object)

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

See also