如何加载由OpenSSL的生成到的RSACryptoServiceProvider RS​​A公钥?加载、公钥、RSACryptoServiceProvider、OpenSSL

2023-09-05 01:40:54 作者:努力,考试全过!

我写一个.NET类的读取我们的中央认证服务器的cookie。它包含用户标识,一些时间戳和)使用2048位RSA密钥和SHA1哈希通过openssl_sign(创建一个签名。

I am writing a .Net Class that reads a cookie from our central authentication server. It contains the UserId, some timestamps and a signature created by openssl_sign() using a 2048 Bit RSA key and a SHA1 Hash.

目前的公钥OpenSSL中PEM格式提供的服务器和有时会改变。使用.NET托管code单独(还),制定了以下过程来得到它的工作我不能阅读的关键是:

The current public key is provided in openssl PEM format on the server and changes on occasion. I cannot read the Key using .Net managed code alone (yet) and worked out the following procedure to get it working:

提取指数和弹性模量从公开密钥 检查关键还在2048位 存储密钥长度,指数的来源的弹性模量,(从模数滴前导零,使其工作)编译和部署

的类,然后创建一个 新的RSACryptoServiceProvider(2048) 并使用 RSAParameters 结构助长了公众的组件到CSP。签名的验证,然后成功。

The Class then creates a new RSACryptoServiceProvider(2048) and feeds the public components using the RSAParameters structure into the CSP. Verification of the signature then succeeds.

我希望得到这个工作没有我创建,编辑和每次部署新议会的主要变化。为了让事情变得有趣,我想坚持到管理code只有(排除了大部分的例子,我发现)。一些听起来完全是内部ASN.1读者创造的 AsnEn codedData(OID,数据) 但唯一的OID我发现可以匹配,RSA又名1.2.840.113549。 1.1.1,没有工作,只生产原始字节。

I would like to get this working without me creating, compiling and deploying a new Assembly each time the key changes. To make things interesting I would like to stick to managed code only (rules out most examples I found). Something that sounds perfect is the internal ASN.1 Reader when creating an instance of AsnEncodedData(oid, data) but the only oid I found that could match, RSA aka 1.2.840.113549.1.1.1, did not work and produced raw bytes only.

补充:前公共密钥

----- BEGIN公钥-----   MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMW90O6C17fapbS35auKolsy7kI0FOE1   C08y5HqgZ0rMXoocV4nH​​SHYBm2HVx2QSR5OLQtERgWDmxOu + vwU1GXUCAwEAAQ ==   ----- END公钥-----

-----BEGIN PUBLIC KEY----- MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMW90O6C17fapbS35auKolsy7kI0FOE1 C08y5HqgZ0rMXoocV4nHSHYBm2HVx2QSR5OLQtERgWDmxOu+vwU1GXUCAwEAAQ== -----END PUBLIC KEY-----

我发现 pempublic.cs 至极,似乎使用来解决这个(因为它似乎)从OpenSSL的源$ C ​​$ C。我将离开问题打开以查看是否有任何其他的解决方案。

I found pempublic.cs wich seems to solve this using (as it seems) sourcecode from openSSL. I will leave the question open to see if there are any other solutions.

推荐答案

要加载私钥让我们用这个code:

To load private key let's use this code:

private RSACryptoServiceProvider GetPrivateKey(string privateKey)
    {
        byte[] privkey = Convert.FromBase64String(privateKey);
        byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

        // --------- Set up stream to decode the asn.1 encoded RSA private key ------
        MemoryStream mem = new MemoryStream(privkey);
        BinaryReader binr = new BinaryReader(mem);  //wrap Memory Stream with BinaryReader for easy reading
        byte bt = 0;
        ushort twobytes = 0;
        int elems = 0;
        try
        {
            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();
            if (twobytes != 0x0102) //version number
                return null;
            bt = binr.ReadByte();
            if (bt != 0x00)
                return null;


            //------ all private key components are Integer sequences ----
            elems = GetIntegerSize(binr);
            MODULUS = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            E = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            D = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            P = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            Q = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            DP = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            DQ = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            IQ = binr.ReadBytes(elems);

            // ------- create RSACryptoServiceProvider instance and initialize with public key -----
            CspParameters CspParameters = new CspParameters();
            CspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(1024, CspParameters);
            RSAParameters RSAparams = new RSAParameters();
            RSAparams.Modulus = MODULUS;
            RSAparams.Exponent = E;
            RSAparams.D = D;
            RSAparams.P = P;
            RSAparams.Q = Q;
            RSAparams.DP = DP;
            RSAparams.DQ = DQ;
            RSAparams.InverseQ = IQ;
            RSA.ImportParameters(RSAparams);
            return RSA;
        }
        catch (Exception ex)
        {
            return null;
        }
        finally
        {
            binr.Close();
        }
    }

要加载公共密钥让我们用这个code:

To load public key let's use this code:

private RSACryptoServiceProvider GetPublicKey(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  ------
        MemoryStream mem = new MemoryStream(x509key);
        BinaryReader binr = new BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
        byte bt = 0;
        ushort twobytes = 0;

        try
        {

            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 = (int)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;
        }

        finally
        {
            binr.Close();
        }
    }

您可以阅读这里原来的职位,以获得更多的细节。

You can read the original post here to get more detail