C#加密与解密

时间:2021-09-07 22:15:53

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;
C#加密与解密
import javax.crypto.spec.SecretKeySpec;
C#加密与解密
C#加密与解密
import org.apache.commons.codec.binary.Base64;
C#加密与解密
C#加密与解密C#加密与解密
public class CryptUtil3DES {
C#加密与解密    
private static final String CRYPT_KEY = "v3VC7LfCq6IL5KgIglqZrQ1b";
C#加密与解密    
private static final String CRYPT_ALGORITHM = "DESede";
C#加密与解密    
C#加密与解密C#加密与解密    
public static String decrypt(String value) {
C#加密与解密C#加密与解密        
try {
C#加密与解密            SecretKeySpec keySpec 
= new SecretKeySpec(CRYPT_KEY.getBytes(), CRYPT_ALGORITHM);
C#加密与解密            Cipher cipher 
= Cipher.getInstance(CRYPT_ALGORITHM);
C#加密与解密            cipher.init(Cipher.DECRYPT_MODE, keySpec);
C#加密与解密            
C#加密与解密            
byte[] decodedByte = Base64.decodeBase64(value.getBytes());
C#加密与解密            
byte[] decryptedByte = cipher.doFinal(decodedByte);            
C#加密与解密            
return new String(decryptedByte);
C#加密与解密C#加密与解密        }
 catch(Exception e) {
C#加密与解密            
return null;
C#加密与解密        }

C#加密与解密    }

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

C#加密与解密    }

C#加密与解密}

C#加密与解密
C#加密与解密
2。C#

C#加密与解密public class CryptionData
C#加密与解密C#加密与解密
{
C#加密与解密    
// The length of Encryptionstring should be 24 byte and not be a weak key
C#加密与解密
    private string EncryptionString;
C#加密与解密
C#加密与解密    
// The length of initialization vector should be 8 byte
C#加密与解密
    private static Byte[] EncryptionIV = Encoding.Default.GetBytes("        ");
C#加密与解密
C#加密与解密    
/// <summary>
C#加密与解密
    /// Constructor
C#加密与解密
    /// </summary>
C#加密与解密
    public CryptionData()
C#加密与解密C#加密与解密    
{
C#加密与解密        
C#加密与解密    }

C#加密与解密
C#加密与解密    
/// <summary>
C#加密与解密
    /// Constructor
C#加密与解密
    /// </summary>
C#加密与解密
    /// <param name="EncryptionString">SecureKey</param>
C#加密与解密
    public CryptionData(string EncryptionString)
C#加密与解密C#加密与解密    
{
C#加密与解密        
this.EncryptionString = EncryptionString;
C#加密与解密    }

C#加密与解密
C#加密与解密    
/// <summary>
C#加密与解密
    /// Encryption method for byte array
C#加密与解密
    /// </summary>
C#加密与解密
    /// <param name="SourceData">source data</param>
C#加密与解密
    /// <returns>byte array</returns>
C#加密与解密
    public byte[] EncryptionByteData(byte[] SourceData)
C#加密与解密C#加密与解密    
{
C#加密与解密        
byte[] returnData = null;
C#加密与解密        
try
C#加密与解密C#加密与解密        
{
C#加密与解密            
// Create TripleDESCryptoServiceProvider object
C#加密与解密
            TripleDESCryptoServiceProvider desProvider = new TripleDESCryptoServiceProvider();
C#加密与解密
C#加密与解密            
// Set SecureKey and IV of desProvider
C#加密与解密
            byte[] byteKey = Encoding.Default.GetBytes(EncryptionString);
C#加密与解密            desProvider.Key 
= byteKey;
C#加密与解密            desProvider.IV 
= EncryptionIV;
C#加密与解密            desProvider.Mode 
= CipherMode.ECB;
C#加密与解密 
C#加密与解密            
// A MemoryStream object
C#加密与解密
            MemoryStream ms = new MemoryStream();
C#加密与解密
C#加密与解密            
// Create Encryptor
C#加密与解密
            ICryptoTransform encrypto = desProvider.CreateEncryptor();
C#加密与解密
C#加密与解密            
// Create CryptoStream object
C#加密与解密
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
C#加密与解密
C#加密与解密            
// Encrypt SourceData
C#加密与解密
            cs.Write(SourceData, 0, SourceData.Length);
C#加密与解密            cs.FlushFinalBlock();
C#加密与解密
C#加密与解密            
// Get Encryption result
C#加密与解密
            returnData = ms.ToArray();
C#加密与解密        }

C#加密与解密        
catch (Exception ex)
C#加密与解密C#加密与解密        
{
C#加密与解密            
throw ex;
C#加密与解密        }

C#加密与解密
C#加密与解密        
return returnData;
C#加密与解密
C#加密与解密    }

C#加密与解密
C#加密与解密    
/// <summary>
C#加密与解密
    /// Decryption method for byte array
C#加密与解密
    /// </summary>
C#加密与解密
    /// <param name="SourceData">source data</param>
C#加密与解密
    /// <returns>byte array</returns>
C#加密与解密
    public byte[] DecryptionByteData(byte[] SourceData)
C#加密与解密C#加密与解密    
{
C#加密与解密        
byte[] returnData = null;
C#加密与解密        
try
C#加密与解密C#加密与解密        
{
C#加密与解密            
// Create TripleDESCryptoServiceProvider object
C#加密与解密
            TripleDESCryptoServiceProvider desProvider = new TripleDESCryptoServiceProvider();
C#加密与解密
C#加密与解密            
// Set SecureKey and IV of desProvider
C#加密与解密
            byte[] byteKey = Encoding.Default.GetBytes(EncryptionString);
C#加密与解密            desProvider.Key 
= byteKey;
C#加密与解密            desProvider.IV 
= EncryptionIV;
C#加密与解密            desProvider.Mode 
= CipherMode.ECB;
C#加密与解密            
// A MemoryStream object
C#加密与解密
            MemoryStream ms = new MemoryStream();
C#加密与解密
C#加密与解密            
// Create Decryptor
C#加密与解密
            ICryptoTransform encrypto = desProvider.CreateDecryptor();
C#加密与解密
C#加密与解密            
// Create CryptoStream object
C#加密与解密
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
C#加密与解密
C#加密与解密            
// Decrypt SourceData
C#加密与解密
            cs.Write(SourceData, 0, SourceData.Length);
C#加密与解密            cs.FlushFinalBlock();
C#加密与解密
C#加密与解密            
// Get Decryption result
C#加密与解密
            returnData = ms.ToArray();
C#加密与解密        }

C#加密与解密        
catch (Exception ex)
C#加密与解密C#加密与解密        
{
C#加密与解密            
throw ex;
C#加密与解密        }

C#加密与解密        
return returnData;
C#加密与解密
C#加密与解密    }

C#加密与解密
C#加密与解密    
/// <summary>
C#加密与解密
    /// Encryption method for string
C#加密与解密
    /// </summary>
C#加密与解密
    /// <param name="SourceData">source data</param>
C#加密与解密
    /// <returns>string</returns>
C#加密与解密
    public string EncryptionStringData(string SourceData)
C#加密与解密C#加密与解密    
{
C#加密与解密        
try
C#加密与解密C#加密与解密        
{
C#加密与解密            
// Convert source data from string to byte array
C#加密与解密
            byte[] SourData = Encoding.Default.GetBytes(SourceData);
C#加密与解密
C#加密与解密            
// Encrypt byte array
C#加密与解密
            byte[] retData = EncryptionByteData(SourData);
C#加密与解密
C#加密与解密            
// Convert encryption result from byte array to Base64String
C#加密与解密
            return Convert.ToBase64String(retData, 0, retData.Length);
C#加密与解密        }

C#加密与解密        
catch (Exception ex)
C#加密与解密C#加密与解密        
{
C#加密与解密            
throw ex;
C#加密与解密        }

C#加密与解密    }

C#加密与解密
C#加密与解密    
/// <summary>
C#加密与解密
    /// Decryption method for string
C#加密与解密
    /// </summary>
C#加密与解密
    /// <param name="SourceData">source data</param>
C#加密与解密
    /// <returns>string</returns>
C#加密与解密
    public string DecryptionStringdata(string SourceData)
C#加密与解密C#加密与解密    
{
C#加密与解密        
try
C#加密与解密C#加密与解密        
{
C#加密与解密            
// Convert source data from Base64String to byte array
C#加密与解密
            byte[] SourData = Convert.FromBase64String(SourceData);
C#加密与解密
C#加密与解密            
// Decrypt byte array
C#加密与解密
            byte[] retData = DecryptionByteData(SourData);
C#加密与解密
C#加密与解密            
// Convert Decryption result from byte array to string
C#加密与解密
            return Encoding.Default.GetString(retData, 0, retData.Length);
C#加密与解密        }

C#加密与解密        
catch (Exception ex)
C#加密与解密C#加密与解密        
{
C#加密与解密            
throw ex;
C#加密与解密        }

C#加密与解密    }

C#加密与解密}