C#之RSA加密解密

 Rsa加密解密-可逆非对称加密

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

namespace Common.Helper.Crypto
{
    /// <summary>
    /// Rsa加密解密-可逆非对称加密(公钥加密算法)
    /// RSA公钥加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美国麻省理工学院)开发的。
    /// 安全性好,性能不如Des
    /// </summary>
    public static class RsaCrypto
    {
        #region 加密解密方式一:加密密钥和解密密钥相同

        //参考:https://www.cnblogs.com/guohu/p/5562759.html

        /// <summary>
        /// 秘钥:加密、解密(秘钥相同,注意保存)
        /// </summary>
        /// <returns></returns>
        private static CspParameters GetCspKey()
        {
            CspParameters param = new CspParameters
            {
                KeyContainerName = "chait"//密匙容器的名称,保持加密解密一致才能解密成功
            };
            return param;
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="palinData">明文</param>
        /// <param name="encodingType">编码方式</param>
        /// <returns>密文</returns>
        public static string Encrypt(string palinData, EncodingStrOrByte.EncodingType encodingType = EncodingStrOrByte.EncodingType.UTF8)
        {
            if (string.IsNullOrWhiteSpace(palinData)) return null;
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(GetCspKey()))
            {
                byte[] bytes = EncodingStrOrByte.GetBytes(palinData, encodingType); //将要加密的字符串转换为指定编码的字节数组
                byte[] encryptData = rsa.Encrypt(bytes, false);//将加密后的字节数据转换为新的加密字节数组
                return Convert.ToBase64String(encryptData);//将加密后的字节数组转换为字符串
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="encryptData">密文</param>
        /// <param name="encodingType">编码方式</param>
        /// <returns>明文</returns>
        public static string Decrypt(string encryptData, EncodingStrOrByte.EncodingType encodingType = EncodingStrOrByte.EncodingType.UTF8)
        {
            if (string.IsNullOrWhiteSpace(encryptData)) return null;
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(GetCspKey()))
            {
                byte[] bytes = Convert.FromBase64String(encryptData);
                byte[] palinData = rsa.Decrypt(bytes, false);
                return EncodingStrOrByte.GetString(palinData, encodingType);
            }
        }
        #endregion

        #region 加密解密方式二:公钥加密/私钥解密

        //参考:https://www.cnblogs.com/dudu/p/dotnet-core-rsa-openssl.html

        #region 公/私密钥
        //openssl genrsa -out rsa_1024_priv.pem 1024
        private static readonly string _privateKey = @"MIICXgIBAAKBgQC0xP5HcfThSQr43bAMoopbzcCyZWE0xfUeTA4Nx4PrXEfDvybJ
EIjbU/rgANAty1yp7g20J7+wVMPCusxftl/d0rPQiCLjeZ3HtlRKld+9htAZtHFZ
osV29h/hNE9JkxzGXstaSeXIUIWquMZQ8XyscIHhqoOmjXaCv58CSRAlAQIDAQAB
AoGBAJtDgCwZYv2FYVk0ABw6F6CWbuZLUVykks69AG0xasti7Xjh3AximUnZLefs
iuJqg2KpRzfv1CM+Cw5cp2GmIVvRqq0GlRZGxJ38AqH9oyUa2m3TojxWapY47zye
PYEjWwRTGlxUBkdujdcYj6/dojNkm4azsDXl9W5YaXiPfbgJAkEA4rlhSPXlohDk
FoyfX0v2OIdaTOcVpinv1jjbSzZ8KZACggjiNUVrSFV3Y4oWom93K5JLXf2mV0Sy
80mPR5jOdwJBAMwciAk8xyQKpMUGNhFX2jKboAYY1SJCfuUnyXHAPWeHp5xCL2UH
tjryJp/Vx8TgsFTGyWSyIE9R8hSup+32rkcCQBe+EAkC7yQ0np4Z5cql+sfarMMm
4+Z9t8b4N0a+EuyLTyfs5Dtt5JkzkggTeuFRyOoALPJP0K6M3CyMBHwb7WsCQQCi
TM2fCsUO06fRQu8bO1A1janhLz3K0DU24jw8RzCMckHE7pvhKhCtLn+n+MWwtzl/
L9JUT4+BgxeLepXtkolhAkEA2V7er7fnEuL0+kKIjmOm5F3kvMIDh9YC1JwLGSvu
1fnzxK34QwSdxgQRF1dfIKJw73lClQpHZfQxL/2XRG8IoA==".Replace("\n", "");

        //openssl rsa -pubout -in rsa_1024_priv.pem -out rsa_1024_pub.pem
        private static readonly string _publicKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0xP5HcfThSQr43bAMoopbzcCy
ZWE0xfUeTA4Nx4PrXEfDvybJEIjbU/rgANAty1yp7g20J7+wVMPCusxftl/d0rPQ
iCLjeZ3HtlRKld+9htAZtHFZosV29h/hNE9JkxzGXstaSeXIUIWquMZQ8XyscIHh
qoOmjXaCv58CSRAlAQIDAQAB".Replace("\n", "");
        #endregion
        /// <summary>
        /// 公钥加密
        /// </summary>
        /// <param name="palinData">明文</param>
        /// <param name="encodingType">编码方式</param>
        /// <returns>string:密文</returns>
        public static string EncryptByPublicKey(string palinData, EncodingStrOrByte.EncodingType encodingType = EncodingStrOrByte.EncodingType.UTF8)
        {
            if (string.IsNullOrWhiteSpace(palinData)) return null;
            RSA rsa = CreateRsaFromPublicKey(_publicKey);
            byte[] palinDataBytes = EncodingStrOrByte.GetBytes(palinData, encodingType);
            byte[] encryptDataBytes = rsa.Encrypt(palinDataBytes, RSAEncryptionPadding.Pkcs1);
            return Convert.ToBase64String(encryptDataBytes);
        }

        /// <summary>
        /// 私钥解密
        /// </summary>
        /// <param name="encryptData">密文</param>
        /// <param name="encodingType">编码方式</param>
        /// <returns>string:明文</returns>
        public static string DecryptByPrivateKey(string encryptData, EncodingStrOrByte.EncodingType encodingType = EncodingStrOrByte.EncodingType.UTF8)
        {
            if (string.IsNullOrWhiteSpace(encryptData)) return null;
            RSA rsa = CreateRsaFromPrivateKey(_privateKey);
            byte[] encryptDataBytes = Convert.FromBase64String(encryptData);
            byte[] palinDataBytes = rsa.Decrypt(encryptDataBytes, RSAEncryptionPadding.Pkcs1);
            return EncodingStrOrByte.GetString(palinDataBytes, encodingType);
        }

        /// <summary>
        /// 创建私钥
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        private static RSA CreateRsaFromPrivateKey(string privateKey)
        {
            var privateKeyBits = Convert.FromBase64String(privateKey);
            var rsa = RSA.Create();
            var RSAparams = new RSAParameters();

            using (var binr = new BinaryReader(new MemoryStream(privateKeyBits)))
            {
                byte bt = 0;
                ushort twobytes = 0;
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)
                    binr.ReadByte();
                else if (twobytes == 0x8230)
                    binr.ReadInt16();
                else
                    throw new Exception("Unexpected value read binr.ReadUInt16()");

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102)
                    throw new Exception("Unexpected version");

                bt = binr.ReadByte();
                if (bt != 0x00)
                    throw new Exception("Unexpected value read binr.ReadByte()");

                RSAparams.Modulus = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.Exponent = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.D = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.P = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.Q = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.DP = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.DQ = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
            }
            rsa.ImportParameters(RSAparams);
            return rsa;
        }

        private static int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            byte lowbyte = 0x00;
            byte highbyte = 0x00;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02)
            { return count; }                
            bt = binr.ReadByte();
            if (bt == 0x81)
            { count = binr.ReadByte();}
            else if (bt == 0x82)
            {
                highbyte = binr.ReadByte();
                lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else{ count = bt; }
            while (binr.ReadByte() == 0x00)
            {
                count -= 1;
            }
            binr.BaseStream.Seek(-1, SeekOrigin.Current);
            return count;
        }

        /// <summary>
        /// 创建公钥
        /// </summary>
        /// <param name="publicKeyString"></param>
        /// <returns></returns>
        private static RSA CreateRsaFromPublicKey(string publicKeyString)
        {
            byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] x509key;
            byte[] seq = new byte[15];
            int x509size;

            x509key = Convert.FromBase64String(publicKeyString);
            x509size = x509key.Length;

            using (var mem = new MemoryStream(x509key))
            {
                using (var binr = new BinaryReader(mem))
                {
                    byte bt = 0;
                    ushort twobytes = 0;
                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130)
                        binr.ReadByte();
                    else if (twobytes == 0x8230)
                        binr.ReadInt16();
                    else
                        return null;
                    seq = binr.ReadBytes(15);
                    if (!CompareBytearrays(seq, SeqOID))
                        return null;
                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8103)
                        binr.ReadByte();
                    else if (twobytes == 0x8203)
                        binr.ReadInt16();
                    else
                        return null;
                    bt = binr.ReadByte();
                    if (bt != 0x00)
                        return null;
                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130)
                        binr.ReadByte();
                    else if (twobytes == 0x8230)
                        binr.ReadInt16();
                    else
                        return null;
                    twobytes = binr.ReadUInt16();
                    byte lowbyte = 0x00;
                    byte highbyte = 0x00;
                    if (twobytes == 0x8102)
                        lowbyte = binr.ReadByte();
                    else if (twobytes == 0x8202)
                    {
                        highbyte = binr.ReadByte();
                        lowbyte = binr.ReadByte();
                    }
                    else
                        return null;
                    byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                    int modsize = BitConverter.ToInt32(modint, 0);
                    int firstbyte = binr.PeekChar();
                    if (firstbyte == 0x00)
                    {
                        binr.ReadByte();
                        modsize -= 1;
                    }
                    byte[] modulus = binr.ReadBytes(modsize);
                    if (binr.ReadByte() != 0x02)
                        return null;
                    int expbytes = (int)binr.ReadByte();
                    byte[] exponent = binr.ReadBytes(expbytes);
                    var rsa = RSA.Create();
                    var rsaKeyInfo = new RSAParameters
                    {
                        Modulus = modulus,
                        Exponent = exponent
                    };
                    rsa.ImportParameters(rsaKeyInfo);
                    return rsa;
                }
            }
        }

        private static bool CompareBytearrays(byte[] a, byte[] b)
        {
            if (a.Length != b.Length)
                return false;
            int i = 0;
            foreach (byte c in a)
            {
                if (c != b[i])
                    return false;
                i++;
            }
            return true;
        }
        #endregion
    }
}

编码处理类:

using System.Text;

namespace Common.Helper
{
    /// <summary>
    /// 处理编码字符串或字符串
    /// </summary>
    public static class EncodingStrOrByte
    {
        /// <summary>
        /// 编码方式
        /// </summary>
        public enum EncodingType { UTF7, UTF8, UTF32, Unicode, BigEndianUnicode, ASCII, GB2312 };
        /// <summary>
        /// 处理指定编码的字符串,转换字节数组
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encodingType"></param>
        /// <returns></returns>
        public static byte[] GetByte(string str, EncodingType encodingType)
        {
            byte[] bytes = null;
            switch (encodingType)
            {
                //将要加密的字符串转换为指定编码的字节数组
                case EncodingType.UTF7:
                    bytes = Encoding.UTF7.GetBytes(str);
                    break;
                case EncodingType.UTF8:
                    bytes = Encoding.UTF8.GetBytes(str);
                    break;
                case EncodingType.UTF32:
                    bytes = Encoding.UTF32.GetBytes(str);
                    break;
                case EncodingType.Unicode:
                    bytes = Encoding.Unicode.GetBytes(str);
                    break;
                case EncodingType.BigEndianUnicode:
                    bytes = Encoding.BigEndianUnicode.GetBytes(str);
                    break;
                case EncodingType.ASCII:
                    bytes = Encoding.ASCII.GetBytes(str);
                    break;
                case EncodingType.GB2312:
                    bytes = Encoding.Default.GetBytes(str);
                    break;
            }
            return bytes;
        }

        /// <summary>
        /// 处理指定编码的字节数组,转换字符串
        /// </summary>
        /// <param name="myByte"></param>
        /// <param name="encodingType"></param>
        /// <returns></returns>
        public static string GetString(byte[] myByte, EncodingType encodingType)
        {
            string str = null;
            switch (encodingType)
            {
                //将要加密的字符串转换为指定编码的字节数组
                case EncodingType.UTF7:
                    str = Encoding.UTF7.GetString(myByte);
                    break;
                case EncodingType.UTF8:
                    str = Encoding.UTF8.GetString(myByte);
                    break;
                case EncodingType.UTF32:
                    str = Encoding.UTF32.GetString(myByte);
                    break;
                case EncodingType.Unicode:
                    str = Encoding.Unicode.GetString(myByte);
                    break;
                case EncodingType.BigEndianUnicode:
                    str = Encoding.BigEndianUnicode.GetString(myByte);
                    break;
                case EncodingType.ASCII:
                    str = Encoding.ASCII.GetString(myByte);
                    break;
                case EncodingType.GB2312:
                    str = Encoding.Default.GetString(myByte);
                    break;
            }
            return str;
        }
    }
}

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: RSA是一种非对称加密算法,通过利用大质数的特性,可以实现可靠的加密和解密过程。 RSA加密过程中,首先需要生成一对密钥,即公钥和私钥。公钥用于加密数据,私钥用于解密数据。 具体加密过程如下: 1. 选取两个不同的质数p和q,并计算它们的乘积n。 2. 计算n的欧拉函数φ(n),即φ(n) = (p-1)(q-1)。 3. 选取一个int型的整数e,使得1<e<φ(n),且e与φ(n)互质。 4. 计算e关于φ(n)的乘法逆元d,即d·e=1(mod φ(n))。 5. 公钥为(n, e),私钥为(n, d)。 6. 将明文数据转化为对应的十进制数m。 7. 加密过程为:c ≡ m^e(mod n)。 8. 得到密文c。 RSA解密过程如下: 1. 将密文c代入解密公式:m ≡ c^d(modn),得到明文m。 相比于其他加密算法,RSA具有加密效率低的特点,但是由于非对称加密的特性,它可以更好地保证数据的安全性。在JS中,通过使用各种开源的加密库,可以方便地实现RSA加密和解密的功能。 总结来说,JS加密RSA C是指通过使用JavaScript实现RSA加密算法,实现数据加密和解密的过程,保证数据的机密性和安全性。 ### 回答2: RSA是一种非对称加密算法,可以用于保护数据的安全性。在使用JavaScript进行RSA加密时,需要使用RSA加密算法的相关库或插件以实现相关功能。 在JavaScript中,我们可以使用如crypto-js或jsencrypt等库来进行RSA加密。这些库提供了一系列方法来生成RSA密钥对、加密和解密数据。 首先,我们需要生成RSA密钥对。可以使用库提供的方法来生成公钥和私钥。公钥用于加密数据,私钥用于解密数据。 使用RSA加密数据的过程如下:首先,将需要加密的数据通过公钥进行加密操作。加密后的数据可以通过网络传输或在本地存储。在接收方获取到加密数据后,可以使用私钥对其进行解密操作,以获取原始数据。 在使用RSA加密数据时,需要保证私钥的安全性,以免私钥被他人获取而导致数据泄露。因此,使用RSA加密时需要合理管理密钥,以保障数据的安全性。 总而言之,使用JavaScript进行RSA加密需要使用相关的库或插件,生成RSA密钥对并通过公钥加密数据,再通过私钥解密数据。加密数据的安全性取决于私钥的保护程度。 ### 回答3: RSA加密是一种非对称加密算法,用于保护数据的安全性和隐私性。在JavaScript中,我们可以使用一些库来实现RSA加密算法。 首先,我们需要准备一对RSA密钥,包括公钥和私钥。通常情况下,公钥用于加密数据,而私钥用于解密数据。可以通过一些在线工具或者自己生成密钥对。 接下来,我们需要引入一个JSRSA库,如"jsencrypt"来实现RSA加密。可以通过在HTML文档中引入该库的JavaScript文件或者使用npm进行安装。 接下来,我们可以在JavaScript代码中通过以下步骤来实现RSA加密: 1. 创建一个RSA实例,并传入公钥。 2. 调用实例的encrypt方法,传入要加密的数据作为参数。 3. 得到加密后的数据,可以通过调用实例的getEncryptedString方法来获取加密后的字符串。 下面是一个简单的示例代码: ```javascript // 引入jsencrypt库 const JSEncrypt = require('jsencrypt'); // 创建RSA实例 const rsa = new JSEncrypt(); // 设置公钥 rsa.setPublicKey(publicKey); // 要加密的数据 const data = 'Hello, RSA!'; // 加密数据 const encryptedData = rsa.encrypt(data); // 输出加密后的数据 console.log(encryptedData); ``` 以上示例中,我们通过传入公钥给RSA实例,并使用encrypt方法对数据进行加密,最后输出加密后的数据。 需要注意的是,RSA加密算法是一种非常安全和复杂的算法,仅仅使用以上代码可能还不够保证数据的安全性。在真实的场景中,还需要考虑密钥的生成和管理,以及数据的完整性和验证等方面的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ChaITSimpleLove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值