.NET 常用加密、解密& 数字签名算法

.NET 常用加密、解密& 数字签名算法
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/25

namespace 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();
        }

        /// <summary>
        /// Put the object serialization for byte array
        /// </summary>
        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;
        }

        /// <summary>
        /// Byte array reverse serialized into object
        /// </summary>
        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

        /**/
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="encryptString"></param>
        /// <returns></returns>
        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;
            }

        }

        /**/
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="decryptString"></param>
        /// <returns></returns>
        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); }
        }

        /// <summary>
        /// AES encode.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        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);
                }
            }
        }


        /// <summary>
        /// AES decode.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        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

    }
}
.NET 常用加密、解密& 数字签名算法

 

.NET 常用加密、解密& 数字签名算法

上一篇:cocos2d-x 3.0 Armature jsb 初体验


下一篇:【一次面试感悟】再谈javascript中的继承