Java数字签名与C#

Java数字签名与C#

本文介绍了Java数字签名与C#不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有以下c#代码从私钥生成数字签名:

I have the following c# code to generate a digital signature from a private key:

    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代码的东西:

I then created what I thought was the equivalent java code:

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;
}

不幸的是,数字签名不匹配。

Unfortunately the digital signatures do not match.

任何帮助将不胜感激。
提前致谢。

Any assistance will be greatly appreciated.Thanks in advance.

编辑:如果我从java代码中删除MessageDigest,那么输出是相同的。为什么?我认为需要哈希。

EDIT: If I remove the MessageDigest from the java code then the output is the same. Why? I thought hashing is needed.

问候,
Eugene

Regards,Eugene

推荐答案

Java符号方法根据Signature类的getInstance方法提供的算法进行散列和签名,所以基本上你在Java中进行了两次哈希。

The Java sign method does hashing and signing based on the algorithms provided in getInstance method of the Signature class, so basically you were hashing twice in Java.

这篇关于Java数字签名与C#不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:03