我在与我们的第三方供应商实施 sso 时遇到问题。他们在验证我的签名时收到以下错误:
java.lang.ArithmeticException: BigInteger: 模数不是正数——在 java.math.BigInteger.modPow(BigInteger.java:1556)
我无法控制他们的 Java 代码。这是我现在正在做的事情:
我使用以下代码在 C# 中创建了一个密钥对:
CspParameters csp = new CspParameters();
csp.KeyNumber = (int)KeyNumber.Signature;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024, csp))
{
File.AppendAllText(path + "PrivateKey.xml", rsa.ToXmlString(true));
File.AppendAllText(path + "PublicKey.xml", rsa.ToXmlString(false));
}
这是签名的代码:
public string MD5withRSASignature(string encryptedStringToSign)
{
byte[] signature;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024))
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(PRIVATE_KEY_PATH);
rsa.FromXmlString(xDoc.OuterXml);
byte[] bytes = Encoding.UTF8.GetBytes(encryptedStringToSign);
signature = rsa.SignData(bytes, new MD5CryptoServiceProvider());
}
return Convert.ToBase64String(signature);
}
(是的,我知道私钥应该在密钥库中)。
这是他们用来转换 xml 键的代码(这是 Java)
private static RSAPublicKey ReadXMLKey(String fileName)
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse( new File(fileName) );
byte[] modBytes = GetBytesFromElement(document, "Modulus");
byte[] expBytes = GetBytesFromElement(document, "Exponent");
RSAPublicKeySpec rsaKeyspec = new RSAPublicKeySpec(new BigInteger(modBytes), new BigInteger(expBytes));
RSAPublicKey key = (RSAPublicKey)KeyFactory.getInstance("RSA").generatePublic(rsaKeyspec);
return key;
}
private static byte[] GetBytesFromElement(Document doc, String tag) throws IOException
{
BASE64Decoder decoder = new BASE64Decoder();
NodeList list = doc.getElementsByTagName(tag);
byte[] results = null;
if (list.getLength() == 1)
{
Element item = (Element)list.item(0);
Text text = (Text)item.getFirstChild();
results = decoder.decodeBuffer(text.getNodeValue().trim());
}
return results;
}