c# 各种加密解密方法

Coder.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.IO;

public class Coder
{
    /// <summary>
    /// 对称加密
    /// </summary>
    /// <param name="sendStr"></param>
    /// <returns></returns>
    public string EncoderStr(string sendStr)
    {
        string keyWord = "67ABCD012589EF34";
        DESEncrypt desc = new DESEncrypt();
        byte[] data = desc.Encrypt(sendStr, keyWord);
        return Convert.ToBase64String(data);
    }

    /// <summary>
    /// 对称解密
    /// </summary>
    /// <param name="recStr"></param>
    /// <returns></returns>
    public string DecoderStr(string recStr)
    {
        string keyWord = "67ABCD012589EF34";
        DESEncrypt desc = new DESEncrypt();
        //将base64字符串转换成二进制BTYE数组
        byte[] recData = Convert.FromBase64String(recStr);
        recStr = desc.Decrypt(recData, keyWord);
        return recStr;
    }

    /// <summary>
    /// 把普通字符串转换成Base64字符串
    /// </summary>
    /// <param name="args"></param>
    /// <returns></returns>
    public string ConvertStringToBase64(string args)
    {
        byte[] by = System.Text.Encoding.Default.GetBytes(args);
        //把二进制BYTE数组转换成base64字符串
        string base64 = Convert.ToBase64String(by);
        if (base64.IndexOf("=") < 0)
        {
            by = System.Text.Encoding.GetEncoding("GB2312").GetBytes(args);
            base64 = Convert.ToBase64String(by);
        }
        return base64;
    }
    /// <summary>
    /// 把Base64字符串转换成普通字符串
    /// </summary>
    /// <param name="base64Str"></param>
    /// <returns></returns>
    public string ConvertBase64ToString(string base64Str)
    {
        try
        {
            byte[] by = Convert.FromBase64String(base64Str);
            return System.Text.Encoding.Default.GetString(by);
        }
        catch (Exception ex)
        {
            byte[] by = Convert.FromBase64String(base64Str);
            return System.Text.Encoding.GetEncoding("GB2312").GetString(by);
        }
    }

    /// <summary>  
    /// utf-8编码  
    /// </summary>  
    /// <param name="code"></param>  
    /// <returns></returns>  
    public string UTF8Encode(string code)
    {
        return System.Web.HttpUtility.UrlEncode(code);
    }

    /// <summary>  
    /// utf-8解码  
    /// </summary>  
    /// <param name="code"></param>  
    /// <returns></returns>  
    public string UTF8Decode(string code)
    {
        return System.Web.HttpUtility.UrlDecode(code);
    }

    /// <summary>
    /// MD5 32位加密
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string GetMD5By32(string str)
    {
        #region 32位加密 写法1
        //return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
        #endregion

        #region 写法2
        string cl = str;
        string pwd = "";
        MD5 md5 = MD5.Create();//实例化一个md5对像
        // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
        byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
        // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
        for (int i = 0; i < s.Length; i++)
        {
            // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 
            pwd = pwd + s[i].ToString("X");

        }
        return pwd;
        #endregion
    }

    /// <summary>
    /// MD5 16位加密
    /// </summary>
    /// <param name="ConvertString"></param>
    /// <returns></returns>
    public string GetMD5By16(string str)
    {
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(str)), 4, 8);
        t2 = t2.Replace("-", "");
        return t2;
    }

    /// <summary>
    /// 用ASCII码与位移来加密字符串
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string ASCIIEncode(string str)//实现接口里的方法
    {
        string hash = "";
        for (int i = 0; i < str.Length; i++)//循环字符串
            hash = hash + (char)(str[i] << 1); //每个字符 ASCII码 左移一位
        return hash;//返回这个字符串
    }

    /// <summary>
    /// 用ASCII码与位移来解密字符串
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string ASCIIDecode(string str)//实现接口里的方法
    {
        string hash = "";
        for (int i = 0; i < str.Length; i++)//同上
            hash = hash + (char)(str[i] >> 1); //每个字符 ASCII码 右移一位
        return hash;
    }

    /// <summary>
    /// 位移和异或加密
    /// </summary>
    /// <param name="characters">要加密的明文</param>
    /// <returns>加密后的密文</returns>
    public string EncryptStr(string characters)
    {
        string key = "330ead0b-4951-46a7-8db8-0e2569472fd1";

        //位移加密

        byte[] bStr = (new UnicodeEncoding()).GetBytes(characters);

        for (int i = 0; i < bStr.Length; i++)
        {
            byte b = (byte)(bStr[i] + 255);
            bStr[i] = b;
        }

        byte[] bKey = (new UnicodeEncoding()).GetBytes(key);//加密锁

        //异或加密
        for (int i = 0; i < bStr.Length; i += 2)
        {

            for (int j = 0; j < bKey.Length; j += 3)
            {
                bStr[i] = Convert.ToByte(bStr[i] ^ bKey[j]);
            }
        }
        return (new UnicodeEncoding()).GetString(bStr).TrimEnd('\0');
    }

    /// <summary>
    /// 位移和异或解密
    /// </summary>
    /// <param name="ciphertext">要解密的密文</param>
    /// <returns>解密后的明文</returns>
    public string DecryptStr(string ciphertext)
    {

        string key = "330ead0b-4951-46a7-8db8-0e2569472fd1";

        byte[] bStr = (new UnicodeEncoding()).GetBytes(ciphertext);
        byte[] bKey = (new UnicodeEncoding()).GetBytes(key);//加密锁

        //异或解密

        for (int i = 0; i < bStr.Length; i += 2)
        {
            for (int j = 0; j < bKey.Length; j += 3)
            {
                bStr[i] = Convert.ToByte(bStr[i] ^ bKey[j]);
            }
        }

        //位移解密
        for (int i = 0; i < bStr.Length; i++)
        {
            byte b = (byte)(bStr[i] - 255);
            bStr[i] = b;
        }

        return (new UnicodeEncoding()).GetString(bStr).TrimEnd('\0');
    }

    //默认密钥向量   
    private static byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

    /// <summary>  
    /// AES加密算法  
    /// </summary>  
    /// <param name="plainText">明文字符串</param>  
    /// <param name="strKey">密钥</param>  
    /// <returns>返回加密后的密文字节数组</returns>  
    public byte[] AESEncrypt(string plainText, string strKey)
    {
        //分组加密算法  
        SymmetricAlgorithm des = Rijndael.Create();
        byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组      
        //设置密钥及密钥向量  
        des.Key = Encoding.UTF8.GetBytes(strKey);
        des.IV = _key1;
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组  
        cs.Close();
        ms.Close();
        return cipherBytes;
    }

    /// <summary>  
    /// AES解密  
    /// </summary>  
    /// <param name="cipherText">密文字节数组</param>  
    /// <param name="strKey">密钥</param>  
    /// <returns>返回解密后的字符串</returns>  
    public byte[] AESDecrypt(byte[] cipherText, string strKey)
    {
        SymmetricAlgorithm des = Rijndael.Create();
        des.Key = Encoding.UTF8.GetBytes(strKey);
        des.IV = _key1;
        byte[] decryptBytes = new byte[cipherText.Length];
        MemoryStream ms = new MemoryStream(cipherText);
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read);
        cs.Read(decryptBytes, 0, decryptBytes.Length);
        cs.Close();
        ms.Close();
        return decryptBytes;
    }
    //AES实例
    void Main(string[] args)
    {
        string text = "AES加密算法测试数据"; //明文  
        string keys = "dongbinhuiasxiny";//密钥,128位              
        byte[] encryptBytes = AESEncrypt(text, keys);
        //将加密后的密文转换为Base64编码,以便显示,可以查看下结果  
        Console.WriteLine("明文:" + text);
        Console.WriteLine("密文:" + Convert.ToBase64String(encryptBytes));
        //解密  
        byte[] decryptBytes = AESDecrypt(encryptBytes, keys);
        //将解密后的结果转换为字符串,也可以将该步骤封装在解密算法中  
        string result = Encoding.UTF8.GetString(decryptBytes);
        Console.WriteLine("解密结果:" + result);
        Console.Read();
    }
}




DESEncrypt.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Collections;

/// <summary>
/// DES对称加密算法
/// </summary>
class DESEncrypt
{
    static DESEncrypt()
    {

    }
    /// <summary>
    /// 加密(DES-ECB PKCS#7)
    /// </summary>
    /// <param name="pToEncrypt">待加密的明文</param>
    /// <param name="sKey">16位16进制的字符串</param>
    /// <returns>返回加密后的字节流</returns>
    public byte[] Encrypt(string pToEncrypt, string sKey)
    {
        byte[] desByte = null;
        try
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(pToEncrypt);
            des.Key = GetKey(sKey);
            des.Mode = CipherMode.ECB;
            des.Padding = PaddingMode.PKCS7;
            desByte = des.CreateEncryptor().TransformFinalBlock(inputByteArray, 0, inputByteArray.Length);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(ex.ToString());
        }
        return desByte;
    }
    /// <summary>
    ///解密(DES-ECB PKCS#7)
    /// </summary>
    /// <param name="bodyByte">待解密的字节流</param>
    /// <param name="sKey">16位16进制的字符串</param>
    /// <returns>返回解密的字符串</returns>
    public string Decrypt(byte[] bodyByte, string sKey)
    {
        string bodyStr = string.Empty;
        try
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            des.Mode = CipherMode.ECB;
            des.Padding = PaddingMode.PKCS7;
            des.Key = GetKey(sKey);
            bodyStr = System.Text.Encoding.UTF8.GetString(des.CreateDecryptor().TransformFinalBlock(bodyByte, 0, bodyByte.Length));
        }
        catch (Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(ex.ToString());
        }
        return bodyStr;
    }


    private byte[] GetKey(string sKey)
    {

        byte[] _key = new byte[8];
        try
        {
            ArrayList array = new ArrayList();
            Char[] sKeyChar = sKey.ToCharArray();
            for (int i = 0; i < sKeyChar.Length; i = i + 2)
            {
                string str = string.Empty;
                for (int j = i; j < i + 2; j++)
                {
                    str += sKeyChar[j];
                }
                array.Add(str);
            }

            for (int i = 0; i < array.Count; i++)
            {
                _key[i] = byte.Parse(array[i].ToString(), System.Globalization.NumberStyles.AllowHexSpecifier);
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(ex.ToString());
        }
        return _key;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值