Examples for Module 04


C# Examples:
Visual Basic Examples:
 

How to Generate a Symmetric Key From a Password

// Check the length and variety of a password public bool IsValidPassword(string password) { bool retval = false; Regex r = new Regex( @"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*\W)", RegexOptions.Singleline); if ((password.Length >= 9) && (r.IsMatch(password))) retval = true; return retval; } // Creating a key from a password // Generate a 16 byte salt RandomNumberGenerator rNum = RandomNumberGenerator.Create(); byte [] salt = new byte[16]; rNum.GetBytes(salt); // Generate a 16 byte (128 bit) key from a password and salt PasswordDeriveBytes passDerBytes = new PasswordDeriveBytes( password, salt); byte [] key = passDerBytes.GetBytes(16);

Return to Table of Contents

How to Encrypt Data with a Symmetric Algorithm

// Create and configure the symmetric algorithm object Rijndael cryptoAlg = Rijndael.Create(); // Assume key is a 16 byte array, as generated in the code // sample in the previous topic cryptoAlg.Key = key; // Create the file stream for the encrypted data // Assume filename is a string with a path to a file FileStream fileStm = new FileStream( filename, FileMode.Create); // Write the salt and initialization vector to the file fileStm.Write(salt, 0, salt.Length); fileStm.Write(cryptoAlg.IV, 0, cryptoAlg.IV.Length); // Create the CryptoStream and encrypt the data CryptoStream cryptoStm = new CryptoStream(fileStm, cryptoAlg.CreateEncryptor(), CryptoStreamMode.Write); // Assume output is an array of bytes you want to encrypt cryptoStm.Write(output, 0, output.Length); cryptoStm.FlushFinalBlock(); cryptoStm.Close();

Return to Table of Contents

How to Decrypt Data with a Symmetric Algorithm

// Create the symmetric algorithm object Rijndael cryptoAlg = Rijndael.Create(); // Open the encrypted file // Assume filename is a string with a path to a file FileStream encFileStm = new FileStream(filename, FileMode.Open); // Declare the variables and read the values from the file byte [] salt = new byte[16]; byte [] IV = new byte[cryptoAlg.IV.Length]; encFileStm.Read(salt, 0, salt.Length); encFileStm.Read(IV, 0, IV.Length); // Regenerate the key and set up the algorithm // Assume password is a string containing the password PasswordDeriveBytes passDerBytes = new PasswordDeriveBytes( password, salt); byte [] key = passDerBytes.GetBytes(16); cryptoAlg.Key = key; cryptoAlg.IV = IV; // Create the CryptoStream for reading and decrypting data CryptoStream cryptoStream = new CryptoStream(encFileStm, cryptoAlg.CreateDecryptor(), CryptoStreamMode.Read); // Loop through the data in the file, decrypting it int bytesRead = 0; byte [] buffer = new byte[256]; do { bytesRead = cryptoStream.Read(buffer, 0, 256); // buffer now contains decrypted data, code to use // the decrypted data goes here } while (bytesRead > 0); // Close the CryptoStream cryptoStream.Close();

Return to Table of Contents

How to Configure an Asymmetric Algorithm

// Create an instance of the default RSA implementation RSA cryptoAlg = RSA.Create(); // Create the CspParameters and pass it to the algorithm CspParameters cspParms = new CspParameters(1, null, "My RSA Key"); RSACryptoServiceProvider alg = new RSACryptoServiceProvider( cspParms); // Creating and loading test keys private void createTestKey(string filename) { // Create a new instance of an RSA algorithm with a // random key and save the key to an XML file RSA alg = RSA.Create(); string key = alg.ToXmlString(true); FileStream fs = new FileStream(filename, FileMode.Create); StreamWriter sw = new StreamWriter(fs); sw.Write(key); sw.Close(); } private RSA loadTestKey(string filename) { // Load an XML string with key information from a // file and set it on a new RSA algorithm object FileStream fs = new FileStream(filename, FileMode.Open); StreamReader sr = new StreamReader(fs); string key = sr.ReadToEnd(); sr.Close(); RSA alg = RSA.Create(); alg.FromXmlString(key); return alg; }

Return to Table of Contents

How to Encrypt and Decrypt Data with an Asymmetric Algorithm

// This method takes an instance of an RSA algorithm and // some data and returns the encrypted data with padding private byte[] encryptRSA(RSA cryptoAlg, byte[] data) { RSAPKCS1KeyExchangeFormatter formatter = new RSAPKCS1KeyExchangeFormatter(cryptoAlg); byte[] encData = formatter.CreateKeyExchange(data); return encData; } // This method takes an instance of an RSA algorithm and // some encrypted data and returns the decrypted data // Note: the key information set on the RSA algorithm must // include a private key private byte[] decryptRSA(RSA cryptoAlg, byte[] encData) { RSAPKCS1KeyExchangeDeformatter deformatter = new RSAPKCS1KeyExchangeDeformatter(cryptoAlg); byte[] data = deformatter.DecryptKeyExchange(encData); return data; } // Create a new instance of an RSA algorithm with a random // key RSACryptoServiceProvider cryptoAlg = new RSACryptoServiceProvider(); // Encrypt the data, the second argument to the Encrypt // method determines the type of padding used // Assume data is an array of bytes byte[] encData = cryptoAlg.Encrypt(data, false); // Decrypt the encrypted data byte[] decData = cryptoAlg.Decrypt(encData, false);

Return to Table of Contents

How to Hash Data

// This method takes some data as an array of bytes and // computes the SHA1 hash of the data private byte[] computeSHA1HashFromBytes(byte[] data) { SHA1 hashAlg = SHA1.Create(); byte[] hashValue = hashAlg.ComputeHash(data); return hashValue; } // This method takes some data as a stream and // computes the SHA1 hash of the data private byte[] computeSHA1HashFromStream(Stream stream) { SHA1 hashAlg = SHA1.Create(); byte[] hashValue = hashAlg.ComputeHash(stream); return hashValue; } // This method takes two file names, a source file and // a destination file, copies the contents of the source // file to the destination file, and then writes the hash // value of the data to the end of the destination file private void writeFileWithSHA512Hash(string sourceFile, string destFile) { // Create the Hash and FileStream objects SHA512 hashAlg = SHA512.Create(); FileStream sourceStream = new FileStream(sourceFile, FileMode.Open); FileStream destStream = new FileStream (destFile, FileMode.Create); // Create a CryptoStream that will hash the source // data as we read it CryptoStream hashedSourceStream = new CryptoStream( sourceStream, hashAlg, CryptoStreamMode.Read); // Loop through the data 1K at a time, hashing the input // data as it is read and writing it to the output file int bytesRead = 0; byte[] buffer = new byte[1024]; do { bytesRead = hashedSourceStream.Read(buffer, 0, 1024); destStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); hashedSourceStream.Close(); // Write the hash value to the end of the output file destStream.Write(hashAlg.Hash, 0, hashAlg.Hash.Length); destStream.Close(); }

Return to Table of Contents

How to Sign Data

// Using RSA's SignHash and VerifyHash // This method takes some data as an array of bytes and // generates an RSA signature for the data private byte[] computeRSASignatureWithSHA1(byte[] data) { SHA1 hashAlg = SHA1.Create(); RSACryptoServiceProvider cryptoAlg = new RSACryptoServiceProvider(); byte[] hashValue = hashAlg.ComputeHash(data); byte[] signature = cryptoAlg.SignHash(hashValue, "1.3.14.3.2.26"); return signature; } // This method takes some data as an array of bytes and // and a signature and verifies the signature against the // data, returning true if the signature is verified private bool verifyRSASignatureWithSHA1(byte[] data, byte[] signature) { SHA1 hashAlg = SHA1.Create(); RSACryptoServiceProvider cryptoAlg = new RSACryptoServiceProvider(); byte[] hashValue = hashAlg.ComputeHash(data); bool sigsMatch = cryptoAlg.VerifyHash(hashValue, "1.3.14.3.2.26", signature); return sigsMatch; } // Using RSA's SignData and VerifyData // This method takes some data as an array of bytes and // generates an RSA signature for the data private byte[] computeRSASignatureWithSHA1(byte[] data) { RSACryptoServiceProvider cryptoAlg = new RSACryptoServiceProvider(); byte[] signature = cryptoAlg.SignData(data, "SHA1"); return signature; } // This method takes some data as an array of bytes and // and a signature and verifies the signature against the // data, returning true if the signature is verified private bool verifyRSASignatureWithSHA1(byte[] data, byte[] signature) { RSACryptoServiceProvider cryptoAlg = new RSACryptoServiceProvider(); bool sigsMatch = cryptoAlg.VerifyData(data, "SHA1", signature); return sigsMatch; } // Using DSA's CreateSignature and VerifySignature // This method takes some data as an array of bytes and // generates a DSA signature for the data private byte[] computeDSASignature(byte[] data) { SHA1 hashAlg = SHA1.Create(); DSACryptoServiceProvider cryptoAlg = new DSACryptoServiceProvider(); byte[] hashValue = hashAlg.ComputeHash(data); byte[] signature = cryptoAlg.CreateSignature(hashValue); return signature; } // This method takes some data as an array of bytes and // and a signature and verifies the signature against the // data, returning true if the signature is verified private bool verifyDSASignature(byte[] data, byte[] signature) { SHA1 hashAlg = SHA1.Create(); DSACryptoServiceProvider cryptoAlg = new DSACryptoServiceProvider(); byte[] hashValue = hashAlg.ComputeHash(data); bool sigsMatch = cryptoAlg.VerifySignature(hashValue, signature); return sigsMatch; }

Return to Table of Contents

How to Generate a Symmetric Key From a Password

' Check the length and variety of a password Public Function IsValidPassword(ByVal password As String) _ As Boolean Dim retval As Boolean = false Dim r As Regex = New Regex( _ "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*\W)", _ RegexOptions.Singleline) If ((password.Length >= 9) And (r.IsMatch(password))) Then retval = True End If Return retval End Function ' Generate a 16 byte salt Dim rNum As RandomNumberGenerator = _ RandomNumberGenerator.Create() Dim salt(15) As Byte rNum.GetBytes(salt) ' Generate a 16 byte (128 bit) key from a password and salt Dim passDerBytes As New PasswordDeriveBytes(password, salt) Dim key() As Byte = passDerBytes.GetBytes(16)

Return to Table of Contents

How to Encrypt Data with a Symmetric Algorithm

' Create and configure the symmetric algorithm object Dim cryptoAlg As Rijndael = Rijndael.Create() ' Assume key is a 16 byte array, as generated in the code ' sample in the previous topic cryptoAlg.Key = key ' Create the file stream for the encrypted data ' Assume filename is a string with a path to a file Dim fileStm As New FileStream(filename, FileMode.Create) ' Write the salt and initialization vector to the file fileStm.Write(salt, 0, salt.Length) fileStm.Write(cryptoAlg.IV, 0, cryptoAlg.IV.Length) ' Create the CryptoStream and encrypt the data Dim cryptoStm As New CryptoStream(fileStm, _ cryptoAlg.CreateEncryptor(), _ CryptoStreamMode.Write) ' Assume output is an array of bytes you want to encrypt cryptoStm.Write(output, 0, output.Length) cryptoStm.FlushFinalBlock() cryptoStm.Close()

Return to Table of Contents

How to Decrypt Data with a Symmetric Algorithm

' Create the symmetric algorithm object Dim cryptoAlg As Rijndael = Rijndael.Create() ' Open the encrypted file ' Assume filename is a string with a path to a file Dim encFileStm As New FileStream(filename, FileMode.Open) ' Declare the variables and read the values from the file Dim salt(15) As Byte Dim IV(cryptoAlg.IV.Length - 1) As Byte encFileStm.Read(salt, 0, salt.Length) encFileStm.Read(IV, 0, IV.Length) ' Regenerate the key and set up the algorithm ' Assume password is a string containing the password Dim passDerBytes As New PasswordDeriveBytes(password, salt) Dim key() As Byte = passDerBytes.GetBytes(16) cryptoAlg.Key = key cryptoAlg.IV = IV ' Create the CryptoStream for reading and decrypting data Dim cryptoStream As New CryptoStream(encFileStm, _ cryptoAlg.CreateDecryptor(), _ CryptoStreamMode.Read) ' Loop through the data in the file, decrypting it Dim bytesRead As Integer = 0 Dim buffer(255) As Byte Do bytesRead = cryptoStream.Read(buffer, 0, 256) ' buffer now contains decrypted data, code to use ' the decrypted data goes here Loop While bytesRead > 0 ' Close the CryptoStream cryptoStream.Close()

Return to Table of Contents

How to Configure an Asymmetric Algorithm

' Create an instance of the default RSA implementation Dim cryptoAlg As RSA = RSA.Create() ' Create the CspParameters and pass it to the algorithm Dim cspParms As New CspParameters(1, Nothing, "My RSA Key") Dim alg As New RSACryptoServiceProvider(cspParms) ' Creating and loading test keys Private Sub createTestKey(ByVal filename As String) ' Create a new instance of an RSA algorithm with a ' random key and save the key to an XML file Dim alg As RSA = RSA.Create() Dim key As String = alg.ToXmlString(True) Dim fs As New FileStream(filename, FileMode.Create) Dim sw As New StreamWriter(fs) sw.Write(key) sw.Close() End Sub Private Function loadTestKey(ByVal filename As String) As RSA ' Load an XML string with key information from a ' file and set it on a new RSA algorithm object Dim fs As New FileStream(filename, FileMode.Open) Dim sr As New StreamReader(fs) Dim key As String = sr.ReadToEnd() sr.Close() Dim alg As RSA = RSA.Create() alg.FromXmlString(key) Return alg End Function

Return to Table of Contents

How to Encrypt and Decrypt Data with an Asymmetric Algorithm

' This method takes an instance of an RSA algorithm and ' some data and returns the encrypted data with padding Private Function encryptRSA(ByVal cryptoAlg As RSA, _ ByVal data() As Byte) As Byte() Dim formatter As New RSAPKCS1KeyExchangeFormatter( _ cryptoAlg) Dim encData As Byte() = formatter.CreateKeyExchange(data) Return encData End Function ' This method takes an instance of an RSA algorithm and ' some encrypted data and returns the decrypted data ' Note: the key information set on the RSA algorithm must ' include a private key Private Function decryptRSA(ByVal cryptoAlg As RSA, _ ByVal encData() As Byte) As Byte() Dim deformatter As New RSAPKCS1KeyExchangeDeformatter( _ cryptoAlg) Dim data() As Byte = deformatter.DecryptKeyExchange( _ encData) Return data End Function ' Create a new instance of an RSA algorithm with a random ' key Dim cryptoAlg As New RSACryptoServiceProvider() ' Encrypt the data, the second argument to the Encrypt ' method determines the type of padding used ' Assume data is an array of bytes Dim encData As Byte() = cryptoAlg.Encrypt(data, False) ' Decrypt the encrypted data Dim decData As Byte() = cryptoAlg.Decrypt(encData, False)

Return to Table of Contents

How to Hash Data

' This method takes some data as an array of bytes and ' computes the SHA1 hash of the data Private Function computeSHA1HashFromBytes( _ ByVal data() As Byte) As Byte() Dim hashAlg As SHA1 = SHA1.Create() Dim hashValue() As Byte = hashAlg.ComputeHash(data) Return hashValue End Function ' This method takes some data as a stream and ' computes the SHA1 hash of the data Private Function computeSHA1HashFromStream( _ ByVal stream As Stream) As Byte() Dim hashAlg As SHA1 = SHA1.Create() Dim hashValue() As Byte = hashAlg.ComputeHash(stream) Return hashValue End Function ' This method takes two file names, a source file and ' a destination file, copies the contents of the source ' file to the destination file, and then writes the hash ' value of the data to the end of the destination file Private Sub writeFileWithSHA512Hash( _ ByVal sourceFile As String, ByVal destFile As String) ' Create the Hash and FileStream objects Dim hashAlg As SHA512 = SHA512.Create() Dim sourceStream As New FileStream(sourceFile, _ FileMode.Open) Dim destStream As New FileStream(destFile, FileMode.Create) ' Create a CryptoStream that will hash the source ' data as we read it Dim hashedSourceStream As New CryptoStream(sourceStream, _ hashAlg, CryptoStreamMode.Read) ' Loop through the data 1K at a time, hashing the input ' data as it is read and writing it to the output file Dim bytesRead As Integer = 0 Dim buffer(1023) As Byte Do bytesRead = hashedSourceStream.Read(buffer, 0, 1024) destStream.Write(buffer, 0, bytesRead) Loop While bytesRead > 0 hashedSourceStream.Close() ' Write the hash value to the end of the output file destStream.Write(hashAlg.Hash, 0, hashAlg.Hash.Length) destStream.Close() End Sub

Return to Table of Contents

How to Sign Data

' This method takes some data as an array of bytes and ' generates an RSA signature for the data Private Function computeRSASignatureWithSHA1( _ ByVal data() As Byte) As Byte() Dim hashAlg As SHA1 = SHA1.Create() Dim cryptoAlg As New RSACryptoServiceProvider() Dim hashValue() As Byte = hashAlg.ComputeHash(data) Dim signature() As Byte = cryptoAlg.SignHash(hashValue, _ "1.3.14.3.2.26") Return signature End Function ' This method takes some data as an array of bytes and ' and a signature and verifies the signature against the ' data, returning true if the signature is verified Private Function verifyRSASignatureWithSHA1( _ ByVal data() As Byte, ByVal signature() As Byte) As Boolean Dim hashAlg As SHA1 = SHA1.Create() Dim cryptoAlg As New RSACryptoServiceProvider() Dim hashValue() As Byte = hashAlg.ComputeHash(data) Dim sigsMatch As Boolean = cryptoAlg.VerifyHash( _ hashValue, "1.3.14.3.2.26", signature) Return sigsMatch End Function ' This method takes some data as an array of bytes and ' generates an RSA signature for the data Private Function computeRSASignatureWithSHA1( _ ByVal data() As Byte) As Byte() Dim cryptoAlg As New RSACryptoServiceProvider() Dim signature() As Byte = cryptoAlg.SignData(data, "SHA1") Return signature End Function ' This method takes some data as an array of bytes and ' and a signature and verifies the signature against the ' data, returning true if the signature is verified Private Function verifyRSASignatureWithSHA1( _ ByVal data() As Byte, ByVal signature() As Byte) As Boolean Dim cryptoAlg As New RSACryptoServiceProvider() Dim sigsMatch As Boolean = cryptoAlg.VerifyData(data, _ "SHA1", signature) Return sigsMatch End Function ' This method takes some data as an array of bytes and ' generates a DSA signature for the data Private Function computeDSASignature(ByVal data() As Byte) _ As Byte() Dim hashAlg As SHA1 = SHA1.Create() Dim cryptoAlg As New DSACryptoServiceProvider() Dim hashValue() As Byte = hashAlg.ComputeHash(data) Dim signature() As Byte = cryptoAlg.CreateSignature( _ hashValue) Return signature End Function 'computeDSASignature ' This method takes some data as an array of bytes and ' and a signature and verifies the signature against the ' data, returning true if the signature is verified Private Function verifyDSASignature(ByVal data() As Byte, _ ByVal signature() As Byte) As Boolean Dim hashAlg As SHA1 = SHA1.Create() Dim cryptoAlg As New DSACryptoServiceProvider() Dim hashValue() As Byte = hashAlg.ComputeHash(data) Dim sigsMatch As Boolean = cryptoAlg.VerifySignature( _ hashValue, signature) Return sigsMatch End Function

Return to Table of Contents