表明来源

https://www.cnblogs.com/shanranlei/p/3630944.html#!comments

本文列举了    数据加密算法(Data Encryption Algorithm,DEA) 密码学中的高级加密标准(Advanced EncryptionStandard,AES)RSA公钥加密算法 的加密解密 .NET实现以及 安全哈希算法(Secure Hash Algorithm)和MD5的实现。

实现如下

        #region MD5

        /// <summary>

        /// MD5加密为32字符长度的16进制字符串

        /// </summary>

        /// <paramname="input"></param>

        /// <returns></returns>

        public static stringEncryptByMD5(string input)

        {

            MD5 md5Hasher = MD5.Create();

            byte[] data =md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input));

            StringBuilder sBuilder = newStringBuilder();

            //将每个字节转为16进制

            for (int i = 0; i < data.Length;i++)

            {

               sBuilder.Append(data[i].ToString("x2"));

            }

            return sBuilder.ToString();

        }

        #endregion

  

        #region SHA1

        /// <summary>

        /// SHA1加密

        /// </summary>

        /// <paramname="input"></param>

        /// <returns></returns>

        public static stringEncryptBySHA1(string input)

        {

            SHA1 sha = new SHA1CryptoServiceProvider();

            byte[] bytes =Encoding.Unicode.GetBytes(input);

            byte[] result =sha.ComputeHash(bytes);

            returnBitConverter.ToString(result);

        }

        #endregion

  

 #region DES
//DES默认密钥向量 private static byte[] DES_IV = { 0x12,0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
/// <summary> /// 加密方法 /// </summary> /// <paramname="input"></param> /// <paramname="key"></param> /// <returns></returns> public static stringEncryptByDES(string input, string key) { byte[] inputBytes =Encoding.UTF8.GetBytes(input); //Encoding.UTF8.GetBytes(input); byte[] keyBytes =ASCIIEncoding.UTF8.GetBytes(key); byte[] encryptBytes =EncryptByDES(inputBytes, keyBytes, keyBytes); //string result =Encoding.UTF8.GetString(encryptBytes); //无法解码,其加密结果中文出现乱码:d\"?e????(??uπ?W??-??,_?\nJn7 //原因:如果明文为中文,UTF8编码两个字节标识一个中文字符,但是加密后,两个字节密文,不一定还是中文字符。 using (DES des = newDESCryptoServiceProvider()) { using (MemoryStream ms = newMemoryStream()) { using (CryptoStream cs =new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { using (StreamWriterwriter = new StreamWriter(cs)) { writer.Write(inputBytes); } } } } string result =Convert.ToBase64String(encryptBytes); return result; } /// <summary> /// DES加密 /// </summary> /// <paramname="inputBytes">输入byte数组</param> /// <param name="key">密钥,只能是英文字母或数字</param> /// <param name="IV">偏移向量</param> /// <returns></returns> public static byte[]EncryptByDES(byte[] inputBytes, byte[] key, byte[] IV) { DES des = newDESCryptoServiceProvider(); //建立加密对象的密钥和偏移量 des.Key = key; des.IV = IV; string result = string.Empty; //1、如果通过CryptoStreamMode.Write方式进行加密,然后CryptoStreamMode.Read方式进行解密,解密成功。 using (MemoryStream ms = newMemoryStream()) { using (CryptoStream cs = newCryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputBytes, 0,inputBytes.Length); } return ms.ToArray(); } //2、如果通过CryptoStreamMode.Write方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,可以得到正确结果 //3、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Read方式进行解密,无法解密,Error:要解密的数据的长度无效。 //4、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,无法解密,Error:要解密的数据的长度无效。 //using (MemoryStream ms = newMemoryStream(inputBytes)) //{ // using (CryptoStream cs = newCryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Read)) // { // using (StreamReader reader = newStreamReader(cs)) // { // result = reader.ReadToEnd(); // returnEncoding.UTF8.GetBytes(result); // } // } //} } /// <summary> /// 解密 /// </summary> /// <paramname="input"></param> /// <paramname="key"></param> /// <returns></returns> public static stringDecryptByDES(string input, string key) { //UTF8无法解密,Error:要解密的数据的长度无效。 //byte[] inputBytes =Encoding.UTF8.GetBytes(input);//UTF8乱码,见加密算法 byte[] inputBytes =Convert.FromBase64String(input); byte[] keyBytes =ASCIIEncoding.UTF8.GetBytes(key); byte[] resultBytes = DecryptByDES(inputBytes,keyBytes, keyBytes); string result =Encoding.UTF8.GetString(resultBytes); return result; } /// <summary> /// 解密方法 /// </summary> /// <param name="inputBytes"></param> /// <paramname="key"></param> /// <paramname="iv"></param> /// <returns></returns> public static byte[]DecryptByDES(byte[] inputBytes, byte[] key, byte[] iv) { DESCryptoServiceProvider des = newDESCryptoServiceProvider(); //建立加密对象的密钥和偏移量,此值重要,不能修改 des.Key = key; des.IV = iv; //通过write方式解密 //using (MemoryStream ms = newMemoryStream()) //{ // using (CryptoStream cs = newCryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) // { // cs.Write(inputBytes, 0,inputBytes.Length); // } // return ms.ToArray(); //} //通过read方式解密 using (MemoryStream ms = newMemoryStream(inputBytes)) { using (CryptoStream cs = newCryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) { using (StreamReader reader = newStreamReader(cs)) { string result =reader.ReadToEnd(); returnEncoding.UTF8.GetBytes(result); } } } //错误写法,注意哪个是输出流的位置,如果范围ms,与原文不一致。 //using (MemoryStream ms = newMemoryStream(inputBytes)) //{ // using (CryptoStream cs = newCryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) // { // cs.Read(inputBytes, 0,inputBytes.Length); // } // return ms.ToArray(); //} } /// <summary> /// 加密字符串 /// </summary> /// <param name="input"></param> /// <paramname="sKey"></param> /// <returns></returns> public static stringEncryptString(string input, string sKey) { byte[] data =Encoding.UTF8.GetBytes(input); using (DESCryptoServiceProvider des= new DESCryptoServiceProvider()) { des.Key =ASCIIEncoding.ASCII.GetBytes(sKey); des.IV =ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform desencrypt = des.CreateEncryptor(); byte[] result =desencrypt.TransformFinalBlock(data, 0, data.Length); returnBitConverter.ToString(result); } } /// <summary> /// 解密字符串 /// </summary> /// <paramname="input"></param> /// <paramname="sKey"></param> /// <returns></returns> public static stringDecryptString(string input, string sKey) { string[] sInput =input.Split("-".ToCharArray()); byte[] data = new byte[sInput.Length]; for (int i = 0; i <sInput.Length; i++) { data[i] = byte.Parse(sInput[i],NumberStyles.HexNumber); } using (DESCryptoServiceProvider des= new DESCryptoServiceProvider()) { des.Key =ASCIIEncoding.ASCII.GetBytes(sKey); des.IV =ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform desencrypt =des.CreateDecryptor(); byte[] result =desencrypt.TransformFinalBlock(data, 0, data.Length); returnEncoding.UTF8.GetString(result); } } #endregion

  

  //AES默认密钥向量   

        public static readonly byte[] AES_IV ={ 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90,0xAB, 0xCD, 0xEF };

 #region AES

        /// <summary>  

        /// AES加密算法  

        /// </summary>  

        /// <paramname="input">明文字符串</param>  

        /// <param name="key">密钥</param>  

        /// <returns>字符串</returns>  

        public static stringEncryptByAES(string input, string key)

        {

            byte[] keyBytes =Encoding.UTF8.GetBytes(key.Substring(0, 32));

            using (AesCryptoServiceProvideraesAlg = new AesCryptoServiceProvider())

            {

                aesAlg.Key = keyBytes;

                aesAlg.IV = AES_IV;

                ICryptoTransform encryptor =aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt =new MemoryStream())

                {

                    using (CryptoStreamcsEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))

                    {

                        using (StreamWriterswEncrypt = new StreamWriter(csEncrypt))

                        {

                           swEncrypt.Write(input);

                        }

                        byte[] bytes =msEncrypt.ToArray();

                        //returnConvert.ToBase64String(bytes);//此方法不可用

                        returnBitConverter.ToString(bytes);

                    }

                }

            }

        }

        /// <summary>  

        /// AES解密  

        /// </summary>  

        /// <paramname="input">密文字节数组</param>  

        /// <param name="key">密钥</param>  

        /// <returns>返回解密后的字符串</returns>  

        public static stringDecryptByAES(string input, string key)

        {

            //byte[] inputBytes =Convert.FromBase64String(input); //Encoding.UTF8.GetBytes(input);

            string[] sInput =input.Split("-".ToCharArray());

            byte[] inputBytes = newbyte[sInput.Length];

            for (int i = 0; i <sInput.Length; i++)

            {

                inputBytes[i] =byte.Parse(sInput[i], NumberStyles.HexNumber);

            }

            byte[] keyBytes =Encoding.UTF8.GetBytes(key.Substring(0, 32));

            using (AesCryptoServiceProvideraesAlg = new AesCryptoServiceProvider())

            {

                aesAlg.Key = keyBytes;

                aesAlg.IV = AES_IV;

                ICryptoTransform decryptor =aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt =new MemoryStream(inputBytes))

                {

                    using (CryptoStreamcsEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))

                    {

                        using (StreamReadersrEncrypt = new StreamReader(csEncrypt))

                        {

                            returnsrEncrypt.ReadToEnd();

                        }

                    }

                }

            }

        }

        /// <summary> 

        /// AES加密        

        /// </summary> 

        /// <param name="inputdata">输入的数据</param>         

       /// <param name="iv">向量128位</param>         

       /// <param name="strKey">加密密钥</param>         

       /// <returns></returns> 

        public static byte[]EncryptByAES(byte[] inputdata, byte[] key, byte[] iv)

        {

            ////分组加密算法 

            //Aes aes = newAesCryptoServiceProvider();          

            ////设置密钥及密钥向量 

            //aes.Key = key;

            //aes.IV = iv;

            //using (MemoryStream ms = newMemoryStream())

            //{

            //    using (CryptoStream cs = newCryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))

            //    {

            //        using (StreamWriter writer = newStreamWriter(cs))

            //        {

            //            writer.Write(inputdata);

            //        }

            //        return ms.ToArray(); 

            //    }               

            //}

            using (AesCryptoServiceProvideraesAlg = new AesCryptoServiceProvider())

            {

                aesAlg.Key = key;

                aesAlg.IV = iv;

                ICryptoTransform encryptor =aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt =new MemoryStream())

                {

                    using (CryptoStreamcsEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))

                    {

                        using (StreamWriterswEncrypt = new StreamWriter(csEncrypt))

                        {

                            swEncrypt.Write(inputdata);

                        }

                        byte[] encrypted =msEncrypt.ToArray();

                        return encrypted;

                    }

                }

            }

        }

       /// <summary>         

        /// AES解密         

        /// </summary> 

       /// <param name="inputdata">输入的数据</param>               

       /// <param name="key">key</param>         

       /// <param name="iv">向量128</param> 

        /// <returns></returns> 

        public static byte[]DecryptByAES(byte[] inputBytes, byte[] key, byte[] iv)

        {

            Aes aes = newAesCryptoServiceProvider();

            aes.Key = key;

            aes.IV = iv;

            byte[] decryptBytes;

            using (MemoryStream ms = newMemoryStream(inputBytes))

            {

                using (CryptoStream cs = newCryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))

                {

                    using (StreamReader reader= new StreamReader(cs))

                    {

                        string result =reader.ReadToEnd();

                        decryptBytes =Encoding.UTF8.GetBytes(result);

                    }

                }

            }

            return decryptBytes;

        }

        #endregion

  

 #region RSA

        /// <summary>

        /// RSA加密

        /// </summary>

        /// <paramname="plaintext">明文</param>

        /// <paramname="publicKey">公钥</param>

        /// <returns>密文字符串</returns>

        public static stringEncryptByRSA(string plaintext, string publicKey)

        {

            UnicodeEncoding ByteConverter = newUnicodeEncoding();

            byte[] dataToEncrypt =ByteConverter.GetBytes(plaintext);

            using (RSACryptoServiceProvider RSA= new RSACryptoServiceProvider())

            {

                RSA.FromXmlString(publicKey);

                byte[] encryptedData =RSA.Encrypt(dataToEncrypt, false);

                return Convert.ToBase64String(encryptedData);

            }

        }

        /// <summary>

        /// RSA解密

        /// </summary>

        /// <paramname="ciphertext">密文</param>

        /// <paramname="privateKey">私钥</param>

        /// <returns>明文字符串</returns>

        public static stringDecryptByRSA(string ciphertext, string privateKey)

        {

            UnicodeEncoding byteConverter = newUnicodeEncoding();

            using (RSACryptoServiceProvider RSA= new RSACryptoServiceProvider())

            {

                RSA.FromXmlString(privateKey);

                byte[] encryptedData =Convert.FromBase64String(ciphertext);

                byte[] decryptedData =RSA.Decrypt(encryptedData, false);

                returnbyteConverter.GetString(decryptedData);

            }

        }

        //public static string signByRSA(stringplaintext, string privateKey)

        //{

        //   UnicodeEncoding ByteConverter = new UnicodeEncoding();

        //   byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);

        //   using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())

        //   {

        //        RSA.FromXmlString(privateKey);

        //        byte[] encryptedData =RSA.SignData(dataToEncrypt,);

        //        return Convert.ToBase64String(encryptedData);

        //   }

        //}

        /// <summary>

        /// 数字签名

        /// </summary>

        /// <paramname="plaintext">原文</param>

        /// <paramname="privateKey">私钥</param>

        /// <returns>签名</returns>

        public static stringHashAndSignString(string plaintext, string privateKey)

        {

            UnicodeEncoding ByteConverter = newUnicodeEncoding();

            byte[] dataToEncrypt =ByteConverter.GetBytes(plaintext);

            using (RSACryptoServiceProviderRSAalg = new RSACryptoServiceProvider())

            {

               RSAalg.FromXmlString(privateKey);

                //使用SHA1进行摘要算法,生成签名

                byte[] encryptedData =RSAalg.SignData(dataToEncrypt, new SHA1CryptoServiceProvider());

                returnConvert.ToBase64String(encryptedData);

            }

        }

        /// <summary>

        /// 验证签名

        /// </summary>

        /// <paramname="plaintext">原文</param>

        /// <paramname="SignedData">签名</param>

        /// <paramname="publicKey">公钥</param>

        /// <returns></returns>

        public static bool VerifySigned(stringplaintext, string SignedData, string publicKey)

        {

            using (RSACryptoServiceProviderRSAalg = new RSACryptoServiceProvider())

            {

               RSAalg.FromXmlString(publicKey);

                UnicodeEncoding ByteConverter =new UnicodeEncoding();

                byte[] dataToVerifyBytes =ByteConverter.GetBytes(plaintext);

                byte[] signedDataBytes =Convert.FromBase64String(SignedData);

                returnRSAalg.VerifyData(dataToVerifyBytes, new SHA1CryptoServiceProvider(),signedDataBytes);

            }

        }

        /// <summary>

        /// 获取Key

        /// 键为公钥,值为私钥

        /// </summary>

        /// <returns></returns>

        public static KeyValuePair<string,string> CreateRSAKey()

        {

            RSACryptoServiceProvider RSA = newRSACryptoServiceProvider();

            string privateKey =RSA.ToXmlString(true);

            string publicKey =RSA.ToXmlString(false);

            return new KeyValuePair<string,string>(publicKey, privateKey);

        }

        #endregion

  

        #region other

        /// <summary>

        /// 

        /// </summary>

        /// <param name="input"></param>

        /// <returns></returns>

        public static byte[] GetBytes(stringinput)

        {

            string[] sInput =input.Split("-".ToCharArray());

            byte[] inputBytes = newbyte[sInput.Length];

            for (int i = 0; i <sInput.Length; i++)

            {

                inputBytes[i] =byte.Parse(sInput[i], NumberStyles.HexNumber);

            }

            return inputBytes;

        }

        #endregion

  

[转]NET实现RSA AES DES 字符串 加密解密以及SHA1 MD5加密的更多相关文章

  1. NET实现RSA AES DES 字符串 加密解密以及SHA1 MD5加密

    本文列举了    数据加密算法(Data Encryption Algorithm,DEA) 密码学中的高级加密标准(Advanced EncryptionStandard,AES)RSA公钥加密算法 ...

  2. Asp.Net Core 2.0 项目实战(7)MD5加密、AES&DES对称加解密

    本文目录 1. 摘要 2. MD5加密封装 3. AES的加密.解密 4. DES加密/解密 5. 总结 1.  摘要 C#中常用的一些加密和解密方案,如:md5加密.RSA加密与解密和DES加密等, ...

  3. 各种加密解密函数(URL加密解密、sha1加密解密、des加密解密)

    原文:各种加密解密函数(URL加密解密.sha1加密解密.des加密解密) 普通hash函数如md5.sha1.base64等都是不可逆函数.虽然我们利用php可以利用这些函数写出可逆函数来.但是跨语 ...

  4. AES加密解密 助手类 CBC加密模式

    "; string result1 = AESHelper.AesEncrypt(str); string result2 = AESHelper.AesDecrypt(result1); ...

  5. 16位的MD5加密和32位MD5加密的区别

    16位的MD5加密和32位MD5加密的区别 MD5加密后所得到的通常是32位的编码,而在不少地方会用到16位的编码它们有什么区别呢?16位加密就是从32位MD5散列中把中间16位提取出来!其实破解16 ...

  6. 加密 解密 RSA & AES & DES

    git: https://github.com/XHTeng/XHCryptorTools rsa RSA加解密中必须考虑到的密钥长度.明文长度和密文长度问题.明文长度需要小于密钥长度,而密文长度则等 ...

  7. RSA,DES,RC4,3DES ,MD5

    一,RSA算法基于一个十分简单的数论事实:将两个大质数相乘十分容易,但是想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥. RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需 ...

  8. Android DES加密的CBC模式加密解密和ECB模式加密解密

    DES加密共有四种模式:电子密码本模式(ECB).加密分组链接模式(CBC).加密反馈模式(CFB)和输出反馈模式(OFB). CBC模式加密: import java.security.Key; i ...

  9. PHP中使用OpenSSL生成RSA公钥私钥及进行加密解密示例(非对称加密)

    php服务端与客户端交互.提供开放api时,通常需要对敏感的部分api数据传输进行数据加密,这时候rsa非对称加密就能派上用处了,下面通过一个例子来说明如何用php来实现数据的加密解密 先了解一下关于 ...

  10. IOS中把字符串加密/IOS中怎么样MD5加密/IOS中NSString分类的实现

    看完过后,你会学到: 1学习IOS开发中的分类实现, 2以及类方法的书写, 3以及字符串的MD5加密/解密. ---------------------------wolfhous---------- ...

随机推荐

  1. 使用layui实现分页展示数据库的数据

    layui是一个前端 UI 框架,内置了js代码,所以我们可以直接使用内置的分页 首先要用到layui的官网手册https://www.layui.com/ 1.进入手册页面的 "示例&qu ...

  2. (0416) python正则 RE 【用python处理sv源文件-格式化代码】

    https://zhuanlan.zhihu.com/p/144069088

  3. xss-labs

    level1 <h1 align=center>欢迎来到level1</h1> <h2 align=center>欢迎用户te111</h2><c ...

  4. 学习- vue 中 API $attr 用法

    2.4.0新增 定义:包含了父作用域不作为 prop 被识别(且获取)的 attribute 绑定( class 和 style 除外).当一个组件没有声明任何 prop 时,这里会包含所有父作用域的 ...

  5. ARM-THUMB procedure call standard(ATPCS是ARM-Thumb过程调用标准的简称)

    为了使单独编译的c语言和汇编程序之间能够相互调用,必须为子程序之间的调用规定一定的规则.ATPCS就是ARM程序和Thumb程序中子程序的基本规则. 基本ATPCS规定了在子程序调用时的一些基本规则, ...

  6. vim替换查找缩进操作

    1.替换 r(要替换的字符)              将游标所在字母替换为指定字母 R(要替换的字符)             连续替换,直到按下Esc cc          删除整行并进入到插入 ...

  7. Linux 文件编码操作enca[适用Mac]

    查看文件编码: enca file.csv 修改文件编码 enca -x UTF-8 file.csv

  8. 如何从相机拍照建立的Fileprovider中获取绝对路径

    我们通过高版本获取的fileprovider,然后拍了个照片,如下 imageUri = FileProvider.getUriForFile 但是我们发现当我们 File file = new Fi ...

  9. nop 中创建任务(Task)

    NopCommerce 中Task 原理是服务端开启线程定时跑. 1.在数据表ScheduleTask中添加一条数据, 2.自定义类,继承ITask 即可 using Data.Log4Net; us ...

  10. select标签如何实现 每个option传递多个值

    设计项目时 我们有时候会利用 <select>  <option  value="值1" > </option>  </select> ...