最近在做银联的一个接口,用到RSA签名,悲剧来了,.net用的RSA密钥格式和JAVA用的不一样
.net为XML格式
<RSAKeyValue><Modulus>53KnujHcV0962zoLigW8d4AUb+1TS3LiySGrXhF5FgjUQhLzI6PCM/hyHPhUat6MTcgWK3kAVInughtNOHXrBI92I1nAdwlMwBPh+F+0UGhQDR5LMaBg7tQq7ebyhy8/QRCtxEO+F0QQYYv0t15RIup+F+08HdWSnTroTBwcEpU=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
JAVA需要PEM文件或DER格式
PEM文件
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCz4PgoQ/2o5cMmFJgcFHLwEl1V
2olZxAEMb7mWfwH36JvORq/maQEE4kYbF2gQN7lQ0C+km0WK6s6ZdzHlhIm/CoK9
YdFCssoTyzj9BDc1RpCtiF1siz/f9vOmGzYKp3bHYHCoEX21XaOuDuVURLuVCWws
HPBpk841ayGwoz4PWQIDAQAB
-----END PUBLIC KEY-----
x50916进制展开
30819f300d06092a864886f70d010101050003818d0030818902818100c166a9a72c74666ed033492d99fa85dffab5230511a3099cd2103a3c89024bcaa8e53b3811fe1588d4827f0621f806c7598fcb4de4624dac420cbbcb84e265589d9fb636a727c7046bcc83ca3bd15980c0ea64246c286b62f55be382b75901f1ee20875018612c69e30e316179460f00cb6f1d965223738c4e58b0da9da4bc4d0203010001
DER16进制展开
30818902818100c166a9a72c74666ed033492d99fa85dffab5230511a3099cd2103a3c89024bcaa8e53b3811fe1588d4827f0621f806c7598fcb4de4624dac420cbbcb84e265589d9fb636a727c7046bcc83ca3bd15980c0ea64246c286b62f55be382b75901f1ee20875018612c69e30e316179460f00cb6f1d965223738c4e58b0da9da4bc4d0203010001
问题来了,它们之间是它喵的啥关系
x509与DER
/**
* 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相互转换
/// <summary>
/// RSA私钥格式转换,java->.net
/// </summary>
/// <param name="privateKeyInfoData">java生成的RSA私钥</param>
/// <returns></returns>
public static string RSAPrivateKeyJava2DotNet(byte[] privateKeyInfoData)
{
RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(privateKeyInfoData); return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
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()));
} /// <summary>
/// RSA私钥格式转换,.net->java
/// </summary>
/// <param name="privateKey">.net生成的私钥</param>
/// <returns></returns>
public static byte[] RSAPrivateKeyDotNet2Java(string privateKey)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(privateKey);
BigInteger m = new BigInteger(, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[].InnerText));
BigInteger exp = new BigInteger(, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[].InnerText));
BigInteger d = new BigInteger(, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[].InnerText));
BigInteger p = new BigInteger(, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[].InnerText));
BigInteger q = new BigInteger(, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[].InnerText));
BigInteger dp = new BigInteger(, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[].InnerText));
BigInteger dq = new BigInteger(, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[].InnerText));
BigInteger qinv = new BigInteger(, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[].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);
} /// <summary>
/// RSA公钥格式转换,java->.net
/// </summary>
/// <param name="keyInfoData">java生成的公钥</param>
/// <returns></returns>
public static string RSAPublicKeyJava2DotNet(byte[] keyInfoData)
{
RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(keyInfoData);
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
} /// <summary>
/// RSA公钥格式转换,.net->java
/// </summary>
/// <param name="publicKey">.net生成的公钥</param>
/// <returns></returns>
public static byte[] RSAPublicKeyDotNet2Java(string publicKey)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(publicKey);
BigInteger m = new BigInteger(, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[].InnerText));
BigInteger p = new BigInteger(, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[].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(, p.Modulus), new BigInteger(, p.Exponent), new BigInteger(, p.D),
new BigInteger(, p.P), new BigInteger(, p.Q), new BigInteger(, p.DP), new BigInteger(, p.DQ),
new BigInteger(, 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(, p.Modulus), new BigInteger(, 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);
}