我有以下 c# 代码从私钥生成数字签名:
static string Sign(string text, string certificate)
{
X509Certificate2 cert = new X509Certificate2(certificate, "TestPassword", X509KeyStorageFlags.Exportable);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
// Hash the data
SHA1Managed sha1 = new SHA1Managed();
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);
// Sign the hash
return System.Convert.ToBase64String(rsa.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")));
}
然后我创建了我认为是等效的 java 代码:
public static String signData(String dataToSign, String keyFile) {
FileInputStream keyfis = null;
try {
keyfis = new FileInputStream(fileName);
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(keyfis, "TestPassword".toCharArray());
KeyStore.PrivateKeyEntry pvk = (KeyStore.PrivateKeyEntry)store.
getEntry("testkey",
new KeyStore.PasswordProtection("TestPassword".toCharArray()));
PrivateKey privateKey = (PrivateKey)pvk.getPrivateKey();
byte[] data = dataToSign.getBytes("US-ASCII");
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] hashed = md.digest(data);
Signature rsa = Signature.getInstance("SHA1withRSA");
rsa.initSign(privateKey);
rsa.update(data);
return Base64.encode(rsa.sign());
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if ( keyfis != null ) {
try { keyfis.close() } catch (Exception ex) { keyfis = null; }
}
}
return null;
}
不幸的是,数字签名不匹配。
任何帮助将不胜感激。提前致谢。
编辑:如果我从 java 代码中删除 MessageDigest,那么输出是相同的。为什么?我认为需要散列。
问候,尤金