Util_加密

Unity开发中常用的加密算法 MD5,Sha1、CRC32,Des,Res等的实现

   public class EncryptUtil
    {
        #region MD5
        public static string MD5Encrypt(string str, int length = 32)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            byte[] result = Encoding.UTF8.GetBytes(str);
            MD5 md5 = MD5.Create();
            byte[] output = md5.ComputeHash(result);
            return HandlBytes(output, length);
        }
        public static string AbstractFileMD5(string fileName, int length = 32)
        {
            if (string.IsNullOrEmpty(fileName))
                return string.Empty;
            using (FileStream file = new FileStream(fileName, FileMode.Open))
            {
                MD5 md5 = MD5.Create();
                byte[] retVal = md5.ComputeHash(file);
                return HandlBytes(retVal, length);
            }
        }
        public static string HandlBytes(byte[] intput, int length = 32)
        {
            string md5Str = string.Empty;
            switch (length)
            {
                case 16:
                    md5Str = BitConverter.ToString(intput, 4, 8);
                    break;
                default:
                    md5Str = BitConverter.ToString(intput);
                    break;
            }
            return md5Str.Replace("-", "");
        }
        #endregion

        #region Sha1
        public static string AbstractFileSha1(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return string.Empty;
            using (FileStream file = new FileStream(fileName, FileMode.Open))
            {
                SHA1 md5 = SHA1.Create();
                byte[] retVal = md5.ComputeHash(file);
                return HandlBytes(retVal);
            }
        }
        public static string EncryptSha1(string str)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            var buffer = Encoding.UTF8.GetBytes(str);
            var output = SHA1.Create().ComputeHash(buffer);
            return HandlBytes(output);
        }
        #endregion

        #region CRC32
        public static string AbstractFileCRC32(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return string.Empty;
            var buffer = File.ReadAllBytes(fileName);
            var output = CRC32.Create().ComputeHash(buffer);
            return string.Format("{0:X8}", output);
        }
        public static string EncryptCRC32(string str)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            var buffer = Encoding.UTF8.GetBytes(str);
            var output = CRC32.Create().ComputeHash(buffer);
            return string.Format("{0:X8}", output);
        }
        class CRC32
        {
            protected ulong[] Crc32Table;
            private CRC32()
            {
                //生成码表
                GetCRC32Table();
            }
            //生成CRC32码表
            public void GetCRC32Table()
            {
                ulong Crc;
                Crc32Table = new ulong[256];
                int i, j;
                for (i = 0; i < 256; i++)
                {
                    Crc = (ulong)i;
                    for (j = 8; j > 0; j--)
                    {
                        if ((Crc & 1) == 1)
                            Crc = (Crc >> 1) ^ 0xEDB88320;
                        else
                            Crc >>= 1;
                    }
                    Crc32Table[i] = Crc;
                }
            }

            //获取字符串的CRC32校验值
            public ulong ComputeHash(byte[] buffer)
            {
                ulong value = 0xffffffff;
                int len = buffer.Length;
                for (int i = 0; i < len; i++)
                {
                    value = (value >> 8) ^ Crc32Table[(value & 0xFF) ^ buffer[i]];
                }
                return value ^ 0xffffffff;
            }

            public static CRC32 Create()
            {
                return new CRC32();
            }
        }

        #endregion

        #region Des加密
        private static void HandlDesStr(ref string key)
        {
            if (key.Length >= 8)
            {
                key = key.Substring(0, 8);
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(key);
                for (int i = 0; i < 8 - key.Length; i++)
                {
                    sb.Append("#");
                }
                key = sb.ToString();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="str">必须是八位字符串</param>
        /// <param name="key">必须是八位字符串</param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string DesEncrypt(string str, string key, string iv)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            HandlDesStr(ref key);
            HandlDesStr(ref iv);
            DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
            using (MemoryStream memStream = new MemoryStream())
            {
                try
                {
                    CryptoStream crypStream = new CryptoStream(memStream, dsp.CreateEncryptor(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(iv)), CryptoStreamMode.Write);
                    StreamWriter sWriter = new StreamWriter(crypStream);
                    sWriter.Write(str);
                    sWriter.Flush();
                    crypStream.FlushFinalBlock();
                    memStream.Flush();
                    return Convert.ToBase64String(memStream.GetBuffer(), 0, (int)memStream.Length);
                }
                catch (Exception e)
                {
                    Debug.LogError(e);
                    return string.Empty;
                }
            }
        }
        public static string DesDecrypt(string str, string key, string iv)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            HandlDesStr(ref key);
            HandlDesStr(ref iv);
            DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
            byte[] buffer = Convert.FromBase64String(str);
            using (MemoryStream memStream = new MemoryStream())
            {
                try
                {
                    CryptoStream crypStream = new CryptoStream(memStream, dsp.CreateDecryptor(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(iv)), CryptoStreamMode.Write);
                    crypStream.Write(buffer, 0, buffer.Length);
                    crypStream.FlushFinalBlock();
                    return ASCIIEncoding.UTF8.GetString(memStream.ToArray());
                }
                catch (Exception e)
                {
                    Debug.LogError(e);
                    return string.Empty;
                }
            }
        }
        #endregion

        #region Res
        public static string RsaDecrypt(string str, string decryptKey)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            byte[] dataToDecrypt = Convert.FromBase64String(str);
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSA.FromXmlString(decryptKey);
            byte[] resultBytes = RSA.Decrypt(dataToDecrypt, false);
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            return ByteConverter.GetString(resultBytes);
        }
        public static KeyValuePair<string, string> GetResaKeyPair()
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            string publicKey = RSA.ToXmlString(false);
            string privateKey = RSA.ToXmlString(true);
            return new KeyValuePair<string, string>(publicKey, privateKey);
        }
        public static string ResEncrypt(string str, string encryptKey)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(encryptKey);
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] DataToEncrypt = ByteConverter.GetBytes(str);
            byte[] resultBytes = rsa.Encrypt(DataToEncrypt, false);
            return Convert.ToBase64String(resultBytes);
        }
        #endregion
    }

猜你喜欢

转载自www.cnblogs.com/PandaHome/p/10934734.html