DES對稱資料加密

耳朵裡有隻風發表於2016-05-23

/// <summary>
/// DES 加密過程
/// </summary>
/// <param name="dataToEncrypt">待加密資料</param>
/// <param name="DESKey"></param>
/// <returns></returns>
public static string Encrypt(string dataToEncrypt, string DESKey)
{
    using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
    {
        byte[] inputByteArray = Encoding.Default.GetBytes(dataToEncrypt);//把字串放到byte陣列中
        des.Key = ASCIIEncoding.ASCII.GetBytes(DESKey); //建立加密物件的金鑰和偏移量
        des.IV = ASCIIEncoding.ASCII.GetBytes(DESKey);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:x2}", b);
                }
                return ret.ToString();
            }
        }
    }
}

/// <summary>
/// DES 解密過程
/// </summary>
/// <param name="dataToDecrypt">待解密資料</param>
/// <param name="DESKey"></param>
/// <returns></returns>
public static string Decrypt(string dataToDecrypt, string DESKey)
{
    using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
    {
        byte[] inputByteArray = new byte[dataToDecrypt.Length / 2];
        for (int x = 0; x < dataToDecrypt.Length / 2; x++)
        {
            int i = (Convert.ToInt32(dataToDecrypt.Substring(x * 2, 2), 16));
            inputByteArray[x] = (byte)i;
        }
        des.Key = ASCIIEncoding.ASCII.GetBytes(DESKey); //建立加密物件的金鑰和偏移量,此值重要,不能修改
        des.IV = ASCIIEncoding.ASCII.GetBytes(DESKey);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return System.Text.Encoding.Default.GetString(ms.ToArray());
            }
        }
    }
}

【個人廣告】
希望大家可以支援我的個人微訊號“小遊戲情報局

這裡寫圖片描述

相關文章