C#加密与解密

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;
        }

    }

}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的盐加密解密可以使用以下步骤: 1. 生成一个随机的盐值 2. 将盐值与要加密的数据进行拼接 3. 使用某种加密算法(如AES)对拼接后的字符串进行加密 4. 将盐值和加密后的数据一起存储 解密时,需要先取出盐值,然后使用相同的加密算法对剩余部分进行解密。以下是一个示例代码: ```csharp using System; using System.Security.Cryptography; using System.Text; class Program { static void Main(string[] args) { string password = "password123"; string salt = GenerateSalt(); string encryptedPassword = EncryptPassword(password, salt); Console.WriteLine("Original password: " + password); Console.WriteLine("Salt: " + salt); Console.WriteLine("Encrypted password: " + encryptedPassword); string decryptedPassword = DecryptPassword(encryptedPassword, salt); Console.WriteLine("Decrypted password: " + decryptedPassword); } static string GenerateSalt() { byte[] saltBytes = new byte[16]; using (var rng = new RNGCryptoServiceProvider()) { rng.GetBytes(saltBytes); } return Convert.ToBase64String(saltBytes); } static string EncryptPassword(string password, string salt) { byte[] saltBytes = Convert.FromBase64String(salt); byte[] passwordBytes = Encoding.UTF8.GetBytes(password); byte[] combinedBytes = new byte[saltBytes.Length + passwordBytes.Length]; Buffer.BlockCopy(saltBytes, 0, combinedBytes, 0, saltBytes.Length); Buffer.BlockCopy(passwordBytes, 0, combinedBytes, saltBytes.Length, passwordBytes.Length); byte[] encryptedBytes; using (var aes = Aes.Create()) { aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.GenerateIV(); aes.Key = Encoding.UTF8.GetBytes("mysecretpassword12345"); using (var encryptor = aes.CreateEncryptor()) { encryptedBytes = encryptor.TransformFinalBlock(combinedBytes, 0, combinedBytes.Length); } } return Convert.ToBase64String(encryptedBytes); } static string DecryptPassword(string encryptedPassword, string salt) { byte[] saltBytes = Convert.FromBase64String(salt); byte[] encryptedBytes = Convert.FromBase64String(encryptedPassword); byte[] decryptedBytes; using (var aes = Aes.Create()) { aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = Encoding.UTF8.GetBytes("mysecretpassword12345"); aes.IV = encryptedBytes.Take(16).ToArray(); using (var decryptor = aes.CreateDecryptor()) { decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 16, encryptedBytes.Length - 16); } } byte[] passwordBytes = new byte[decryptedBytes.Length - saltBytes.Length]; Buffer.BlockCopy(decryptedBytes, saltBytes.Length, passwordBytes, 0, passwordBytes.Length); return Encoding.UTF8.GetString(passwordBytes); } } ``` 注意,上述代码中的密码和加密密钥应该使用更加安全的方式进行管理,例如将其存储在安全的密钥库中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值