c# encryption

Of the

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

/// <summary>
/// 字符串加密组件
/// </summary>
public class DesEncrypt
{
    
    
    private const string CIV = "Mi9l/+7Zujhy12se6Yjy111A";  //初始化向量
    private const string CKEY = "jkHuIy9D/9i="; //密钥(常量)
    
    /// <summary>
    /// 解密字符串
    /// </summary>
    /// <param name="Value">要解密的字符串</param>
    /// <returns>string</returns>
    public static string DecryptString(string encStr)
    {
    
    
        try
        {
    
    
            DESCryptoServiceProvider mCSP = new DESCryptoServiceProvider();
            byte[] byt = Convert.FromBase64String(encStr);
            MemoryStream ms = new MemoryStream();
            //用指定的密钥和初始化向量创建对称数据解密标准
            ICryptoTransform ct = mCSP.CreateDecryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV));
            CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();

            return Encoding.UTF8.GetString(ms.ToArray()); //将字节数组中的所有字符解码为一个字符串
        }
        catch (Exception e)
        {
    
    
            return e.Message;
        }
    }
    
    /// <summary>
    /// 加密字符串
    /// </summary>
    /// <param name="Value">需加密的字符串</param>
    /// <returns></returns>
    public static string EncryptString(string Value)
    {
    
    
        try
        {
    
    
            DESCryptoServiceProvider mCSP = new DESCryptoServiceProvider();
            byte[] byt = Encoding.UTF8.GetBytes(Value);
            MemoryStream ms = new MemoryStream(); //创建内存流
            //CreateEncryptor创建(对称数据)加密对象
            ICryptoTransform ct = mCSP.CreateEncryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV)); 
            CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); //将内存流链接到加密转换的流
            cs.Write(byt, 0, byt.Length); //写入内存流
            cs.FlushFinalBlock(); //将缓冲区中的数据写入内存流,并清除缓冲区
            cs.Close(); //释放内存流

            return Convert.ToBase64String(ms.ToArray()); //将内存流转写入字节数组并转换为string字符
        }
        catch (Exception e)
        {
    
    
            return e.Message;
        }
    }
}

Base64

using System;
using System.Text;

public class Base64Encrypter
{
    
    
    /// Base64加密 
    /// <param name="codeName">加密采用的编码方式</param> 
    /// <param name="source">待加密的明文</param> 
    /// <returns>加密后的字符串</returns>
    public static string EncodeBase64(string source)
    {
    
    
        Encoding encode = Encoding.UTF8;
        byte[] bytes = encode.GetBytes(source);
        string result = Convert.ToBase64String(bytes);
        return result;
    }

    /// Base64解密 
    /// <param name="codeName">解密采用的编码方式,注意和加密时采用的方式一致</param> 
    /// <param name="result">待解密的密文</param> 
    /// <returns>解密后的字符串</returns> 
    public static string DecodeBase64(string result)
    {
    
    
        Encoding encode = Encoding.UTF8;
        byte[] bytes = Convert.FromBase64String(result);
        string decode = encode.GetString(bytes);
        return decode;
    }
}

SHA1

		/// <summary>
        /// sha1加密
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static string encodeToSHA1(string content)
        {
    
    
            try
            {
    
    
                Encoding encode = Encoding.UTF8;
                SHA1 sha1 = new SHA1CryptoServiceProvider();
                byte[] bytes_in = encode.GetBytes(content);
                byte[] bytes_out = sha1.ComputeHash(bytes_in);
                sha1.Dispose();
                string result = BitConverter.ToString(bytes_out);
                result = result.Replace("-", "");
                return result.ToLower();
            }
            catch (Exception ex)
            {
    
    
                throw new Exception("SHA1 encode error:" + ex.Message);
            }
        }

AES

	/// <summary>
    ///  AES 加密
    /// </summary>
    /// <param name="str">明文(待加密)</param>
    /// <param name="key">密文</param>
    /// <returns></returns>
    public static string AesEncrypt(string key,string iv, string str)
    {
    
    
        if (string.IsNullOrEmpty(str)) return null;
        Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
        
        // 待考证
        // 无法加密16个字符的key,需要补全
        // byte[] bs = new byte[32];
        // 关键代码 补全
        // BitConverter.ToInt32(temp, 0);
        // byte[] data = Encoding.UTF8.GetBytes(key);
        // Array.Copy(data, 0, bs, 0, data.Length);

        System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
        {
    
    
            IV = Encoding.UTF8.GetBytes(iv),
            Key = Encoding.UTF8.GetBytes(key),
            //KeySize = 128/8,
            Mode = System.Security.Cryptography.CipherMode.CBC,
            Padding = System.Security.Cryptography.PaddingMode.PKCS7
            // 当您设置Key属性,KeySize属性自动设置为新密钥的位长度。
            // 设置KeySize属性时,现有密钥被清除(并且在下次访问密钥时自动生成新的随机密钥)。
            // 因此,如果您正在设置Key属性,则没有必要事先设置KeySize属性。
        };

        System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
        Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        string result = Convert.ToBase64String(resultArray, 0, resultArray.Length);
        result = result.Replace("+", "-").Replace("/", "_").Replace("=", "~");

        return result;
    }
    
    /// <summary>
    ///  AES 解密
    /// </summary>
    /// <param name="str">明文(待解密)</param>
    /// <param name="key">密文</param>
    /// <returns></returns>
    public static string AesDecrypt(string key, string iv, string str)
    {
    
    
        if (string.IsNullOrEmpty(str)) return null;
        str = str.Replace("-", "+").Replace("_", "/").Replace("~", "=");
        
        Byte[] toEncryptArray = Convert.FromBase64String(str);

        System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
        {
    
    
            IV = Encoding.UTF8.GetBytes(iv),
            Key = Encoding.UTF8.GetBytes(key),
            Mode = System.Security.Cryptography.CipherMode.CBC,
            Padding = System.Security.Cryptography.PaddingMode.PKCS7
        };

        System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
        Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        return Encoding.UTF8.GetString(resultArray);
    }

RSA

	public static string RSAEncrypt(string publickey, string content)
    {
    
    
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        byte[] cipherbytes;
        rsa.FromXmlString(publickey);
        cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
        string result = Convert.ToBase64String(cipherbytes);
        result = result.Replace("+", "-").Replace("/", "_").Replace("=", "~");
 
        return result;
    }

The publicKey is in xml format. If the input is a base64 string, it cannot be directly encrypted and needs to be converted.
source

namespace RSA
{
    
    
    using System;
    using System.Security.Cryptography;
    using Org.BouncyCastle.Asn1.Pkcs;
    using Org.BouncyCastle.Math;
    using Org.BouncyCastle.Pkcs;
    using Org.BouncyCastle.Asn1.X509;
    using Org.BouncyCastle.X509;
    using Org.BouncyCastle.Security;
    using Org.BouncyCastle.Crypto.Parameters;
 
    public class RSAKeyConverter
    {
    
    
        /// <summary>
        /// xml private key -> base64 private key string
        /// </summary>
        /// <param name="xmlPrivateKey"></param>
        /// <returns></returns>
        public static string FromXmlPrivateKey(string xmlPrivateKey)
        {
    
    
            string result = string.Empty;
            using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
    
    
                rsa.FromXmlString(xmlPrivateKey);
                RSAParameters param = rsa.ExportParameters(true);
                RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(
                    new BigInteger(1, param.Modulus), new BigInteger(1, param.Exponent),
                    new BigInteger(1, param.D), new BigInteger(1, param.P),
                    new BigInteger(1, param.Q), new BigInteger(1, param.DP),
                    new BigInteger(1, param.DQ), new BigInteger(1, param.InverseQ));
                PrivateKeyInfo privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
               
                result = Convert.ToBase64String(privateKey.ToAsn1Object().GetEncoded());
            }
            return result;
        }
 
        /// <summary>
        /// xml public key -> base64 public key string
        /// </summary>
        /// <param name="xmlPublicKey"></param>
        /// <returns></returns>
        public static string FromXmlPublicKey(string xmlPublicKey)
        {
    
    
            string result = string.Empty;
            using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
    
    
                rsa.FromXmlString(xmlPublicKey);
                RSAParameters p = rsa.ExportParameters(false);
                RsaKeyParameters keyParams = new RsaKeyParameters(
                    false, new BigInteger(1,p.Modulus), new BigInteger(1, p.Exponent));
                SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyParams);
                result = Convert.ToBase64String(publicKeyInfo.ToAsn1Object().GetEncoded());
            }
            return result;
        }
 
        /// <summary>
        /// base64 private key string -> xml private key
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string ToXmlPrivateKey(string privateKey)
        {
    
    
            RsaPrivateCrtKeyParameters privateKeyParams =
                PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey)) as RsaPrivateCrtKeyParameters;
            using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
    
    
                RSAParameters rsaParams = new RSAParameters()
                {
    
    
                    Modulus = privateKeyParams.Modulus.ToByteArrayUnsigned(),
                    Exponent = privateKeyParams.PublicExponent.ToByteArrayUnsigned(),
                    D = privateKeyParams.Exponent.ToByteArrayUnsigned(),
                    DP = privateKeyParams.DP.ToByteArrayUnsigned(),
                    DQ = privateKeyParams.DQ.ToByteArrayUnsigned(),
                    P = privateKeyParams.P.ToByteArrayUnsigned(),
                    Q = privateKeyParams.Q.ToByteArrayUnsigned(),
                    InverseQ = privateKeyParams.QInv.ToByteArrayUnsigned()
                };
                rsa.ImportParameters(rsaParams);
                return rsa.ToXmlString(true);
            }
        }
 
        /// <summary>
        /// base64 public key string -> xml public key
        /// </summary>
        /// <param name="pubilcKey"></param>
        /// <returns></returns>
        public static string ToXmlPublicKey(string pubilcKey)
        {
    
    
            RsaKeyParameters p = 
                PublicKeyFactory.CreateKey(Convert.FromBase64String(pubilcKey)) as RsaKeyParameters;
            using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
    
    
                RSAParameters rsaParams = new RSAParameters
                {
    
    
                    Modulus = p.Modulus.ToByteArrayUnsigned(),
                    Exponent = p.Exponent.ToByteArrayUnsigned()
                };
                rsa.ImportParameters(rsaParams);
                return rsa.ToXmlString(false);
            }
        }
    }
}
 

One more dll is needed , e68q

 // 使用
 RSAEncrypt(RSAKeyConverter.ToXmlPublicKey(publicKey_base64),content);

Guess you like

Origin blog.csdn.net/baidu_38392815/article/details/123090485