美文网首页
C#之常用加解密

C#之常用加解密

作者: 小羊爱学习 | 来源:发表于2024-06-02 09:05 被阅读0次

    加解密在数据传输中尤为重要,其加密解密的方式也有很多种,我这个类目前只总结了几个常用的,后续用到时会继续完善添加

        public static class JSCSecurityTool
        {
            #region AES加解密
            //默认密钥向量
            private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };
    
            /// <summary>
            /// 对称加密算法AES(块式加密算法)
            /// </summary>
            /// <param name="encryptString">待加密字符串</param>
            /// <param name="encryptKey">加密密钥,须半角字符</param>
            /// <param name="mode">加密模式</param>
            /// <returns>加密结果字符串</returns>
            public static string AESEncrypt(string encryptString, string encryptKey, CipherMode mode = CipherMode.CBC)
            {
                encryptKey = GetSHA256Hash(encryptKey);
                var aes = Aes.Create();
                aes.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));
                aes.IV = Keys;
                aes.Mode = mode;
                var rijndaelEncrypt = aes.CreateEncryptor();
                byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
                byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
                return Convert.ToBase64String(encryptedData);
            }
    
            /// <summary>
            /// 对称加密算法AES解密字符串
            /// </summary>
            /// <param name="decryptString">待解密的字符串</param>
            /// <param name="decryptKey">解密密钥,和加密密钥相同</param>
            /// <param name="mode">加密模式</param>
            /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
            public static string AESDecrypt(string decryptString, string decryptKey, CipherMode mode = CipherMode.CBC)
            {
                try
                {
                    decryptKey = GetSHA256Hash(decryptKey);
                    var aes = Aes.Create("AesManaged");
                    aes.Key = Encoding.UTF8.GetBytes(decryptKey);
                    aes.IV = Keys;
                    aes.Mode = mode;
                    ICryptoTransform rijndaelDecrypt = aes.CreateDecryptor();
                    byte[] inputData = Convert.FromBase64String(decryptString);
                    byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
                    return Encoding.UTF8.GetString(decryptedData);
                }
                catch
                {
                    return string.Empty;
                }
            }
    
            // 使用SHA-256哈希函数处理秘钥
            private static string GetSHA256Hash(string input)
            {
                using (SHA256 sha256 = System.Security.Cryptography.SHA256.Create())
                {
                    byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                    byte[] hashedBytes = sha256.ComputeHash(inputBytes);
                    // 取前32字节作为AES算法的秘钥
                    return Convert.ToBase64String(hashedBytes).Substring(0, 32);
                }
            }
            #endregion
    
            #region Base64加密解密
            /// <summary>
            /// Base64加密
            /// </summary>
            /// <param name="str">需要加密的字符串</param>
            /// <returns>加密后的数据</returns>
            public static string Base64Encrypt(string str)
            {
                try
                {
                    byte[] encbuff = Encoding.UTF8.GetBytes(str);
                    return Convert.ToBase64String(encbuff);
                }
                catch
                {
                    return str;
                }
            }
    
            /// <summary>
            /// Base64解密
            /// </summary>
            /// <param name="str">需要解密的字符串</param>
            /// <returns>解密后的数据</returns>
            public static string Base64Decrypt(string str)
            {
                try
                {
                    byte[] decbuff = Convert.FromBase64String(str);
                    return Encoding.UTF8.GetString(decbuff);
                }
                catch
                {
                    return str;
                }
            }
            #endregion
    
            #region MD5加密
            /// <summary>
            ///     对字符串进行MD5摘要
            /// </summary>
            /// <param name="str">需要摘要的字符串</param>
            /// <returns>MD5摘要字符串</returns>
            public static string MD5Encrypt(string str)
            {
                MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
                byte[] hashedDataBytes;
                hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(str));
                StringBuilder byte2String = new StringBuilder();
                foreach (byte i in hashedDataBytes)
                {
                    byte2String.Append(i.ToString("x2"));
                }
                return byte2String.ToString();
            }
            #endregion
    
            #region SHA256加密
            /// <summary>
            /// SHA256函数
            /// </summary>
            /// <param name="str">原始字符串</param>
            /// <returns>SHA256结果(返回长度为44字节的字符串),SHA256的输出长度固定为256位</returns>
            public static string SHA256EncryptBase64(string str)
            {
                byte[] sha256Data = Encoding.UTF8.GetBytes(str);
                using (var sha256 = SHA256.Create())
                {
                    byte[] result = sha256.ComputeHash(sha256Data);
                    return Convert.ToBase64String(result); //返回长度为44字节的字符串
                }
            }
    
            /// <summary>
            /// SHA256函数
            /// </summary>
            /// <param name="str"></param>
            /// <returns>SHA256结果(十六进制字符串)</returns>
            public static string SHA256EncryptHex(string str)
            {
                //使用 SHA256 加密算法:
                SHA256 sha256 = new SHA256Managed();
                byte[] sha256Bytes = Encoding.Default.GetBytes(str);
                byte[] cryString = sha256.ComputeHash(sha256Bytes);
                string sha256Str = string.Empty;
                for (int i = 0; i < cryString.Length; i++)
                {
                    sha256Str += cryString[i].ToString("X2");
                }
                return sha256Str;
            }
            #endregion
        }
    
    

    相关文章

      网友评论

          本文标题:C#之常用加解密

          本文链接:https://www.haomeiwen.com/subject/wttsqjtx.html