• 传递参数安全验证代码示例


    在开发内部系统当中,我们经常使用参数进行传递,但由于明文传递会涉及到安全问题。所以我们一般都是加密明文再和明文一起传递,接受方再检测是否被明文是否中途被篡改。

    表达不好,还是看代码吧!

    上图是我对字符串加密和解密后的对照图。

    下面是才是我调用的类:

    /// <summary>
    /// 对称加密处理类
    /// </summary>
    public class SymmCrypt
    {
        private SymmetricAlgorithm mobjCryptoService;
    
        public enum SymmProvEnum
        {
            DES, RC2, Rijndael
        }
    
        public SymmCrypt()
        {
            this.mobjCryptoService = new DESCryptoServiceProvider();
        }
    
        /// <summary>
        /// 构造函数,选择加密方式
        /// </summary>
        /// <param name="encryptType"></param>
        public SymmCrypt(SymmProvEnum encryptType)
        {
            switch (encryptType)
            {
                case SymmProvEnum.DES:
                    mobjCryptoService = new DESCryptoServiceProvider();
                    break;
                case SymmProvEnum.RC2:
                    mobjCryptoService = new RC2CryptoServiceProvider();
                    break;
                case SymmProvEnum.Rijndael:
                    mobjCryptoService = new RijndaelManaged();
                    break;
    
            }
        }
    
        /// <summary>
        /// 利用MD5加密算法加密
        /// </summary>
        /// <param name="strIN">需要加密的字符串</param>
        /// <returns>返回加密过的字符串</returns>
        public static string MD5Encrypt(string strIN)
        {
            byte[] tmpByte;
            MD5 md5 = new MD5CryptoServiceProvider();
            tmpByte = md5.ComputeHash(GetBytesBySting(strIN));
            md5.Clear();
            return GetStringByBytes(tmpByte);
    
        }
    
        /// <summary>
        /// 利用SHA1加密算法加密
        /// </summary>
        /// <param name="strIN">需要加密的字符串</param>
        /// <returns>返回加密过的字符串</returns>
        public static string SHA1Encrypt(string strIN)
        {
            byte[] tmpByte;
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            tmpByte = sha1.ComputeHash(GetBytesBySting(strIN));
            sha1.Clear();
            return GetStringByBytes(tmpByte);
    
        }
    
        /// <summary>
        /// 利用SHA256加密算法加密
        /// </summary>
        /// <param name="strIN">需要加密的字符串</param>
        /// <returns>返回加密过的字符串</returns>
        public static string SHA256Encrypt(string strIN)
        {
            byte[] tmpByte;
            SHA256 sha256 = new SHA256Managed();
            tmpByte = sha256.ComputeHash(GetBytesBySting(strIN));
            sha256.Clear();
            return GetStringByBytes(tmpByte);
        }
    
        /// <summary>
        /// 利用SHA512加密算法加密
        /// </summary>
        /// <param name="strIN">需要加密的字符串</param>
        /// <returns>返回加密过的字符串</returns>
        public static string SHA512Encrypt(string strIN)
        {
            byte[] tmpByte;
            SHA512 sha512 = new SHA512Managed();
            tmpByte = sha512.ComputeHash(GetBytesBySting(strIN));
            sha512.Clear();
            return GetStringByBytes(tmpByte);
    
        }
    
        #region Base64加密
        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="text">要加密的字符串</param>
        /// <returns></returns>
        public static string EncodeBase64(string text)
        {
            //如果字符串为空,则返回
            if (string.IsNullOrEmpty(text))
            {
                return "";
            }
    
            try
            {
                char[] Base64Code = new char[]{'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','0','1','2','3','4','5','6','7',
                                                '8','9','+','/','='};
                byte empty = (byte)0;
                ArrayList byteMessage = new ArrayList(Encoding.Default.GetBytes(text));
                StringBuilder outmessage;
                int messageLen = byteMessage.Count;
                int page = messageLen / 3;
                int use = 0;
                if ((use = messageLen % 3) > 0)
                {
                    for (int i = 0; i < 3 - use; i++)
                        byteMessage.Add(empty);
                    page++;
                }
                outmessage = new System.Text.StringBuilder(page * 4);
                for (int i = 0; i < page; i++)
                {
                    byte[] instr = new byte[3];
                    instr[0] = (byte)byteMessage[i * 3];
                    instr[1] = (byte)byteMessage[i * 3 + 1];
                    instr[2] = (byte)byteMessage[i * 3 + 2];
                    int[] outstr = new int[4];
                    outstr[0] = instr[0] >> 2;
                    outstr[1] = ((instr[0] & 0x03) << 4) ^ (instr[1] >> 4);
                    if (!instr[1].Equals(empty))
                        outstr[2] = ((instr[1] & 0x0f) << 2) ^ (instr[2] >> 6);
                    else
                        outstr[2] = 64;
                    if (!instr[2].Equals(empty))
                        outstr[3] = (instr[2] & 0x3f);
                    else
                        outstr[3] = 64;
                    outmessage.Append(Base64Code[outstr[0]]);
                    outmessage.Append(Base64Code[outstr[1]]);
                    outmessage.Append(Base64Code[outstr[2]]);
                    outmessage.Append(Base64Code[outstr[3]]);
                }
                return outmessage.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    
        #region Base64解密
        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="text">要解密的字符串</param>
        public static string DecodeBase64(string text)
        {
            ////如果字符串为空,则返回
            //if (ValidationHelper.IsNullOrEmpty<string>(text))
            //{
            //    return "";
            //}
    
            //将空格替换为加号
            text = text.Replace(" ", "+");
    
            try
            {
                if ((text.Length % 4) != 0)
                {
                    return "包含不正确的BASE64编码";
                }
                if (!Regex.IsMatch(text, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase))
                {
                    return "包含不正确的BASE64编码";
                }
                string Base64Code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
                int page = text.Length / 4;
                ArrayList outMessage = new ArrayList(page * 3);
                char[] message = text.ToCharArray();
                for (int i = 0; i < page; i++)
                {
                    byte[] instr = new byte[4];
                    instr[0] = (byte)Base64Code.IndexOf(message[i * 4]);
                    instr[1] = (byte)Base64Code.IndexOf(message[i * 4 + 1]);
                    instr[2] = (byte)Base64Code.IndexOf(message[i * 4 + 2]);
                    instr[3] = (byte)Base64Code.IndexOf(message[i * 4 + 3]);
                    byte[] outstr = new byte[3];
                    outstr[0] = (byte)((instr[0] << 2) ^ ((instr[1] & 0x30) >> 4));
                    if (instr[2] != 64)
                    {
                        outstr[1] = (byte)((instr[1] << 4) ^ ((instr[2] & 0x3c) >> 2));
                    }
                    else
                    {
                        outstr[2] = 0;
                    }
                    if (instr[3] != 64)
                    {
                        outstr[2] = (byte)((instr[2] << 6) ^ instr[3]);
                    }
                    else
                    {
                        outstr[2] = 0;
                    }
                    outMessage.Add(outstr[0]);
                    if (outstr[1] != 0)
                        outMessage.Add(outstr[1]);
                    if (outstr[2] != 0)
                        outMessage.Add(outstr[2]);
                }
                byte[] outbyte = (byte[])outMessage.ToArray(Type.GetType("System.Byte"));
                return Encoding.Default.GetString(outbyte);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    
    
        /// <summary>
        /// 把字节转换成字符串
        /// </summary>
        /// <param name="Byte">需要转换字节数组</param>
        /// <returns>转换后的字符串</returns>
        private static string GetStringByBytes(byte[] Byte)
        {
            string tmpString = "";
            //tmpString = UTF8Encoding.Default.GetString(Byte);
            tmpString = BitConverter.ToString(Byte);
            return tmpString;
        }
    
        /// <summary>
        /// 把字符串转换成字节数组
        /// </summary>
        /// <param name="strKey">需要转换的字符串</param>
        /// <returns>转换后的字节数组</returns>
        private static byte[] GetBytesBySting(string strKey)
        {
            int tmpStrLen = strKey.Length;
            byte[] tmpByte = new byte[tmpStrLen - 1];
            tmpByte = UTF8Encoding.Default.GetBytes(strKey);
            return tmpByte;
        }
    
    
        /// <summary>
        /// 获取Key的字节
        /// </summary>
        /// <param name="keyString">Key字符串</param>
        /// <returns>转换后的字节形式</returns>
        private byte[] GetKeyBytes(string keyString)
        {
            string sTemp = "";
            if (mobjCryptoService.LegalKeySizes.Length > 0)
            {
                int lessSize = 0;
                int moreSize = mobjCryptoService.LegalKeySizes[0].MinSize;
                while (keyString.Length * 8 > moreSize)
                {
                    lessSize = moreSize;
                    moreSize += mobjCryptoService.LegalKeySizes[0].SkipSize;
                    System.Threading.Thread.Sleep(0);
                }
                sTemp = keyString.PadRight(moreSize / 8, '_');
            }
            else
                sTemp = keyString;
            return ASCIIEncoding.ASCII.GetBytes(sTemp);
        }
    
        /// <summary>
        /// 获取IV向量的字节
        /// </summary>
        /// <param name="ivString">IV向量字符串</param>
        /// <returns>转换后的字节形式</returns>
        private byte[] GetIvBytes(string ivString)
        {
            ivString += "diksk.sl";
            ivString = ivString.Substring(0, this.mobjCryptoService.IV.Length);
            return ASCIIEncoding.ASCII.GetBytes(ivString);
        }
    
    
    
        /// <summary>
        /// 对输入的字符串进行加密
        /// </summary>
        /// <param name="sourceString">需要加密的原始字符串</param>
        /// <param name="keyString">加密密钥</param>
        /// <param name="ivString">加密向量</param>
        /// <returns>加密后的字符串</returns>
        public string Encrypt(string sourceString, string keyString, string ivString)
        {
            byte[] data = Encoding.Default.GetBytes(sourceString);
            byte[] result;
            mobjCryptoService.Key = GetKeyBytes(keyString);
            mobjCryptoService.IV = GetIvBytes(ivString);
            ICryptoTransform desencrypt = mobjCryptoService.CreateEncryptor();
            result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            string desString = "";
            for (int i = 0; i < result.Length; i++)
            {
                desString += result[i].ToString() + "-";
            }
    
            //return desString.TrimEnd('-');
            return BitConverter.ToString(result);
        }
    
        /// <summary>
        /// 对输入的密文字符串进行解密
        /// </summary>
        /// <param name="sourceString">需要解密的密文字符串</param>
        /// <param name="keyString">解密密钥</param>
        /// <param name="ivString">解密向量</param>
        /// <returns>解密后的原始字符串</returns>
        public string Decrypt(string sourceString, string keyString, string ivString)
        {
            try
            {
                string[] sInput = sourceString.Split("-".ToCharArray());
                byte[] data = new byte[sInput.Length];
                byte[] result;
                for (int i = 0; i < sInput.Length; i++)
                    data[i] = byte.Parse(sInput[i], System.Globalization.NumberStyles.HexNumber);
                mobjCryptoService.Key = GetKeyBytes(keyString);
                mobjCryptoService.IV = GetIvBytes(ivString);
                ICryptoTransform desencrypt = mobjCryptoService.CreateDecryptor();
                result = desencrypt.TransformFinalBlock(data, 0, data.Length);
                return Encoding.Default.GetString(result);
            }
            catch
            {
                return "error";
            }
        }
    
        
    }
  • 相关阅读:
    正则表达式简介
    每个程序员都必须遵守的编程原则
    String, StringBuffer, StringBuilder
    一些软件设计的原则
    A hard puzzle ACM HDU1097
    ACM HDU 1032The 3n + 1 problem
    Humble Numbers HDU 1058 ACM
    ACM HDU 1028Ignatius and the Princess III
    HangOver ACM HDU1056
    ACM HDU 1021Fibonacci Again
  • 原文地址:https://www.cnblogs.com/flyfish2012/p/3431353.html
Copyright © 2020-2023  润新知