开发者论坛

 找回密码
 注册 (请使用非IE浏览器)
查看: 4651|回复: 1

[源码] C# 各种加密/解密方式和Base64编码/解码

[复制链接]

0

精华

0

贡献

0

赞扬

帖子
2
软币
93
在线时间
4 小时
注册时间
2019-1-26
发表于 2019-1-27 11:03:40 | 显示全部楼层 |阅读模式
本帖最后由 choose 于 2019-1-27 11:08 编辑

C# 各种加密/解密方式和Base64编码/解码

  • MD5加密

  • DES加密/解密

  • SHA1加密

  • RSA加密/解密

  • AES加密/解密

  • Base64编码/解码

  • RSA-SHA1 数字签名



[C#] 纯文本查看 复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Common
{
    /// <summary>
    /// 加密
    /// </summary>
    public class EncryptHelper
    {
        #region MD5加密
        /// <summary>
        /// GetMD5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EncryptMD5(string source)
        {
            byte[] b = System.Text.Encoding.Default.GetBytes(source);
            b = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
            {
                ret += b[i].ToString("x").PadLeft(2, '0');
            }
            return ret;
        }

        /// <summary>
        /// 用MD5加密,全大写
        /// </summary>
        /// <param name="source">待加密字符串</param>
        /// <returns>加密后字符串</returns>
        public static string EncryptMD5ToUpper(string source)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(source, "md5").ToUpper();
        }
        #endregion

        #region DES加密

        //默认密钥向量
        private static byte[] Keys = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 };
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
        public static string EncryptDES(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }

        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
        public static string DecryptDES(string decryptString, string decryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }
        #endregion

        #region SHA1加密
        /// <summary>
        /// use sha1 to encrypt string
        /// </summary>
        public static string EncryptSHA1(string source)
        {
            byte[] StrRes = Encoding.Default.GetBytes(source);
            HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
            StrRes = iSHA.ComputeHash(StrRes);
            StringBuilder EnText = new StringBuilder();
            foreach (byte iByte in StrRes)
            {
                EnText.AppendFormat("{0:x2}", iByte);
            }
            return EnText.ToString();
        }
        #endregion

        #region RSA加密
        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="publickey"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string EncryptRSA(string publickey, string content)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(publickey);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);

            return Convert.ToBase64String(cipherbytes);
        }

        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="privatekey"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string DecryptRSA(string privatekey, string content)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(privatekey);
            cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);

            return Encoding.UTF8.GetString(cipherbytes);
        }
        #endregion

        #region AES加密
        /*
         * 跨程序使用AES加密,需要注意运算模式和填充模式;
         * 比如java
         * 需要设置
         * Mode = CipherMode.ECB; //C#默认运算模式为CBC,java默认为ECB,因此要将C#的加密方式改为ECB
         * Padding = PaddingMode.PKCS7; //设置为PKCS7,否则解密后字符串结尾会出现多余字符
         * 测试地址:http://www.seacha.com/tools/aes.html 
         */

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

        /// <summary>
        /// AES加密,返回Base64编码后的字符
        /// </summary>
        /// <param name="plainText">明文字符串</param>
        /// <param name="strKey">密钥</param>
        /// <returns>返回加密后的Base64编码字符串</returns>
        public static string EncryptAES(string plainText, string strKey)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(plainText);

            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = Encoding.UTF8.GetBytes(strKey);
            rDel.IV = _Aeskey;
            rDel.BlockSize = 128;
            rDel.Mode = CipherMode.ECB;//设置为ECB
            rDel.Padding = PaddingMode.PKCS7;//设置为PKCS7,否则解密后字符串结尾会出现多余字符

            ICryptoTransform cTransform = rDel.CreateEncryptor();
            var s = cTransform.TransformFinalBlock(byteArray, 0, byteArray.Length);
            var encrypt = Convert.ToBase64String(s);
            rDel.Clear();
            return encrypt;
        }
        /// <summary>
        /// AES解密,返回解密后的字符串
        /// </summary>
        /// <param name="cipherText">Base64编码的密文</param>
        /// <param name="strKey">密钥</param>
        /// <returns>返回解密后的字符串</returns>
        public static string DecryptAES(string cipherText, string strKey)
        {
            byte[] byteArray = Convert.FromBase64String(cipherText);

            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = Encoding.UTF8.GetBytes(strKey);
            rDel.IV = _Aeskey;
            rDel.BlockSize = 128;
            rDel.Mode = CipherMode.ECB;//必须设置为ECB
            rDel.Padding = PaddingMode.PKCS7;//必须设置为PKCS7

            ICryptoTransform cTransform = rDel.CreateDecryptor();

            var s = cTransform.TransformFinalBlock(byteArray, 0, byteArray.Length);

            var decrypt = Encoding.UTF8.GetString(s);
            rDel.Clear();
            return decrypt;



        }
        #endregion

        #region Base64编码
        public static string EncryptBase64(string source)
        {
            byte[] bytes = Encoding.Default.GetBytes(source);
            return Convert.ToBase64String(bytes);
        }
        public static string EncryptBase64(byte[] bytes)
        {
            return Convert.ToBase64String(bytes);
        }
        public static string DecryptBase64(string source)
        {
            byte[] outputb = Convert.FromBase64String(source);
            return Encoding.Default.GetString(outputb);
        }
        #endregion

        #region RSA-SHA1 数字签名
        /// <summary>
        /// 数字签名 
        /// </summary>
        /// <param name="plaintext">原文</param>
        /// <param name="privateKey">私钥</param>
        /// <returns>Base64 签名</returns>
        public static string HashAndSignString(string plaintext, string privateKey)
        {
            UTF8Encoding ByteConverter = new UTF8Encoding();
            byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);

            using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider())
            {
                RSAalg.FromXmlString(privateKey);
                //使用SHA1进行摘要算法,生成签名
                byte[] encryptedData = RSAalg.SignData(dataToEncrypt, new SHA1CryptoServiceProvider());
                return Convert.ToBase64String(encryptedData);
            }
        }
        /// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="plaintext">原文</param>
        /// <param name="SignedData">Base64 签名</param>
        /// <param name="publicKey">公钥</param>
        /// <returns></returns>
        public static bool VerifySigned(string plaintext, string SignedData, string publicKey)
        {
            try
            {
                using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider())
                {
                    RSAalg.FromXmlString(publicKey);
                    UTF8Encoding ByteConverter = new UTF8Encoding();
                    byte[] dataToVerifyBytes = ByteConverter.GetBytes(plaintext);
                    byte[] signedDataBytes = Convert.FromBase64String(SignedData);
                    return RSAalg.VerifyData(dataToVerifyBytes, new SHA1CryptoServiceProvider(), signedDataBytes);
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion
    } 
}


文章内容转载自:cssteach.com

回复

使用道具 举报

Archiver|手机版|小黑屋|开发者网 ( 苏ICP备08004430号-2 )
版权所有:南京韵文教育信息咨询有限公司

GMT+8, 2024-12-22 20:03

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表