在.NET中使用PEM编码的RSA私钥

Dav*_*ita 3 .net c# cryptography rsa private-key

我有一个私钥,看起来像这样:

----- BEGIN RSA 私钥 ----- 一些私钥数据 ----- END RSA PRIVA

我需要在我的C#项目中使用此密钥,但我找不到任何示例如何使用此格式的密钥.谢谢

小智 10

  1. setp 1获取"一些私钥数据"content.remove ----- BEGIN RSA PRIVATE KEY -----和----- END RSA PRIVA,删除所有行符号("\n");
  2. setp 2.解析RSA的密钥.
private RSACryptoServiceProvider CreateRsaProviderFromPrivateKey(string privateKey)
{
    var privateKeyBits = System.Convert.FromBase64String(privateKey);

    var RSA = new RSACryptoServiceProvider();
    var 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;
}
Run Code Online (Sandbox Code Playgroud)