BouncyCastle RSAPrivateKey to .NET RSAPrivateKey

前端 未结 5 618
我在风中等你
我在风中等你 2020-12-07 23:27

I\'m creating a certificate distribution system to keep track of clients and stuff.

What happens is:

  • Client send CSR to Server
  • Server checks a
5条回答
  •  忘掉有多难
    2020-12-07 23:52

    The answer (from username) points to the right direction: padding.

    Bouncy-castle's latest version from git has the following code:

    public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey)
    {
       RSAParameters rp = new RSAParameters();
       rp.Modulus = privKey.Modulus.ToByteArrayUnsigned();
       rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned();
       rp.P = privKey.P.ToByteArrayUnsigned();
       rp.Q = privKey.Q.ToByteArrayUnsigned();
       rp.D = ConvertRSAParametersField(privKey.Exponent, rp.Modulus.Length);
       rp.DP = ConvertRSAParametersField(privKey.DP, rp.P.Length);
       rp.DQ = ConvertRSAParametersField(privKey.DQ, rp.Q.Length);
       rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length);
       return rp;
    }
    
    private static byte[] ConvertRSAParametersField(BigInteger n, int size)
    {
       byte[] bs = n.ToByteArrayUnsigned();
       if (bs.Length == size)
          return bs;
       if (bs.Length > size)
          throw new ArgumentException("Specified size too small", "size");
       byte[] padded = new byte[size];
       Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
       return padded;
    }
    

    nb: This code in not in the nuget version (2011) of bouncy castle, or in most code samples were RSA parameters are simply copied.

    This code is different from the code you can see anywhere else which basically copy/paste the key parameters, and does not perform the extra padding step.

提交回复
热议问题