数据加密

How To: Encrypt and Decrypt Data Using a Symmetric (Rijndael) Key

The code below demonstrates how to generate a persistent (i.e. non-random) symmetric key using the Rijndael (AES) algorithm and use this key to encrypt and decrypt a text string. The key is derived from several characteristics passed to encryption and decryption routines. Code samples are provided in C# and Visual Basic.NET.

Note: These examples are offered for demonstration purpose only. In a real application you may need to modify the code to make it more efficient. For example, instead of initializing encryptor and decryptor in Encrypt and Decrypt methods, you may want to do it once in a constructor and change the scope of both methods from static (Shared in Visual Basic) to instance. See also the How To Encrypt Data With Salt sample, which explains how encryption should be implemented in production applications. For additional information about symmetric-key encryption, check an MSDN sample describing how to create a general purpose encryption library.

None.gif C# code
None.gif
None.gif[printer
- friendly version] [code output] 
ExpandedBlockStart.gifContractedBlock.gif
/**/ ///
None.gif //  SAMPLE: Symmetric key encryption and decryption using Rijndael algorithm.
None.gif
//  
None.gif
//  To run this sample, create a new Visual C# project using the Console
None.gif
//  Application template and replace the contents of the Class1.cs file with
None.gif
//  the code below.
None.gif
//
None.gif
//  THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
None.gif
//  EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
None.gif
//  WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
None.gif
//  
None.gif
//  Copyright (C) 2003.  Obviex(TM).  All rights reserved.
None.gif
//  
None.gif
using  System;
None.gif
using  System.IO;
None.gif
using  System.Text;
None.gif
using  System.Security.Cryptography;
None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**/ /// <summary>
InBlock.gif
/// This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and 
InBlock.gif
/// decrypt data. As long as encryption and decryption routines use the same
InBlock.gif
/// parameters to generate the keys, the keys are guaranteed to be the same.
InBlock.gif
/// The class uses static functions with duplicate code to make it easier to
InBlock.gif
/// demonstrate encryption and decryption logic. In a real-life application, 
InBlock.gif
/// this may not be the most efficient way of handling encryption, so - as
InBlock.gif
/// soon as you feel comfortable with it - you may want to redesign this class.
ExpandedBlockEnd.gif
/// </summary>

None.gif public   class  RijndaelSimple
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// Encrypts specified plaintext using Rijndael symmetric key algorithm
InBlock.gif    
/// and returns a base64-encoded result.
InBlock.gif    
/// </summary>
InBlock.gif    
/// <param name="plainText">
InBlock.gif    
/// Plaintext value to be encrypted.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="passPhrase">
InBlock.gif    
/// Passphrase from which a pseudo-random password will be derived. The
InBlock.gif    
/// derived password will be used to generate the encryption key.
InBlock.gif    
/// Passphrase can be any string. In this example we assume that this
InBlock.gif    
/// passphrase is an ASCII string.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="saltValue">
InBlock.gif    
/// Salt value used along with passphrase to generate password. Salt can
InBlock.gif    
/// be any string. In this example we assume that salt is an ASCII string.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="hashAlgorithm">
InBlock.gif    
/// Hash algorithm used to generate password. Allowed values are: "MD5" and
InBlock.gif    
/// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="passwordIterations">
InBlock.gif    
/// Number of iterations used to generate password. One or two iterations
InBlock.gif    
/// should be enough.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="initVector">
InBlock.gif    
/// Initialization vector (or IV). This value is required to encrypt the
InBlock.gif    
/// first block of plaintext data. For RijndaelManaged class IV must be 
InBlock.gif    
/// exactly 16 ASCII characters long.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="keySize">
InBlock.gif    
/// Size of encryption key in bits. Allowed values are: 128, 192, and 256. 
InBlock.gif    
/// Longer keys are more secure than shorter keys.
InBlock.gif    
/// </param>
InBlock.gif    
/// <returns>
InBlock.gif    
/// Encrypted value formatted as a base64-encoded string.
ExpandedSubBlockEnd.gif    
/// </returns>

InBlock.gif    public static string Encrypt(string   plainText,
InBlock.gif                                 
string   passPhrase,
InBlock.gif                                 
string   saltValue,
InBlock.gif                                 
string   hashAlgorithm,
InBlock.gif                                 
int      passwordIterations,
InBlock.gif                                 
string   initVector,
InBlock.gif                                 
int      keySize)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
// Convert strings into byte arrays.
InBlock.gif        
// Let us assume that strings only contain ASCII codes.
InBlock.gif        
// If strings include Unicode characters, use Unicode, UTF7, or UTF8 
InBlock.gif        
// encoding.
InBlock.gif
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
InBlock.gif        
byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);
InBlock.gif        
InBlock.gif        
// Convert our plaintext into a byte array.
InBlock.gif        
// Let us assume that plaintext contains UTF8-encoded characters.
InBlock.gif
        byte[] plainTextBytes  = Encoding.UTF8.GetBytes(plainText);
InBlock.gif        
InBlock.gif        
// First, we must create a password, from which the key will be derived.
InBlock.gif        
// This password will be generated from the specified passphrase and 
InBlock.gif        
// salt value. The password will be created using the specified hash 
InBlock.gif        
// algorithm. Password creation can be done in several iterations.
InBlock.gif
        PasswordDeriveBytes password = new PasswordDeriveBytes(
InBlock.gif                                                        passPhrase, 
InBlock.gif                                                        saltValueBytes, 
InBlock.gif                                                        hashAlgorithm, 
InBlock.gif                                                        passwordIterations);
InBlock.gif        
InBlock.gif        
// Use the password to generate pseudo-random bytes for the encryption
InBlock.gif        
// key. Specify the size of the key in bytes (instead of bits).
InBlock.gif
        byte[] keyBytes = password.GetBytes(keySize / 8);
InBlock.gif        
InBlock.gif        
// Create uninitialized Rijndael encryption object.
InBlock.gif
        RijndaelManaged symmetricKey = new RijndaelManaged();
InBlock.gif        
InBlock.gif        
// It is reasonable to set encryption mode to Cipher Block Chaining
InBlock.gif        
// (CBC). Use default options for other symmetric key parameters.
InBlock.gif
        symmetricKey.Mode = CipherMode.CBC;        
InBlock.gif        
InBlock.gif        
// Generate encryptor from the existing key bytes and initialization 
InBlock.gif        
// vector. Key size will be defined based on the number of the key 
InBlock.gif        
// bytes.
InBlock.gif
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
InBlock.gif                                                         keyBytes, 
InBlock.gif                                                         initVectorBytes);
InBlock.gif        
InBlock.gif        
// Define memory stream which will be used to hold encrypted data.
InBlock.gif
        MemoryStream memoryStream = new MemoryStream();        
InBlock.gif                
InBlock.gif        
// Define cryptographic stream (always use Write mode for encryption).
InBlock.gif
        CryptoStream cryptoStream = new CryptoStream(memoryStream, 
InBlock.gif                                                     encryptor,
InBlock.gif                                                     CryptoStreamMode.Write);
InBlock.gif        
// Start encrypting.
InBlock.gif
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
InBlock.gif                
InBlock.gif        
// Finish encrypting.
InBlock.gif
        cryptoStream.FlushFinalBlock();
InBlock.gif
InBlock.gif        
// Convert our encrypted data from a memory stream into a byte array.
InBlock.gif
        byte[] cipherTextBytes = memoryStream.ToArray();
InBlock.gif                
InBlock.gif        
// Close both streams.
InBlock.gif
        memoryStream.Close();
InBlock.gif        cryptoStream.Close();
InBlock.gif        
InBlock.gif        
// Convert encrypted data into a base64-encoded string.
InBlock.gif
        string cipherText = Convert.ToBase64String(cipherTextBytes);
InBlock.gif        
InBlock.gif        
// Return encrypted string.
InBlock.gif
        return cipherText;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
InBlock.gif    
/// </summary>
InBlock.gif    
/// <param name="cipherText">
InBlock.gif    
/// Base64-formatted ciphertext value.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="passPhrase">
InBlock.gif    
/// Passphrase from which a pseudo-random password will be derived. The
InBlock.gif    
/// derived password will be used to generate the encryption key.
InBlock.gif    
/// Passphrase can be any string. In this example we assume that this
InBlock.gif    
/// passphrase is an ASCII string.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="saltValue">
InBlock.gif    
/// Salt value used along with passphrase to generate password. Salt can
InBlock.gif    
/// be any string. In this example we assume that salt is an ASCII string.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="hashAlgorithm">
InBlock.gif    
/// Hash algorithm used to generate password. Allowed values are: "MD5" and
InBlock.gif    
/// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="passwordIterations">
InBlock.gif    
/// Number of iterations used to generate password. One or two iterations
InBlock.gif    
/// should be enough.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="initVector">
InBlock.gif    
/// Initialization vector (or IV). This value is required to encrypt the
InBlock.gif    
/// first block of plaintext data. For RijndaelManaged class IV must be
InBlock.gif    
/// exactly 16 ASCII characters long.
InBlock.gif    
/// </param>
InBlock.gif    
/// <param name="keySize">
InBlock.gif    
/// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
InBlock.gif    
/// Longer keys are more secure than shorter keys.
InBlock.gif    
/// </param>
InBlock.gif    
/// <returns>
InBlock.gif    
/// Decrypted string value.
InBlock.gif    
/// </returns>
InBlock.gif    
/// <remarks>
InBlock.gif    
/// Most of the logic in this function is similar to the Encrypt
InBlock.gif    
/// logic. In order for decryption to work, all parameters of this function
InBlock.gif    
/// - except cipherText value - must match the corresponding parameters of
InBlock.gif    
/// the Encrypt function which was called to generate the
InBlock.gif    
/// ciphertext.
ExpandedSubBlockEnd.gif    
/// </remarks>

InBlock.gif    public static string Decrypt(string   cipherText,
InBlock.gif                                 
string   passPhrase,
InBlock.gif                                 
string   saltValue,
InBlock.gif                                 
string   hashAlgorithm,
InBlock.gif                                 
int      passwordIterations,
InBlock.gif                                 
string   initVector,
InBlock.gif                                 
int      keySize)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
// Convert strings defining encryption key characteristics into byte
InBlock.gif        
// arrays. Let us assume that strings only contain ASCII codes.
InBlock.gif        
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
InBlock.gif        
// encoding.
InBlock.gif
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
InBlock.gif        
byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);
InBlock.gif        
InBlock.gif        
// Convert our ciphertext into a byte array.
InBlock.gif
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
InBlock.gif        
InBlock.gif        
// First, we must create a password, from which the key will be 
InBlock.gif        
// derived. This password will be generated from the specified 
InBlock.gif        
// passphrase and salt value. The password will be created using
InBlock.gif        
// the specified hash algorithm. Password creation can be done in
InBlock.gif        
// several iterations.
InBlock.gif
        PasswordDeriveBytes password = new PasswordDeriveBytes(
InBlock.gif                                                        passPhrase, 
InBlock.gif                                                        saltValueBytes, 
InBlock.gif                                                        hashAlgorithm, 
InBlock.gif                                                        passwordIterations);
InBlock.gif        
InBlock.gif        
// Use the password to generate pseudo-random bytes for the encryption
InBlock.gif        
// key. Specify the size of the key in bytes (instead of bits).
InBlock.gif
        byte[] keyBytes = password.GetBytes(keySize / 8);
InBlock.gif        
InBlock.gif        
// Create uninitialized Rijndael encryption object.
InBlock.gif
        RijndaelManaged    symmetricKey = new RijndaelManaged();
InBlock.gif        
InBlock.gif        
// It is reasonable to set encryption mode to Cipher Block Chaining
InBlock.gif        
// (CBC). Use default options for other symmetric key parameters.
InBlock.gif
        symmetricKey.Mode = CipherMode.CBC;
InBlock.gif        
InBlock.gif        
// Generate decryptor from the existing key bytes and initialization 
InBlock.gif        
// vector. Key size will be defined based on the number of the key 
InBlock.gif        
// bytes.
InBlock.gif
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
InBlock.gif                                                         keyBytes, 
InBlock.gif                                                         initVectorBytes);
InBlock.gif        
InBlock.gif        
// Define memory stream which will be used to hold encrypted data.
InBlock.gif
        MemoryStream  memoryStream = new MemoryStream(cipherTextBytes);
InBlock.gif                
InBlock.gif        
// Define cryptographic stream (always use Read mode for encryption).
InBlock.gif
        CryptoStream  cryptoStream = new CryptoStream(memoryStream, 
InBlock.gif                                                      decryptor,
InBlock.gif                                                      CryptoStreamMode.Read);
InBlock.gif
InBlock.gif        
// Since at this point we don't know what the size of decrypted data
InBlock.gif        
// will be, allocate the buffer long enough to hold ciphertext;
InBlock.gif        
// plaintext is never longer than ciphertext.
InBlock.gif
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];
InBlock.gif        
InBlock.gif        
// Start decrypting.
InBlock.gif
        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 
InBlock.gif                                                   
0
InBlock.gif                                                   plainTextBytes.Length);
InBlock.gif                
InBlock.gif        
// Close both streams.
InBlock.gif
        memoryStream.Close();
InBlock.gif        cryptoStream.Close();
InBlock.gif        
InBlock.gif        
// Convert decrypted data into a string. 
InBlock.gif        
// Let us assume that the original plaintext string was UTF8-encoded.
InBlock.gif
        string plainText = Encoding.UTF8.GetString(plainTextBytes, 
InBlock.gif                                                   
0
InBlock.gif                                                   decryptedByteCount);
InBlock.gif        
InBlock.gif        
// Return decrypted string.   
InBlock.gif
        return plainText;
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**/ /// <summary>
InBlock.gif
/// Illustrates the use of RijndaelSimple class to encrypt and decrypt data.
ExpandedBlockEnd.gif
/// </summary>

None.gif public   class  RijndaelSimpleTest
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// The main entry point for the application.
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    [STAThread]
InBlock.gif    
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
string   plainText          = "Hello, World!";    // original plaintext
InBlock.gif
        
InBlock.gif        
string   passPhrase         = "Pas5pr@se";        // can be any string
InBlock.gif
        string   saltValue          = "s@1tValue";        // can be any string
InBlock.gif
        string   hashAlgorithm      = "SHA1";             // can be "MD5"
InBlock.gif
        int      passwordIterations = 2;                  // can be any number
InBlock.gif
        string   initVector         = "@1B2c3D4e5F6g7H8"// must be 16 bytes
InBlock.gif
        int      keySize            = 256;                // can be 192 or 128
InBlock.gif
        
InBlock.gif        Console.WriteLine(String.Format(
"Plaintext : {0}", plainText));
InBlock.gif
InBlock.gif        
string  cipherText = RijndaelSimple.Encrypt(plainText,
InBlock.gif                                                    passPhrase,
InBlock.gif                                                    saltValue,
InBlock.gif                                                    hashAlgorithm,
InBlock.gif                                                    passwordIterations,
InBlock.gif                                                    initVector,
InBlock.gif                                                    keySize);
InBlock.gif
InBlock.gif        Console.WriteLine(String.Format(
"Encrypted : {0}", cipherText));
InBlock.gif        
InBlock.gif        plainText          
= RijndaelSimple.Decrypt(cipherText,
InBlock.gif                                                    passPhrase,
InBlock.gif                                                    saltValue,
InBlock.gif                                                    hashAlgorithm,
InBlock.gif                                                    passwordIterations,
InBlock.gif                                                    initVector,
InBlock.gif                                                    keySize);
InBlock.gif
InBlock.gif        Console.WriteLine(String.Format(
"Decrypted : {0}", plainText));
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
//
None.gif
//  END OF FILE
ExpandedBlockStart.gifContractedBlock.gif
/**/ ///
None.gif ^  Back to top  
None.gif
None.gif
None.gif
None.gif
--------------------------------------------------------------------------------
None.gif
None.gif

None.gif VB.NET code
None.gif
None.gif[printer
- friendly version] [code output] 
None.gif
' ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
None.gif'
 SAMPLE: Symmetric key encryption and decryption using Rijndael algorithm.
None.gif'
 
None.gif'
 To run this sample, create a new Visual Basic.NET project using the Console 
None.gif'
 Application template and replace the contents of the Module1.vb file with 
None.gif'
 the code below.
None.gif'
 
None.gif'
 THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
None.gif'
 EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
None.gif'
 WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
None.gif'
 
None.gif'
 Copyright (C) 2003.  Obviex(TM).  All rights reserved.
None.gif'
None.gif
Imports  System
None.gif
Imports  System.IO
None.gif
Imports  System.Text
None.gif
Imports  System.Security.Cryptography
None.gif
ExpandedBlockStart.gifContractedBlock.gif
Module Module1 Module Module1
InBlock.gif
InBlock.gif
' <summary>
InBlock.gif'
 This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and 
InBlock.gif'
 decrypt data. As long as encryption and decryption routines use the same 
InBlock.gif'
 parameters to generate the keys, the keys are guaranteed to be the same.
InBlock.gif'
 The class uses static functions with duplicate code to make it easier to 
InBlock.gif'
 demonstrate encryption and decryption logic. In a real-life application, 
InBlock.gif'
 this may not be the most efficient way of handling encryption, so - as 
InBlock.gif'
 soon as you feel comfortable with it - you may want to redesign this class.
InBlock.gif'
 </summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif
Public Class RijndaelSimpleClass RijndaelSimple
InBlock.gif
InBlock.gif    
' <summary>
InBlock.gif
    ' Encrypts specified plaintext using Rijndael symmetric key algorithm
InBlock.gif
    ' and returns a base64-encoded result.
InBlock.gif
    ' </summary>
InBlock.gif
    ' <param name="plainText">
InBlock.gif
    ' Plaintext value to be encrypted.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="passPhrase">
InBlock.gif
    ' Passphrase from which a pseudo-random password will be derived. The 
InBlock.gif
    ' derived password will be used to generate the encryption key. 
InBlock.gif
    ' Passphrase can be any string. In this example we assume that this 
InBlock.gif
    ' passphrase is an ASCII string.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="saltValue">
InBlock.gif
    ' Salt value used along with passphrase to generate password. Salt can 
InBlock.gif
    ' be any string. In this example we assume that salt is an ASCII string.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="hashAlgorithm">
InBlock.gif
    ' Hash algorithm used to generate password. Allowed values are: "MD5" and
InBlock.gif
    ' "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="passwordIterations">
InBlock.gif
    ' Number of iterations used to generate password. One or two iterations
InBlock.gif
    ' should be enough.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="initVector">
InBlock.gif
    ' Initialization vector (or IV). This value is required to encrypt the 
InBlock.gif
    ' first block of plaintext data. For RijndaelManaged class IV must be 
InBlock.gif
    ' exactly 16 ASCII characters long.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="keySize">
InBlock.gif
    ' Size of encryption key in bits. Allowed values are: 128, 192, and 256. 
InBlock.gif
    ' Longer keys are more secure than shorter keys.
InBlock.gif
    ' </param>
InBlock.gif
    ' <returns>
InBlock.gif
    ' Encrypted value formatted as a base64-encoded string.
InBlock.gif
    ' </returns>
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Public Shared Function Encrypt()Function Encrypt(ByVal plainText           As String,  _
InBlock.gif                                   
ByVal passPhrase          As String,  _
InBlock.gif                                   
ByVal saltValue           As String,  _
InBlock.gif                                   
ByVal hashAlgorithm       As String,  _
InBlock.gif                                   
ByVal passwordIterations  As Integer, _
InBlock.gif                                   
ByVal initVector          As String,  _
InBlock.gif                                   
ByVal keySize             As Integer) _
InBlock.gif                           
As String
InBlock.gif
InBlock.gif        
' Convert strings into byte arrays.
InBlock.gif
        ' Let us assume that strings only contain ASCII codes.
InBlock.gif
        ' If strings include Unicode characters, use Unicode, UTF7, or UTF8 
InBlock.gif
        ' encoding.
InBlock.gif
        Dim initVectorBytes As Byte() 
InBlock.gif        initVectorBytes 
= Encoding.ASCII.GetBytes(initVector)
InBlock.gif
InBlock.gif        
Dim saltValueBytes As Byte()
InBlock.gif        saltValueBytes 
= Encoding.ASCII.GetBytes(saltValue)
InBlock.gif        
InBlock.gif        
' Convert our plaintext into a byte array.
InBlock.gif
        ' Let us assume that plaintext contains UTF8-encoded characters.
InBlock.gif
        Dim plainTextBytes As Byte()
InBlock.gif        plainTextBytes 
= Encoding.UTF8.GetBytes(plainText)
InBlock.gif        
InBlock.gif        
' First, we must create a password, from which the key will be derived.
InBlock.gif
        ' This password will be generated from the specified passphrase and 
InBlock.gif
        ' salt value. The password will be created using the specified hash 
InBlock.gif
        ' algorithm. Password creation can be done in several iterations.
InBlock.gif
        Dim password As PasswordDeriveBytes
InBlock.gif        password 
= new PasswordDeriveBytes(passPhrase,     _
InBlock.gif                                           saltValueBytes, _ 
InBlock.gif                                           hashAlgorithm,  _
InBlock.gif                                           passwordIterations)
InBlock.gif        
InBlock.gif        
' Use the password to generate pseudo-random bytes for the encryption
InBlock.gif
        ' key. Specify the size of the key in bytes (instead of bits).
InBlock.gif
        Dim keyBytes As Byte()
InBlock.gif        keyBytes 
= password.GetBytes(keySize / 8)
InBlock.gif        
InBlock.gif        
' Create uninitialized Rijndael encryption object.
InBlock.gif
        Dim symmetricKey As RijndaelManaged 
InBlock.gif        symmetricKey 
= new RijndaelManaged()
InBlock.gif        
InBlock.gif        
' It is reasonable to set encryption mode to Cipher Block Chaining
InBlock.gif
        ' (CBC). Use default options for other symmetric key parameters.
InBlock.gif
        symmetricKey.Mode = CipherMode.CBC        
InBlock.gif        
InBlock.gif        
' Generate encryptor from the existing key bytes and initialization 
InBlock.gif
        ' vector. Key size will be defined based on the number of the key 
InBlock.gif
        ' bytes.
InBlock.gif
        Dim encryptor As ICryptoTransform 
InBlock.gif        encryptor 
= symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)
InBlock.gif        
InBlock.gif        
' Define memory stream which will be used to hold encrypted data.
InBlock.gif
        Dim memoryStream As MemoryStream 
InBlock.gif        memoryStream 
= new MemoryStream()        
InBlock.gif                
InBlock.gif        
' Define cryptographic stream (always use Write mode for encryption).
InBlock.gif
        Dim cryptoStream As CryptoStream
InBlock.gif        cryptoStream 
= new CryptoStream(memoryStream, _ 
InBlock.gif                                        encryptor,    _
InBlock.gif                                        CryptoStreamMode.
Write)
InBlock.gif        
' Start encrypting.
InBlock.gif
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
InBlock.gif                
InBlock.gif        
' Finish encrypting.
InBlock.gif
        cryptoStream.FlushFinalBlock()
InBlock.gif
InBlock.gif        
' Convert our encrypted data from a memory stream into a byte array.
InBlock.gif
        Dim cipherTextBytes As Byte() 
InBlock.gif        cipherTextBytes 
= memoryStream.ToArray()
InBlock.gif                
InBlock.gif        
' Close both streams.
InBlock.gif
        memoryStream.Close()
InBlock.gif        cryptoStream.Close()
InBlock.gif        
InBlock.gif        
' Convert encrypted data into a base64-encoded string.
InBlock.gif
        Dim cipherText As String 
InBlock.gif        cipherText 
= Convert.ToBase64String(cipherTextBytes)
InBlock.gif        
InBlock.gif        
' Return encrypted string.
InBlock.gif
        Encrypt = cipherText
ExpandedSubBlockEnd.gif    
End Function

InBlock.gif    
InBlock.gif    
' <summary>
InBlock.gif
    ' Decrypts specified ciphertext using Rijndael symmetric key algorithm.
InBlock.gif
    ' </summary>
InBlock.gif
    ' <param name="cipherText">
InBlock.gif
    ' Base64-formatted ciphertext value.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="passPhrase">
InBlock.gif
    ' Passphrase from which a pseudo-random password will be derived. The 
InBlock.gif
    ' derived password will be used to generate the encryption key. 
InBlock.gif
    ' Passphrase can be any string. In this example we assume that this 
InBlock.gif
    ' passphrase is an ASCII string.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="saltValue">
InBlock.gif
    ' Salt value used along with passphrase to generate password. Salt can 
InBlock.gif
    ' be any string. In this example we assume that salt is an ASCII string.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="hashAlgorithm">
InBlock.gif
    ' Hash algorithm used to generate password. Allowed values are: "MD5" and
InBlock.gif
    ' "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="passwordIterations">
InBlock.gif
    ' Number of iterations used to generate password. One or two iterations
InBlock.gif
    ' should be enough.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="initVector">
InBlock.gif
    ' Initialization vector (or IV). This value is required to encrypt the 
InBlock.gif
    ' first block of plaintext data. For RijndaelManaged class IV must be 
InBlock.gif
    ' exactly 16 ASCII characters long.
InBlock.gif
    ' </param>
InBlock.gif
    ' <param name="keySize">
InBlock.gif
    ' Size of encryption key in bits. Allowed values are: 128, 192, and 256. 
InBlock.gif
    ' Longer keys are more secure than shorter keys.
InBlock.gif
    ' </param>
InBlock.gif
    ' <returns>
InBlock.gif
    ' Decrypted string value.
InBlock.gif
    ' </returns>
InBlock.gif
    ' <remarks>
InBlock.gif
    ' Most of the logic in this function is similar to the Encrypt 
InBlock.gif
    ' logic. In order for decryption to work, all parameters of this function
InBlock.gif
    ' - except cipherText value - must match the corresponding parameters of 
InBlock.gif
    ' the Encrypt function which was called to generate the 
InBlock.gif
    ' ciphertext.
InBlock.gif
    ' </remarks>
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Public Shared Function Decrypt()Function Decrypt(ByVal cipherText          As String,  _
InBlock.gif                                   
ByVal passPhrase          As String,  _
InBlock.gif                                   
ByVal saltValue           As String,  _
InBlock.gif                                   
ByVal hashAlgorithm       As String,  _
InBlock.gif                                   
ByVal passwordIterations  As Integer, _
InBlock.gif                                   
ByVal initVector          As String,  _
InBlock.gif                                   
ByVal keySize             As Integer) _
InBlock.gif                           
As String
InBlock.gif
InBlock.gif        
' Convert strings defining encryption key characteristics into byte
InBlock.gif
        ' arrays. Let us assume that strings only contain ASCII codes.
InBlock.gif
        ' If strings include Unicode characters, use Unicode, UTF7, or UTF8
InBlock.gif
        ' encoding.
InBlock.gif
        Dim initVectorBytes As Byte() 
InBlock.gif        initVectorBytes 
= Encoding.ASCII.GetBytes(initVector)
InBlock.gif
InBlock.gif        
Dim saltValueBytes As Byte()
InBlock.gif        saltValueBytes 
= Encoding.ASCII.GetBytes(saltValue)
InBlock.gif       
InBlock.gif        
' Convert our ciphertext into a byte array.
InBlock.gif
        Dim cipherTextBytes As Byte() 
InBlock.gif        cipherTextBytes 
= Convert.FromBase64String(cipherText)
InBlock.gif        
InBlock.gif        
' First, we must create a password, from which the key will be 
InBlock.gif
        ' derived. This password will be generated from the specified 
InBlock.gif
        ' passphrase and salt value. The password will be created using
InBlock.gif
        ' the specified hash algorithm. Password creation can be done in
InBlock.gif
        ' several iterations.
InBlock.gif
        Dim password As PasswordDeriveBytes 
InBlock.gif        password 
= new PasswordDeriveBytes(passPhrase,     _
InBlock.gif                                           saltValueBytes, _
InBlock.gif                                           hashAlgorithm,  _
InBlock.gif                                           passwordIterations)
InBlock.gif        
InBlock.gif        
' Use the password to generate pseudo-random bytes for the encryption
InBlock.gif
        ' key. Specify the size of the key in bytes (instead of bits).
InBlock.gif
        Dim keyBytes As Byte() 
InBlock.gif        keyBytes 
= password.GetBytes(keySize / 8)
InBlock.gif        
InBlock.gif        
' Create uninitialized Rijndael encryption object.
InBlock.gif
        Dim symmetricKey As RijndaelManaged 
InBlock.gif        symmetricKey 
= new RijndaelManaged()
InBlock.gif        
InBlock.gif        
' It is reasonable to set encryption mode to Cipher Block Chaining
InBlock.gif
        ' (CBC). Use default options for other symmetric key parameters.
InBlock.gif
        symmetricKey.Mode = CipherMode.CBC
InBlock.gif        
InBlock.gif        
' Generate decryptor from the existing key bytes and initialization 
InBlock.gif
        ' vector. Key size will be defined based on the number of the key 
InBlock.gif
        ' bytes.
InBlock.gif
        Dim decryptor As ICryptoTransform 
InBlock.gif        decryptor 
= symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)
InBlock.gif        
InBlock.gif        
' Define memory stream which will be used to hold encrypted data.
InBlock.gif
        Dim memoryStream As MemoryStream  
InBlock.gif        memoryStream 
= new MemoryStream(cipherTextBytes)
InBlock.gif                
InBlock.gif        
' Define memory stream which will be used to hold encrypted data.
InBlock.gif
        Dim cryptoStream As CryptoStream  
InBlock.gif        cryptoStream 
= new CryptoStream(memoryStream, _
InBlock.gif                                        decryptor,    _
InBlock.gif                                        CryptoStreamMode.Read)
InBlock.gif
InBlock.gif        
' Since at this point we don't know what the size of decrypted data
InBlock.gif
        ' will be, allocate the buffer long enough to hold ciphertext;
InBlock.gif
        ' plaintext is never longer than ciphertext.
InBlock.gif
        Dim plainTextBytes As Byte() 
InBlock.gif        
ReDim plainTextBytes(cipherTextBytes.Length)
InBlock.gif        
InBlock.gif        
' Start decrypting.
InBlock.gif
        Dim decryptedByteCount As Integer 
InBlock.gif        decryptedByteCount 
= cryptoStream.Read(plainTextBytes, _
InBlock.gif                                               
0,              _
InBlock.gif                                               plainTextBytes.Length)
InBlock.gif                
InBlock.gif        
' Close both streams.
InBlock.gif
        memoryStream.Close()
InBlock.gif        cryptoStream.Close()
InBlock.gif        
InBlock.gif        
' Convert decrypted data into a string. 
InBlock.gif
        ' Let us assume that the original plaintext string was UTF8-encoded.
InBlock.gif
        Dim plainText As String 
InBlock.gif        plainText 
= Encoding.UTF8.GetString(plainTextBytes, _
InBlock.gif                                            
0, _
InBlock.gif                                            decryptedByteCount)
InBlock.gif        
InBlock.gif        
' Return decrypted string.
InBlock.gif
        Decrypt = plainText
ExpandedSubBlockEnd.gif    
End Function

ExpandedSubBlockEnd.gif
End Class

InBlock.gif
InBlock.gif
' <summary>
InBlock.gif'
 The main entry point for the application.
InBlock.gif'
 </summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif
Sub Main()Sub Main()
InBlock.gif    
Dim plainText          As String
InBlock.gif    
Dim cipherText         As String
InBlock.gif    
InBlock.gif    
Dim passPhrase         As String
InBlock.gif    
Dim saltValue          As String
InBlock.gif    
Dim hashAlgorithm      As String
InBlock.gif    
Dim passwordIterations As Integer
InBlock.gif    
Dim initVector         As String
InBlock.gif    
Dim keySize            As Integer
InBlock.gif
InBlock.gif    plainText          
= "Hello, World!"    ' original plaintext
InBlock.gif
    
InBlock.gif    passPhrase         
= "Pas5pr@se"        ' can be any string
InBlock.gif
    saltValue          = "s@1tValue"        ' can be any string
InBlock.gif
    hashAlgorithm      = "SHA1"             ' can be "MD5"
InBlock.gif
    passwordIterations = 2                  ' can be any number
InBlock.gif
    initVector         = "@1B2c3D4e5F6g7H8" ' must be 16 bytes
InBlock.gif
    keySize            = 256                ' can be 192 or 128
InBlock.gif
    
InBlock.gif    Console.
WriteLine(String.Format("Plaintext : {0}", plainText))
InBlock.gif
InBlock.gif    cipherText 
= RijndaelSimple.Encrypt(plainText,          _
InBlock.gif                                        passPhrase,         _
InBlock.gif                                        saltValue,          _
InBlock.gif                                        hashAlgorithm,      _
InBlock.gif                                        passwordIterations, _
InBlock.gif                                        initVector,         _
InBlock.gif                                        keySize)
InBlock.gif
InBlock.gif    Console.
WriteLine(String.Format("Encrypted : {0}", cipherText))
InBlock.gif    
InBlock.gif    plainText  
= RijndaelSimple.Decrypt(cipherText,         _
InBlock.gif                                        passPhrase,         _
InBlock.gif                                        saltValue,          _
InBlock.gif                                        hashAlgorithm,      _
InBlock.gif                                        passwordIterations, _
InBlock.gif                                        initVector,         _
InBlock.gif                                        keySize)
InBlock.gif
InBlock.gif    Console.
WriteLine(String.Format("Decrypted : {0}", plainText))
ExpandedSubBlockEnd.gif
End Sub

InBlock.gif
ExpandedBlockEnd.gif
End Module

None.gif
'  
None.gif'
 END OF FILE
None.gif'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
None.gif



http://www.obviex.com/samples/Encryption.aspx

-----------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值