C#加密与解密

来源:互联网 发布:手机连接电视软件 编辑:程序博客网 时间:2024/04/29 01:16

1、(1)3des算法介绍

 3DES算法是指使用双长度(16字节)密钥K=(KL||KR)将8字节明文数据块进行3次DES加密/解密。如下所示:
      Y = DES(KL)[DES-1(KR)[DES(KL[X])]]
      解密方式为:
      X = DES-1 (KL)[DES      (KR)[ DES-1 (KL[Y])]]
  其中,DES(KL[X])表示用密钥K对数据X进行DES加密,DES-1 (KL[Y])表示用密钥K对数据Y进行解密。
  SessionKey的计算采用3DES算法,计算出单倍长度的密钥。表示法为:SK = Session(DK,DATA)
  3DES加密算法为:
      VOID 3DES(BYTE DoubleKeyStr[16], BYTE Data[8], BYTE Out[8])
{
      BYTE Buf1[8], Buf2[8];
      DES      (&DoubleKeyStr[0], Data, Buf1);
      UDES(&DoubleKeyStr[8], Buf1, Buf2);
      DES      (&DoubleKeyStr[0], Buf2, Out);
}
(2)3des+base64加密与解密示例

设Ek()和Dk()代表DES算法的加密和解密过程,K代表DES算法使用的密钥,P代表明文,C代表密表,这样,

3DES加密过程为:C=Ek3(Dk2(Ek1(P)))
3DES解密过程为:P=Dk1((EK2(Dk3(C)))

具体的加/解密过程如下所示。
using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;
class Class1
{
static void Main()
{
Console.WriteLine("Encrypt String...");
txtKey = "tkGGRmBErvc=";
btnKeyGen();
Console.WriteLine("Encrypt Key :",txtKey);
txtIV = "Kl7ZgtM1dvQ=";
btnIVGen();
Console.WriteLine("Encrypt IV :",txtIV);
Console.WriteLine();
string txtEncrypted = EncryptString("1111");
Console.WriteLine("Encrypt String : ",txtEncrypted);
string txtOriginal = DecryptString(txtEncrypted);
Console.WriteLine("Decrypt String : ",txtOriginal);
}
private static SymmetricAlgorithm mCSP;
private static string txtKey;
private static string txtIV;
private static void btnKeyGen()
{
mCSP = SetEnc();
byte[] byt2 = Convert.FromBase64String(txtKey);
mCSP.Key = byt2;
}
private static void btnIVGen()
{
byte[] byt2 = Convert.FromBase64String(txtIV);
mCSP.IV = byt2;
}
private static string EncryptString(string Value)
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
byt = Encoding.UTF8.GetBytes(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
private static string DecryptString(string Value)
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
byt = Convert.FromBase64String(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
private static SymmetricAlgorithm SetEnc()
{
return new DESCryptoServiceProvider();
}
}
K1、K2、K3决定了算法的安全性,若三个密钥互不相同,本质上就相当于用一个长为168位的密钥进行加密。多年来,它在对付强力攻击时是比较安全的。若数据对安全性要求不那么高,K1可以等于K3。在这种情况下,密钥的有效长度为112位。

(3)java与C#加密与解密对比

java中的Cipher.DECRYPR_MODE

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class CryptUtil3DES {
    
private static final String CRYPT_KEY = "v3VC7LfCq6IL5KgIglqZrQ1b";
    
private static final String CRYPT_ALGORITHM = "DESede";
    
    
public static String decrypt(String value) {
        
try {
            SecretKeySpec keySpec 
= new SecretKeySpec(CRYPT_KEY.getBytes(), CRYPT_ALGORITHM);
            Cipher cipher 
= Cipher.getInstance(CRYPT_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            
            
byte[] decodedByte = Base64.decodeBase64(value.getBytes());
            
byte[] decryptedByte = cipher.doFinal(decodedByte);            
            
return new String(decryptedByte);
        }
 catch(Exception e) {
            
return null;
        }

    }

    
    
public static String encrypt(String value) {
        
try {
            SecretKeySpec keySpec 
= new SecretKeySpec(CRYPT_KEY.getBytes(), CRYPT_ALGORITHM);
            Cipher cipher 
= Cipher.getInstance(CRYPT_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            
            
byte[] encryptedByte = cipher.doFinal(value.getBytes());
            
byte[] encodedByte = Base64.encodeBase64(encryptedByte);
            
return new String(encodedByte);
        }
 catch(Exception e) {
            
return null;
        }

    }

}


2。C#

public class CryptionData
{
    
// The length of Encryptionstring should be 24 byte and not be a weak key
    private string EncryptionString;

    
// The length of initialization vector should be 8 byte
    private static Byte[] EncryptionIV = Encoding.Default.GetBytes("        ");

    
/// <summary>
    /// Constructor
    /// </summary>
    public CryptionData()
    
{
        
    }


    
/// <summary>
    /// Constructor
    /// </summary>
    /// <param name="EncryptionString">SecureKey</param>
    public CryptionData(string EncryptionString)
    
{
        
this.EncryptionString = EncryptionString;
    }


    
/// <summary>
    /// Encryption method for byte array
    /// </summary>
    /// <param name="SourceData">source data</param>
    /// <returns>byte array</returns>
    public byte[] EncryptionByteData(byte[] SourceData)
    
{
        
byte[] returnData = null;
        
try
        
{
            
// Create TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider desProvider = new TripleDESCryptoServiceProvider();

            
// Set SecureKey and IV of desProvider
            byte[] byteKey = Encoding.Default.GetBytes(EncryptionString);
            desProvider.Key 
= byteKey;
            desProvider.IV 
= EncryptionIV;
            desProvider.Mode 
= CipherMode.ECB;
 
            
// A MemoryStream object
            MemoryStream ms = new MemoryStream();

            
// Create Encryptor
            ICryptoTransform encrypto = desProvider.CreateEncryptor();

            
// Create CryptoStream object
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);

            
// Encrypt SourceData
            cs.Write(SourceData, 0, SourceData.Length);
            cs.FlushFinalBlock();

            
// Get Encryption result
            returnData = ms.ToArray();
        }

        
catch (Exception ex)
        
{
            
throw ex;
        }


        
return returnData;

    }


    
/// <summary>
    /// Decryption method for byte array
    /// </summary>
    /// <param name="SourceData">source data</param>
    /// <returns>byte array</returns>
    public byte[] DecryptionByteData(byte[] SourceData)
    
{
        
byte[] returnData = null;
        
try
        
{
            
// Create TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider desProvider = new TripleDESCryptoServiceProvider();

            
// Set SecureKey and IV of desProvider
            byte[] byteKey = Encoding.Default.GetBytes(EncryptionString);
            desProvider.Key 
= byteKey;
            desProvider.IV 
= EncryptionIV;
            desProvider.Mode 
= CipherMode.ECB;
            
// A MemoryStream object
            MemoryStream ms = new MemoryStream();

            
// Create Decryptor
            ICryptoTransform encrypto = desProvider.CreateDecryptor();

            
// Create CryptoStream object
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);

            
// Decrypt SourceData
            cs.Write(SourceData, 0, SourceData.Length);
            cs.FlushFinalBlock();

            
// Get Decryption result
            returnData = ms.ToArray();
        }

        
catch (Exception ex)
        
{
            
throw ex;
        }

        
return returnData;

    }


    
/// <summary>
    /// Encryption method for string
    /// </summary>
    /// <param name="SourceData">source data</param>
    /// <returns>string</returns>
    public string EncryptionStringData(string SourceData)
    
{
        
try
        
{
            
// Convert source data from string to byte array
            byte[] SourData = Encoding.Default.GetBytes(SourceData);

            
// Encrypt byte array
            byte[] retData = EncryptionByteData(SourData);

            
// Convert encryption result from byte array to Base64String
            return Convert.ToBase64String(retData, 0, retData.Length);
        }

        
catch (Exception ex)
        
{
            
throw ex;
        }

    }


    
/// <summary>
    /// Decryption method for string
    /// </summary>
    /// <param name="SourceData">source data</param>
    /// <returns>string</returns>
    public string DecryptionStringdata(string SourceData)
    
{
        
try
        
{
            
// Convert source data from Base64String to byte array
            byte[] SourData = Convert.FromBase64String(SourceData);

            
// Decrypt byte array
            byte[] retData = DecryptionByteData(SourData);

            
// Convert Decryption result from byte array to string
            return Encoding.Default.GetString(retData, 0, retData.Length);
        }

        
catch (Exception ex)
        
{
            
throw ex;
        }

    }

}

 

 

 

原创粉丝点击