rsa加密解密

因为等保的原因,要改造登录窗口,submit用户名跟密码的时候不能明文传输。那行吧,就考虑一下将用户名跟密码加密传输。

到网上找了一下资料,发现流行的是RSA客户端跟服务端加密解密传输。

废话不多说,直接上资源

首先是客户端的

资源传送门,赚点积分 

还有C#版本的

    /// <summary>
    /// 参数加密帮助类
    /// </summary>
    internal class JsEncryptHelper
    {
        private const string defaultprivateKey = @"MIICXAIBAAKBgQCLjsieLWHvl1VbAKUaxwKhXIqCrahTjPIw5hprptRd4cbMnyCO
AYL1sX4S21DsiSwgwzDybCoskU2xMOvESNxtUcvPnxnlnRkh/2p72dbrhszDT2xx
WmsidUokLujM50R8Bgx/6zBTa3+oNON3kcywhSdkIl+z28fC01WAHC+MkQIDAQAB
AoGBAImV/B1Nuqb9+I2eRifvGZ3B4WBSGog8ha1FvbhyIh5ob5jeLLczsEvPb+7h
P5fi6JloNkJZ9v43RnQxOc8q0fyUAgyU0wBXoDpNHBGlebPIc67YItHqn472zlvw
FX+wm8y/v1va0iDB8NghiSDR74mJjBk1qk7PX2F2mk0tmJEdAkEAwYrqA/MELQ0p
gS2OndjXx7VqDzooRtCkyeaZDpPtl8NednBxPeiRnhfFYftNevzzIi5oJRoNyWEq
eGUEx7AIEwJBALiYB9sIHRoAfxtMDiRaT8HFkXV5H/yxO0AIT7xK97+zBIOPaWHY
NCaCPPg/1YIiKr8I/xa1CRFr3ZAFhI7x9UsCQH9QiSY1605TdTUDqehN54v4257O
rAYBZBVoetCrIMUPgIk66FNINNohWvdcX5iC4tFeY6XcYKtTHqP6F83gDz8CQFmW
t6FPM8iN2yKla+uqxTC3MVyBN8wNPENchU5OWCV6vcMYFD4/jzftV6foWzg4WuSy
ehNMM6V342VluCskNTcCQBzoCwgFRX9lQe9h13rYP5Ash777RBC4cxyReeznYBDD
8d9GwnaUnkCmnIB9MdJdjnPNRiOh0xAFgcqJ5TzaZ7k=";

        private const string defaultpublicKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLjsieLWHvl1VbAKUaxwKhXIqC
rahTjPIw5hprptRd4cbMnyCOAYL1sX4S21DsiSwgwzDybCoskU2xMOvESNxtUcvP
nxnlnRkh/2p72dbrhszDT2xxWmsidUokLujM50R8Bgx/6zBTa3+oNON3kcywhSdk
Il+z28fC01WAHC+MkQIDAQAB";

        private readonly RSACryptoServiceProvider _privateKeyRsaProvider;
        private readonly RSACryptoServiceProvider _publicKeyRsaProvider;

        public JsEncryptHelper(string privateKey = null, string publicKey = null)
        {
            if (string.IsNullOrEmpty(privateKey))
            {
                privateKey = defaultprivateKey;
            }
            if (string.IsNullOrEmpty(publicKey))
            {
                publicKey = defaultpublicKey;
            }

            if (!string.IsNullOrEmpty(privateKey))
            {
                _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
            }

            if (!string.IsNullOrEmpty(publicKey))
            {
                _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
            }
        }

        public string Decrypt(string cipherText)
        {
            if (_privateKeyRsaProvider == null)
            {
                throw new Exception("_privateKeyRsaProvider is null");
            }

            byte[] asdfasdf = Convert.FromBase64String(cipherText);

            return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), false));
        }

        public string Encrypt(string text)
        {
            if (_publicKeyRsaProvider == null)
            {
                throw new Exception("_publicKeyRsaProvider is null");
            }

            return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), false));
        }

        private RSACryptoServiceProvider CreateRsaProviderFromPrivateKey(string privateKey)
        {
            byte[] privateKeyBits = Convert.FromBase64String(privateKey);

            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSAParameters RSAparams = new RSAParameters();

            using (BinaryReader 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 int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            byte lowbyte = 0x00;
            byte highbyte = 0x00;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02)
            {
                return 0;
            }

            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;
        }

        private RSACryptoServiceProvider CreateRsaProviderFromPublicKey(string publicKeyString)
        {
            // encoded OID sequence for  PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
            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;

            // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
            using (MemoryStream mem = new MemoryStream(x509key))
            {
                using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading
                {
                    byte bt = 0;
                    ushort twobytes = 0;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                    {
                        binr.ReadByte(); //advance 1 byte
                    }
                    else if (twobytes == 0x8230)
                    {
                        binr.ReadInt16(); //advance 2 bytes
                    }
                    else
                    {
                        return null;
                    }

                    seq = binr.ReadBytes(15); //read the Sequence OID
                    if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct
                    {
                        return null;
                    }

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
                    {
                        binr.ReadByte(); //advance 1 byte
                    }
                    else if (twobytes == 0x8203)
                    {
                        binr.ReadInt16(); //advance 2 bytes
                    }
                    else
                    {
                        return null;
                    }

                    bt = binr.ReadByte();
                    if (bt != 0x00) //expect null byte next
                    {
                        return null;
                    }

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                    {
                        binr.ReadByte(); //advance 1 byte
                    }
                    else if (twobytes == 0x8230)
                    {
                        binr.ReadInt16(); //advance 2 bytes
                    }
                    else
                    {
                        return null;
                    }

                    twobytes = binr.ReadUInt16();
                    byte lowbyte = 0x00;
                    byte highbyte = 0x00;

                    if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
                    {
                        lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
                    }
                    else if (twobytes == 0x8202)
                    {
                        highbyte = binr.ReadByte(); //advance 2 bytes
                        lowbyte = binr.ReadByte();
                    }
                    else
                    {
                        return null;
                    }

                    byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
                    int modsize = BitConverter.ToInt32(modint, 0);

                    int firstbyte = binr.PeekChar();
                    if (firstbyte == 0x00)
                    {
                        //if first byte (highest order) of modulus is zero, don't include it
                        binr.ReadByte(); //skip this null byte
                        modsize -= 1; //reduce modulus buffer size by 1
                    }

                    byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes

                    if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data
                    {
                        return null;
                    }

                    int expbytes = binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
                    byte[] exponent = binr.ReadBytes(expbytes);

                    // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                    RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                    RSAParameters RSAKeyInfo = new RSAParameters();
                    RSAKeyInfo.Modulus = modulus;
                    RSAKeyInfo.Exponent = exponent;
                    RSA.ImportParameters(RSAKeyInfo);

                    return RSA;
                }
            }
        }

        private 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;
        }
    }
View Code

记住要引用

using System.Security.Cryptography;

使用方法如下:

        {
            JsEncryptHelper newRSA = new JsEncryptHelper();

            var test1 = newRSA.Encrypt("123456789");

            var rsa = "eLlvV/vstngYl9EOsp8ZPP6mGqcLcB+JtsYXfnSTebOdeTz23NuW8hbJEYmMnhLKocH5wdyPqC5BfHSLA3sv5LEZl5UeUNTuS2mbUvuTDaTjeYwUWFQEFHyzFnJeo2lINVjKeiYA0wVOd2J9JNCLYaZpbPceyWCV4sL2RF9W/F4=";

            var test2 = newRSA.Decrypt(rsa);

            return;
        }

 

posted @ 2024-09-13 16:16  poisson_notes  阅读(7)  评论(0编辑  收藏  举报