如何使用Base64进行加密和解密

来源:互联网 发布:2016欧洲杯网络转播权 编辑:程序博客网 时间:2024/04/27 05:21

 

//----------------------------- Base64 class --------------------------------------
//---------------------------------------------------------------------------------
//---File:          clsBase64
//---Description:   The class file to encode string or decode string in base algorithm 
//---Author:        Knight
//---Created Date:  Oct.8, 2005
//---Modified Date: Jul.4, 2006
//---------------------------------------------------------------------------------
//----------------------------{ Base64 class }-------------------------------------

using System;

namespace Base64
{
    
using System.Text;
    
/// <summary>
    
/// Summary description for clsBase64.
    
/// </summary>

    public class clsBase64
    
{
        
protected clsBase64()
        
{
            
//Avoid to be inited
        }


        
Base64_Algorithm_Implement 
        
/// <summary>
        
/// Encrypt data based on specific key
        
/// </summary>
        
/// <param name="Data">the data to be encrypted</param>
        
/// <param name="Key">key data</param>
        
/// <returns>If successfully, return encrypted string; else return NULL</returns>

        public static string EncryptData( string Data, string Key )
        
{
            
if( Data == null || Data == "" ) return null;

            
if( Key == null || Key == "" ) return null;

            
char[] chrEncrypted = GetEncoded( Key.ToCharArray(), 
                Encoding.Unicode.GetBytes( Data ) );
            
if( chrEncrypted != null )
                
return new string( chrEncrypted );
            
else
                
return null;
        }

        
/// <summary>
        
/// Decrypt data based on specific key
        
/// </summary>
        
/// <param name="Data">the data to be decrypted</param>
        
/// <param name="Key">key data</param>
        
/// <returns>If successfully, return decrypted string; else return NULL</returns>

        public static string DecryptData( string Data, string Key )
        
{
            
if( Data == null || Data == "" ) return null;

            
if( Key == null || Key == "" ) return null;

            
byte[] bDecrypted = GetDecoded( Key.ToCharArray(),
                Data.ToCharArray() );
            
if( bDecrypted != null )
                
return Encoding.Unicode.GetString( bDecrypted );
            
else
                
return null;
        }

    }


}

// 调用如下:
  
// Encrypt data 
    string strEncryptedData = Base64.clsBase64.EncryptData(  yourData, yourKey );  
    
if( strEncryptedData != null )
        MessageBox.Show( strEncryptedData );

    
// Decrypt data
    string strDecryptedData = Base64.clsBase64.DecryptData(  yourData, yourKey );
    
if( strDecryptedData != null )
        MessageBox.Show( strDecryptedData );