RSA密钥,JAVA与.NET,IOS之间转换

最近在做银联的一个接口,用到RSA签名,悲剧来了,.net用的RSA密钥格式和JAVA用的不一样

.net为XML格式

1
53KnujHcV0962zoLigW8d4AUb+1TS3LiySGrXhF5FgjUQhLzI6PCM/hyHPhUat6MTcgWK3kAVInughtNOHXrBI92I1nAdwlMwBPh+F+0UGhQDR5LMaBg7tQq7ebyhy8/QRCtxEO+F0QQYYv0t15RIup+F+08HdWSnTroTBwcEpU=AQAB

JAVA需要PEM文件或DER格式

PEM文件

1
2
3
4
5
6
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCz4PgoQ/2o5cMmFJgcFHLwEl1V
2olZxAEMb7mWfwH36JvORq/maQEE4kYbF2gQN7lQ0C+km0WK6s6ZdzHlhIm/CoK9
YdFCssoTyzj9BDc1RpCtiF1siz/f9vOmGzYKp3bHYHCoEX21XaOuDuVURLuVCWws
HPBpk841ayGwoz4PWQIDAQAB
-----END PUBLIC KEY-----

x50916进制展开

1
30819f300d06092a864886f70d010101050003818d0030818902818100c166a9a72c74666ed033492d99fa85dffab5230511a3099cd2103a3c89024bcaa8e53b3811fe1588d4827f0621f806c7598fcb4de4624dac420cbbcb84e265589d9fb636a727c7046bcc83ca3bd15980c0ea64246c286b62f55be382b75901f1ee20875018612c69e30e316179460f00cb6f1d965223738c4e58b0da9da4bc4d0203010001

  

DER16进制展开

30818902818100c166a9a72c74666ed033492d99fa85dffab5230511a3099cd2103a3c89024bcaa8e53b3811fe1588d4827f0621f806c7598fcb4de4624dac420cbbcb84e265589d9fb636a727c7046bcc83ca3bd15980c0ea64246c286b62f55be382b75901f1ee20875018612c69e30e316179460f00cb6f1d965223738c4e58b0da9da4bc4d0203010001

问题来了,它们之间是它喵的啥关系

x509与DER

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
      * x509格式公钥转换为Der格式
      *
      * @param x509PublicKey x509格式公钥字符串
      * @return Der格式公钥字符串
      */
     public  static  String getRsaPublicKeyDerFromX509(String x509PublicKey) {
         try  {
             ASN1InputStream aIn =  new  ASN1InputStream(hexString2ByteArr(x509PublicKey));
             SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());
             RSAPublicKeyStructure  struct  = RSAPublicKeyStructure.getInstance(info.getPublicKey());
             if  (aIn !=  null )
                 aIn.close();
             return  byteArr2HexString( struct .getDERObject().getEncoded());
         catch  (IOException e) {
             return  null ;
         }
     }

x509与PEM

对于公钥,x509=Convert.FromBase64String(PEM中间内容)

私钥就不知道怎么算的

因此JAVA使用格式都是可以用x509进行转换的,剩下的就是如何将.NET的和JAVA的相互转换

格式转换要用到一个开源加密库Bouncy Castle Crypto APIs,官网地址: http://www.bouncycastle.org/csharp/

x509与.NET相互转换

复制代码
/// 
        /// RSA私钥格式转换,java->.net
        /// 
        /// java生成的RSA私钥
        /// 
        public static string RSAPrivateKeyJava2DotNet(byte[] privateKeyInfoData)
        {
            RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(privateKeyInfoData);

            return string.Format("{0}{1}

{2}

{3}{4}{5}{6}{7}
", Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned())); } /// /// RSA私钥格式转换,.net->java /// /// .net生成的私钥 /// public static byte[] RSAPrivateKeyDotNet2Java(string privateKey) { XmlDocument doc = new XmlDocument(); doc.LoadXml(privateKey); BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText)); BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText)); BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText)); BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText)); BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText)); BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText)); BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText)); BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText)); RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam); byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded(); return serializedPrivateBytes; //return Convert.ToBase64String(serializedPrivateBytes); } /// /// RSA公钥格式转换,java->.net /// /// java生成的公钥 /// public static string RSAPublicKeyJava2DotNet(byte[] keyInfoData) { RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(keyInfoData); return string.Format("{0}{1}", Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()), Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned())); } /// /// RSA公钥格式转换,.net->java /// /// .net生成的公钥 /// public static byte[] RSAPublicKeyDotNet2Java(string publicKey) { XmlDocument doc = new XmlDocument(); doc.LoadXml(publicKey); BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText)); BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText)); RsaKeyParameters pub = new RsaKeyParameters(false, m, p); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub); byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded(); return serializedPublicBytes; //return Convert.ToBase64String(serializedPublicBytes); }
复制代码

PEM与.NET相互转换

复制代码
 public static void Xml2PemPrivate(string xml,string saveFile)
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xml);
            var p = rsa.ExportParameters(true);
            var key = new RsaPrivateCrtKeyParameters(
                new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent), new BigInteger(1, p.D),
                new BigInteger(1, p.P), new BigInteger(1, p.Q), new BigInteger(1, p.DP), new BigInteger(1, p.DQ),
                new BigInteger(1, p.InverseQ));
            using (var sw = new StreamWriter(saveFile))
            {
                var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
                pemWriter.WriteObject(key);
            }
        }
        public static string Pem2XmlPrivate(string pemFile)
        {
            AsymmetricCipherKeyPair keyPair;
            using (var sr = new StreamReader(pemFile))
            {
                var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
            }
            var key = (RsaPrivateCrtKeyParameters)keyPair.Private;
            var p = new RSAParameters
            {
                Modulus = key.Modulus.ToByteArrayUnsigned(),
                Exponent = key.PublicExponent.ToByteArrayUnsigned(),
                D = key.Exponent.ToByteArrayUnsigned(),
                P = key.P.ToByteArrayUnsigned(),
                Q = key.Q.ToByteArrayUnsigned(),
                DP = key.DP.ToByteArrayUnsigned(),
                DQ = key.DQ.ToByteArrayUnsigned(),
                InverseQ = key.QInv.ToByteArrayUnsigned(),
            };
            var rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(p);
            return rsa.ToXmlString(true);
        }


        public static string Xml2PemPublic(string xml, string saveFile)
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xml);
            var p = rsa.ExportParameters(false);
            RsaKeyParameters key = new RsaKeyParameters(false, new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent)); 
            using (var sw = new StreamWriter(saveFile))
            {
                var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
                pemWriter.WriteObject(key);
            }
            return System.IO.File.ReadAllText(saveFile);
        }

        public static string Pem2XmlPublic(string pemFileConent)
        {
            pemFileConent = pemFileConent.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\n", "").Replace("\r", "");
            var data = Convert.FromBase64String(pemFileConent);
            return RSAPublicKeyJava2DotNet(data);
        }
复制代码

你可能感兴趣的:(IOS,ASP.NET,MVC)