博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.NET 常用加密、解密& 数字签名算法
阅读量:5894 次
发布时间:2019-06-19

本文共 8438 字,大约阅读时间需要 28 分钟。

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.Serialization.Formatters.Binary;using System.Security.Cryptography;using System.Text;//xlding, 2013/07/25namespace Gemr.Utils{    public class CommonAlgorithms    {        #region Sort        public static string[] BubbleSort(string[] array)        {            int length = array.Length;            for (int i = 0; i <= length - 1; i++)            {                for (int j = length - 1; j > i; j--)                {                    if (array[j].CompareTo(array[j - 1]) < 0)                    {                        string temp = array[j];                        array[j] = array[j - 1];                        array[j - 1] = temp;                    }                }            }            return array;        }        #endregion Sort        private static char[] constant =        {            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'        };        public byte[] ConvertStringToByteArray(string str)        {            if (string.IsNullOrEmpty(str)) return null;            byte[] byteArray = System.Text.Encoding.Default.GetBytes(str);            return byteArray;        }        public static string GenerateRandom(int Length)        {            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(52);            Random rd = new Random();            for (int i = 0; i < Length; i++)            {                newRandom.Append(constant[rd.Next(52)]);            }            return newRandom.ToString();        }        ///         /// Put the object serialization for byte array        ///         public static byte[] SerializeObject(object obj)        {            if (obj == null)                return null;            MemoryStream ms = new MemoryStream();            BinaryFormatter formatter = new BinaryFormatter();            formatter.Serialize(ms, obj);            ms.Position = 0;            byte[] bytes = new byte[ms.Length];            ms.Read(bytes, 0, bytes.Length);            ms.Close();            return bytes;        }        ///         /// Byte array reverse serialized into object        ///         public static object DeserializeObject(byte[] bytes)        {            object obj = null;            if (bytes == null)                return obj;            MemoryStream ms = new MemoryStream(bytes);            ms.Position = 0;            BinaryFormatter formatter = new BinaryFormatter();            obj = formatter.Deserialize(ms);            ms.Close();            return obj;        }        public static string ConvertByteArrayToString(byte[] byteArray)        {            if (byteArray == null || byteArray.Length == 0) return null;            string str = System.Text.Encoding.Default.GetString(byteArray);            return str;        }        //public static string ByteToString(byte[] value)        //{        //    StringBuilder sb = new StringBuilder();        //    for (int i = 0; i < value.Length; i++)        //    {        //        sb.Append(value[i].ToString("x2"));        //    }        //    return sb.ToString();        //}        #region SHA1 (数字签名)               public static string GetSHA1(string strSource)        {            string strResult = "";            //Create            System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();            byte[] bytResult = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strSource));            for (int i = 0; i < bytResult.Length; i++)            {                strResult = strResult + bytResult[i].ToString("X2");            }            return strResult;        }        public static byte[] GetSHA1(byte[] value)        {            System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();            return sha.ComputeHash(value);        }        #endregion SHA1        #region DES        /**/        ///         /// DES加密        ///         ///         /// 
public static string DesEncrypt(string encryptString, string sKey) { using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Convert.ToBase64String(ms.ToArray()); ms.Close(); return str; } } /**/ /// /// DES解密 /// /// ///
public static string DesDecrypt(string decryptString, string sKey) { byte[] inputByteArray = Convert.FromBase64String(decryptString); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return str; } } #endregion DES #region AES #region Use static key private static readonly byte[] aesKey = { 0x03, 0x00, 0x52, 0xc3, 0x03, 0x00, 0x52, 0xc3, 0x03, 0x00, 0x52, 0xc3, 0x03, 0x00, 0x52, 0xc3 }; public static string StaticAeskey { get { return System.Text.Encoding.Default.GetString(aesKey); } } /// /// AES encode. /// /// ///
public static string AesEncode(string value) { using (Aes aes = Aes.Create()) { using (ICryptoTransform encryptor = aes.CreateEncryptor(aesKey, aesKey)) { byte[] buffer = Encoding.UTF8.GetBytes(value); buffer = encryptor.TransformFinalBlock(buffer, 0, buffer.Length); return Convert.ToBase64String(buffer); } } } /// /// AES decode. /// /// ///
public static string AesDecode(string value) { using (Aes aes = Aes.Create()) { using (ICryptoTransform decryptor = aes.CreateDecryptor(aesKey, aesKey)) { byte[] buffer = Convert.FromBase64String(value); buffer = decryptor.TransformFinalBlock(buffer, 0, buffer.Length); return Encoding.UTF8.GetString(buffer); } } } #endregion Use static key public static byte[] GetKey() { Random rd = new Random(); byte[] key = new byte[16]; rd.NextBytes(key); return key; } public static byte[] AesEncode(byte[] key, byte[] value) { using (Aes aes = Aes.Create()) { using (ICryptoTransform encryptor = aes.CreateEncryptor(key, key)) { return encryptor.TransformFinalBlock(value, 0, value.Length); } } } public static byte[] AesDecode(byte[] key, byte[] value) { using (Aes aes = Aes.Create()) { using (ICryptoTransform decryptor = aes.CreateDecryptor(key, key)) { return decryptor.TransformFinalBlock(value, 0, value.Length); } } } #endregion AES }}

 

转载地址:http://akisx.baihongyu.com/

你可能感兴趣的文章
地址总线 数据总线 和控制总线的作用
查看>>
微信群之Java技术红包问答
查看>>
BZOJ2663 [Beijing wc2012]灵魂宝石
查看>>
go面试题
查看>>
WS_CLIPCHILDREN与WS_CLIPSIBLINGS
查看>>
.NET 环境下运行tensorflow
查看>>
第二次结对编程作业——毕设导师智能匹配
查看>>
C# 消息队列 多线程 委托
查看>>
Java 集合、Iterator迭代器、泛型等
查看>>
semantic ui框架学习笔记二
查看>>
SQL Server中DateTime与DateTime2的区别
查看>>
可集成到APP的车架号识别sdk
查看>>
jQuery获取margin-top和padding-top的值
查看>>
java集合 collection-list-ArrayList 去除ArrayList集合中的重复元素。
查看>>
Hacker(六)----黑客藏匿之地--系统进程
查看>>
[Android UI] Service里面启动Activity和Alertdialog
查看>>
产品经理如何使用 CODING 进行项目规划
查看>>
测试计划
查看>>
Android中Intent的各种常见作用。
查看>>
正则表达式
查看>>