数据加密

简介:

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.gifC# code
None.gif
None.gif[printer-friendly version] [code output] 
ExpandedBlockStart.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.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.gif {
ExpandedSubBlockStart.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.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.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.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.gif /// <summary>
InBlock.gif
/// Illustrates the use of RijndaelSimple class to encrypt and decrypt data.
ExpandedBlockEnd.gif
/// </summary>

None.gif public  class RijndaelSimpleTest
ExpandedBlockStart.gif {
ExpandedSubBlockStart.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.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.gif
///////////////////////////////////////////////////////////////////////////////
None.gif^ Back to top  
None.gif
None.gif
None.gif
None.gif--------------------------------------------------------------------------------
None.gif
None.gif

None.gifVB.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.gif 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.gif
Public Class 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.gif
    Public Shared 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.gif
    Public Shared 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.gifEnd Class

InBlock.gif
InBlock.gif' <summary>
InBlock.gif'
 The main entry point for the application.
InBlock.gif'
 </summary>
ExpandedSubBlockStart.gif
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.gifEnd Sub

InBlock.gif
ExpandedBlockEnd.gifEnd Module

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




本文转自斯克迪亚博客园博客,原文链接:http://www.cnblogs.com/sgsoft/archive/2004/08/25/36320.html,如需转载请自行联系原作者
相关文章
|
7月前
|
存储 算法 安全
第4章 数据库安全性——4.5 数据加密
第4章 数据库安全性——4.5 数据加密
|
5天前
|
存储 安全 网络安全
C#编程的安全性与加密技术
【4月更文挑战第21天】C#在.NET框架支持下,以其面向对象和高级特性成为安全软件开发的利器。本文探讨C#在安全加密领域的应用,包括使用System.Security.Cryptography库实现加密算法,利用SSL/TLS保障网络传输安全,进行身份验证,并强调编写安全代码的重要性。实际案例涵盖在线支付、企业应用和文件加密,展示了C#在应对安全挑战的同时,不断拓展其在该领域的潜力和未来前景。
|
1月前
|
存储 算法 安全
密码学系列之九:密钥管理
密码学系列之九:密钥管理
266 45
|
3月前
|
数据安全/隐私保护
突然遇到一个加密需求和解密需求
突然遇到一个加密需求和解密需求
22 0
|
10月前
|
算法 安全 数据安全/隐私保护
数据加密
数据加密
111 0
|
存储 网络安全 数据安全/隐私保护
赶紧!快加密吧!
hello,大家好,我是Jackpop。今天跟大家聊一下隐私保护的话题。 使用电脑久了,日积月累,都会沉淀下来一些隐私信息,内容包含但不限于文档、音频、视频等形式。
|
安全 算法 网络安全
【计算机网络】网络安全 : 数据加密模型 ( 加密模型 | 密钥 | 密码学 | 密码安全 )
【计算机网络】网络安全 : 数据加密模型 ( 加密模型 | 密钥 | 密码学 | 密码安全 )
518 0
【计算机网络】网络安全 : 数据加密模型 ( 加密模型 | 密钥 | 密码学 | 密码安全 )
|
算法 数据安全/隐私保护 Android开发
|
算法 数据安全/隐私保护 网络协议
数据加密(对称加密和非对称加密)
通过网络通信的五层模型(ISO规定的是七层模型,TCP/IP规定的是五层模型)可以实现两个应用程序之间的数据通信    但是现在有个问题是 数据如何加密,总不能两个人之间说的话让第三个人活着别的人听到吧  那最简单的例子就是:A和B之间传递数据,如何保证数据不被第三个人知道,或者说第三个人就算知道数据,但是不知道数据所代表的意思。
992 1
|
算法 关系型数据库 程序员