常用密码加密解密操作相关类

    /// <summary>
    /// 密码加密解密操作相关类
    /// </summary>
    public static class EncryptHelper
    {
        #region MD5 加密

        /// <summary>
        /// MD5加密
        /// </summary>
        public static string Md532(this string source)
        {
            if (string.IsNullOrEmpty(source)) return null;
            var encoding = Encoding.UTF8;
            MD5 md5 = MD5.Create();
            return HashAlgorithmBase(md5, source, encoding);
        }

        /// <summary>
        /// 加盐MD5加密
        /// </summary>
        public static string Md532Salt(this string source, string salt)
        {
            return string.IsNullOrEmpty(source) ? source.Md532() : (source + "『" + salt + "』").Md532();
        }

        #endregion

        #region SHA 加密

        /// <summary>
        /// SHA1 加密
        /// </summary>
        public static string Sha1(this string source)
        {
            if (string.IsNullOrEmpty(source)) return null;
            var encoding = Encoding.UTF8;
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            return HashAlgorithmBase(sha1, source, encoding);
        }

        /// <summary>
        /// SHA256 加密
        /// </summary>
        public static string Sha256(this string source)
        {
            if (string.IsNullOrEmpty(source)) return null;
            var encoding = Encoding.UTF8;
            SHA256 sha256 = new SHA256Managed();
            return HashAlgorithmBase(sha256, source, encoding);
        }

        /// <summary>
        /// SHA512 加密
        /// </summary>
        public static string Sha512(this string source)
        {
            if (string.IsNullOrEmpty(source)) return null;
            var encoding = Encoding.UTF8;
            SHA512 sha512 = new SHA512Managed();
            return HashAlgorithmBase(sha512, source, encoding);
        }

        #endregion

        #region HMAC 加密

        /// <summary>
        /// HmacSha1 加密
        /// </summary>
        public static string HmacSha1(this string source, string keyVal)
        {
            if (string.IsNullOrEmpty(source)) return null;
            var encoding = Encoding.UTF8;
            byte[] keyStr = encoding.GetBytes(keyVal);
            HMACSHA1 hmacSha1 = new HMACSHA1(keyStr);
            return HashAlgorithmBase(hmacSha1, source, encoding);
        }

        /// <summary>
        /// HmacSha256 加密
        /// </summary>
        public static string HmacSha256(this string source, string keyVal)
        {
            if (string.IsNullOrEmpty(source)) return null;
            var encoding = Encoding.UTF8;
            byte[] keyStr = encoding.GetBytes(keyVal);
            HMACSHA256 hmacSha256 = new HMACSHA256(keyStr);
            return HashAlgorithmBase(hmacSha256, source, encoding);
        }

        /// <summary>
        /// HmacSha384 加密
        /// </summary>
        public static string HmacSha384(this string source, string keyVal)
        {
            if (string.IsNullOrEmpty(source)) return null;
            var encoding = Encoding.UTF8;
            byte[] keyStr = encoding.GetBytes(keyVal);
            HMACSHA384 hmacSha384 = new HMACSHA384(keyStr);
            return HashAlgorithmBase(hmacSha384, source, encoding);
        }

        /// <summary>
        /// HmacSha512 加密
        /// </summary>
        public static string HmacSha512(this string source, string keyVal)
        {
            if (string.IsNullOrEmpty(source)) return null;
            var encoding = Encoding.UTF8;
            byte[] keyStr = encoding.GetBytes(keyVal);
            HMACSHA512 hmacSha512 = new HMACSHA512(keyStr);
            return HashAlgorithmBase(hmacSha512, source, encoding);
        }

        /// <summary>
        /// HmacMd5 加密
        /// </summary>
        public static string HmacMd5(this string source, string keyVal)
        {
            if (string.IsNullOrEmpty(source)) return null;
            var encoding = Encoding.UTF8;
            byte[] keyStr = encoding.GetBytes(keyVal);
            HMACMD5 hmacMd5 = new HMACMD5(keyStr);
            return HashAlgorithmBase(hmacMd5, source, encoding);
        }

        /// <summary>
        /// HmacRipeMd160 加密
        /// </summary>
        public static string HmacRipeMd160(this string source, string keyVal)
        {
            if (string.IsNullOrEmpty(source)) return null;
            var encoding = Encoding.UTF8;
            byte[] keyStr = encoding.GetBytes(keyVal);
            HMACRIPEMD160 hmacRipeMd160 = new HMACRIPEMD160(keyStr);
            return HashAlgorithmBase(hmacRipeMd160, source, encoding);
        }

        #endregion

        #region AES 加密解密

        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="source">待加密字段</param>
        /// <param name="keyVal">密钥值</param>
        /// <param name="ivVal">加密辅助向量</param>
        /// <returns></returns>
        public static string AesStr(this string source, string keyVal, string ivVal)
        {
            var encoding = Encoding.UTF8;
            byte[] btKey = keyVal.FormatByte(encoding);
            byte[] btIv = ivVal.FormatByte(encoding);
            byte[] byteArray = encoding.GetBytes(source);
            string encrypt;
            Rijndael aes = Rijndael.Create();
            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(btKey, btIv), CryptoStreamMode.Write))
                {
                    cStream.Write(byteArray, 0, byteArray.Length);
                    cStream.FlushFinalBlock();
                    encrypt = Convert.ToBase64String(mStream.ToArray());
                }
            }
            aes.Clear();
            return encrypt;
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="source">待加密字段</param>
        /// <param name="keyVal">密钥值</param>
        /// <param name="ivVal">加密辅助向量</param>
        /// <returns></returns>
        public static string UnAesStr(this string source, string keyVal, string ivVal)
        {
            var encoding = Encoding.UTF8;
            byte[] btKey = keyVal.FormatByte(encoding);
            byte[] btIv = ivVal.FormatByte(encoding);
            byte[] byteArray = Convert.FromBase64String(source);
            string decrypt;
            Rijndael aes = Rijndael.Create();
            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(btKey, btIv), CryptoStreamMode.Write))
                {
                    cStream.Write(byteArray, 0, byteArray.Length);
                    cStream.FlushFinalBlock();
                    decrypt = encoding.GetString(mStream.ToArray());
                }
            }
            aes.Clear();
            return decrypt;
        }

        /// <summary>
        /// AES Byte类型 加密
        /// </summary>
        /// <param name="data">待加密明文</param>
        /// <param name="keyVal">密钥值</param>
        /// <param name="ivVal">加密辅助向量</param>
        /// <returns></returns>
        public static byte[] AesByte(this byte[] data, string keyVal, string ivVal)
        {
            byte[] bKey = new byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(keyVal.PadRight(bKey.Length)), bKey, bKey.Length);
            byte[] bVector = new byte[16];
            Array.Copy(Encoding.UTF8.GetBytes(ivVal.PadRight(bVector.Length)), bVector, bVector.Length);
            byte[] cryptograph;
            Rijndael aes = Rijndael.Create();
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bVector), CryptoStreamMode.Write))
                    {
                        cStream.Write(data, 0, data.Length);
                        cStream.FlushFinalBlock();
                        cryptograph = mStream.ToArray();
                    }
                }
            }
            catch
            {
                cryptograph = null;
            }
            return cryptograph;
        }

        /// <summary>
        /// AES Byte类型 解密
        /// </summary>
        /// <param name="data">待解密明文</param>
        /// <param name="keyVal">密钥值</param>
        /// <param name="ivVal">加密辅助向量</param>
        /// <returns></returns>
        public static byte[] UnAesByte(this byte[] data, string keyVal, string ivVal)
        {
            byte[] bKey = new byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(keyVal.PadRight(bKey.Length)), bKey, bKey.Length);
            byte[] bVector = new byte[16];
            Array.Copy(Encoding.UTF8.GetBytes(ivVal.PadRight(bVector.Length)), bVector, bVector.Length);
            byte[] original;
            Rijndael aes = Rijndael.Create();
            try
            {
                using (MemoryStream mStream = new MemoryStream(data))
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read))
                    {
                        using (MemoryStream originalMemory = new MemoryStream())
                        {
                            byte[] buffer = new byte[1024];
                            int readBytes;
                            while ((readBytes = cStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                originalMemory.Write(buffer, 0, readBytes);
                            }

                            original = originalMemory.ToArray();
                        }
                    }
                }
            }
            catch
            {
                original = null;
            }
            return original;
        }

        #endregion

        #region RSA 加密解密

        //密钥对,请配合密钥生成工具使用『 http://download.csdn.net/detail/downiis6/9464639 』
        private const string PublicRsaKey = @"<RSAKeyValue>
  <Modulus>8Yvf/LjXRhCuOREk2CuSYvbD/RadwJ4sjHREIpQVKwkTlG3BtRgpnaMcoeLAesmwvpBWnqK4hBkYLxhRj+NEKnlGrJ+LkNMnZr0/4CMuulZFAnx7iQYaSq7Eh7kBKGLofc05CjZguYpnPNxHIv4VNx+a9tIh+hnhjrmkJLUm3l0=</Modulus>
  <Exponent>AQAB</Exponent>
</RSAKeyValue>";
        private const string PrivateRsaKey = @"<RSAKeyValue>
  <Modulus>8Yvf/LjXRhCuOREk2CuSYvbD/RadwJ4sjHREIpQVKwkTlG3BtRgpnaMcoeLAesmwvpBWnqK4hBkYLxhRj+NEKnlGrJ+LkNMnZr0/4CMuulZFAnx7iQYaSq7Eh7kBKGLofc05CjZguYpnPNxHIv4VNx+a9tIh+hnhjrmkJLUm3l0=</Modulus>
  <Exponent>AQAB</Exponent>
  <P>/xAaa/4dtDxcEAk5koSZBPjuxqvKJikpwLA1nCm3xxAUMDVxSwQyr+SHFaCnBN9kqaNkQCY6kDCfJXFWPOj0Bw==</P>
  <Q>8m8PFVA4sO0oEKMVQxt+ivDTHFuk/W154UL3IgC9Y6bzlvYewXZSzZHmxZXXM1lFtwoYG/k+focXBITsiJepew==</Q>
  <DP>ONVSvdt6rO2CKgSUMoSfQA9jzRr8STKE3i2lVG2rSIzZosBVxTxjOvQ18WjBroFEgdQpg23BQN3EqGgvqhTSQw==</DP>
  <DQ>gfp7SsEM9AbioTDemHEoQlPly+FyrxE/9D8UAt4ErGX5WamxSaYntOGRqcOxcm1djEpULMNP90R0Wc7uhjlR+w==</DQ>
  <InverseQ>C0eBsp2iMOxWwKo+EzkHOP0H+YOitUVgjekGXmSt9a3TvikQNaJ5ATlqKsZaMGsnB6UIHei+kUaCusVX0HgQ2A==</InverseQ>
  <D>tPYxEfo9Nb3LeO+SJe3G1yO+w37NIwCdqYB1h15f2YUMSThNVmpKy1HnYpUp1RQDuVETw/duu3C9gJL8kAsZBjBrVZ0zC/JZsgvSNprfUK3Asc4FgFsGfQGKW1nvvgdMbvqr4ClB0R8czkki+f9Oc5ea/RMqXxlI+XjzMYDEknU=</D>
</RSAKeyValue>";

        /// <summary>
        /// RSA 加密
        /// </summary>
        public static string Rsa(this string source)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(PublicRsaKey);
            var cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(source), true);
            return Convert.ToBase64String(cipherbytes);
        }

        /// <summary>
        /// RSA解密
        /// </summary>
        public static string UnRsa(this string source)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(PrivateRsaKey);
            var cipherbytes = rsa.Decrypt(Convert.FromBase64String(source), true);
            return Encoding.UTF8.GetString(cipherbytes);
        }

        #endregion

        #region DES 加密解密

        /// <summary>
        /// DES 加密
        /// </summary>
        public static string Des(this string source, string keyVal, string ivVal)
        {
            try
            {
                byte[] data = Encoding.UTF8.GetBytes(source);
                var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : keyVal), IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : ivVal) };
                var desencrypt = des.CreateEncryptor();
                byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
                return BitConverter.ToString(result);
            }
            catch { return "转换出错!"; }
        }

        /// <summary>
        /// DES 解密
        /// </summary>
        public static string UnDes(this string source, string keyVal, string ivVal)
        {
            try
            {
                string[] sInput = source.Split("-".ToCharArray());
                byte[] data = new byte[sInput.Length];
                for (int i = 0; i < sInput.Length; i++)
                {
                    data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
                }
                var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : keyVal), IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : ivVal) };
                var desencrypt = des.CreateDecryptor();
                byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
                return Encoding.UTF8.GetString(result);
            }
            catch { return "解密出错!"; }
        }

        #endregion

        #region TripleDES 加密解密

        /// <summary>
        /// DES3 加密
        /// </summary>
        public static string Des3(this string source, string keyVal)
        {
            try
            {
                TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
                {
                    Key = keyVal.FormatByte(Encoding.UTF8),
                    Mode = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] btArray = Encoding.UTF8.GetBytes(source);
                    try
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(btArray, 0, btArray.Length);
                            cs.FlushFinalBlock();
                        }
                        return ms.ToArray().Bytes2Str();
                    }
                    catch { return source; }
                }
            }
            catch
            {
                return "TripleDES加密出现错误";
            }
        }

        /// <summary>
        /// DES3 解密
        /// </summary>
        public static string UnDes3(this string source, string keyVal)
        {
            try
            {
                byte[] byArray = source.Str2Bytes();
                TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
                {
                    Key = keyVal.FormatByte(Encoding.UTF8),
                    Mode = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(byArray, 0, byArray.Length);
                        cs.FlushFinalBlock();
                        cs.Close();
                        ms.Close();
                        return Encoding.UTF8.GetString(ms.ToArray());
                    }
                }
            }
            catch
            {
                return "TripleDES解密出现错误";
            }
        }

        #endregion

        #region BASE64 加密解密

        /// <summary>
        /// BASE64 加密
        /// </summary>
        /// <param name="source">待加密字段</param>
        /// <returns></returns>
        public static string Base64(this string source)
        {
            var btArray = Encoding.UTF8.GetBytes(source);
            return Convert.ToBase64String(btArray, 0, btArray.Length);
        }

        /// <summary>
        /// BASE64 解密
        /// </summary>
        /// <param name="source">待解密字段</param>
        /// <returns></returns>
        public static string UnBase64(this string source)
        {
            var btArray = Convert.FromBase64String(source);
            return Encoding.UTF8.GetString(btArray);
        }

        #endregion

        #region 内部方法

        /// <summary>
        /// 转成数组
        /// </summary>
        private static byte[] Str2Bytes(this string source)
        {
            source = source.Replace(" ", "");
            byte[] buffer = new byte[source.Length / 2];
            for (int i = 0; i < source.Length; i += 2) buffer[i / 2] = Convert.ToByte(source.Substring(i, 2), 16);
            return buffer;
        }

        /// <summary>
        /// 转换成字符串
        /// </summary>
        private static string Bytes2Str(this IEnumerable<byte> source, string formatStr = "{0:X2}")
        {
            StringBuilder pwd = new StringBuilder();
            foreach (byte btStr in source) { pwd.AppendFormat(formatStr, btStr); }
            return pwd.ToString();
        }

        private static byte[] FormatByte(this string strVal, Encoding encoding)
        {
            return encoding.GetBytes(strVal.Base64().Substring(0, 16).ToUpper());
        }

        /// <summary>
        /// HashAlgorithm 加密统一方法
        /// </summary>
        private static string HashAlgorithmBase(HashAlgorithm hashAlgorithmObj, string source, Encoding encoding)
        {
            byte[] btStr = encoding.GetBytes(source);
            byte[] hashStr = hashAlgorithmObj.ComputeHash(btStr);
            return hashStr.Bytes2Str();
        }

        #endregion
    }

原文地址:https://www.cnblogs.com/ruanraun/p/9050261.html

时间: 2024-10-15 01:10:14

常用密码加密解密操作相关类的相关文章

JS中的加密解密操作,以及对应的C#中的加密解密

JS: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>RSA Login Test</title> <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> <scri

利用PBFunc在Powerbuilder中进行国密SM4的加密解密操作

利用PBFunc的n_pbfunc_cryp对象可以很方便的进行SM4的加密解密操作,其中ECB不需要向量IV,其它模式需要IV 代码下载地址:https://download.csdn.net/download/my_aa/12309197 SM4加密: 1 //可用 http://aks.jd.com/tools/sec/ 对比结果 2 string ls_data 3 ls_data = sle_1.Text//要加密的数据 4 string ls_key 5 ls_key = sle_k

C#常用的加密解密方法

开篇 C#内置很多加密解密的方法,有MD5,SHA1,base64等.这里会简单介绍下这几个方法以及用法,不过不会深入研究每种加密方法的原理,高手请绕行. 这几个加密解密会分为两类说,一类是只有加密,没有解密类型的MD5,SHA1.此类加密常用在数据校验.一类是有加密,有解密类型的base64,DES,RSA.此类加密常用在数据传输. 数据校验型 MD5 Message Digest Algorithm MD5(中文名为消息摘要算法第五版)为计算机安全领域广泛使用的一种散列函数,用以提供消息的完

ios RSA加密解密一些相关问题

前言: 最近在做一个类似支付宝的理财项目,涉及到了RSA加解密方面的知识,在这里也遇到了不少的问题.写出来与大家分享心得. 1.什么是RSA加密解密(ios RSA加密解密过程) 这些网上都说的很清楚,大家可以从网上查找一下. 理论上是可以用公钥加密,私钥解密,或者是私钥加密,公钥解密. 我的理解是:A向B请求数据:A把自己的信息用私钥签名,并且把自己的公钥传送给B, B受到A的数据:B将A的公钥取出,并且用A的公钥确认签名, B向A发送数据:B将自己的数据用A公钥加密,再将自己的公钥暴露给A,

我常用的加密解密代码

代码 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/ -->/*用法 protected void Page_Load(object sender, EventArgs e) { //加密 this.Title = CEncrypt.DesEncrypt("pwd", CEncrypt.Key); this.Title += CEncry

凯撒密码加密解密--JAVA实现(基础)

凯撒密码一种代换密码,据说凯撒是率先使用加密函的古代将领之一,因此这种加密方法被称为恺撒密码.凯撒密码的基本思想是:通过把字母移动一定的位数来实现加密和解密.明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文. 使用JAVA程序实现对明文的加密: package com.qikeyishu.www; public class Kaisapwd { public static void main(String[] args) { char str[]={'a','b'

Openfire用户密码加密解密

需求要求审核过程中都用匿名进行用户注册登录,注册用户审核通过后才使用openfire内置表 如何做到用户密码统一 Openfire是通过org.jivesoftware.util.Blowfish.java实现的加密. 密钥:在openfire的数据库中有表ofproperty,其中就有passwordKey的值 Blowfish blow=new Blowfish(passwordKey); //加密 String encrypt=blow.encryptString("123");

常用字符串加密解密方法

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web.Security; namespace HuaTong.General.Utility { /// <summa

vue 登录 + 记住密码 + 密码加密解密

<template> <el-form :model="ruleForm"> <h3 class="title">系统登录</h3> <el-form-item prop="mobile"> <el-input type="text" v-model="ruleForm.mobile" auto-complete="off"