简体   繁体   English

Java数字签名与C#不同

[英]Java Digital Signature different to C#

I have the following c# code to generate a digital signature from a private key: 我有以下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")));            
    }

I then created what I thought was the equivalent java code: 然后我创建了我认为是等效的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;
}

Unfortunately the digital signatures do not match. 不幸的是,数字签名不匹配。

Any assistance will be greatly appreciated. 任何帮助将不胜感激。 Thanks in advance. 提前致谢。

EDIT : If I remove the MessageDigest from the java code then the output is the same. 编辑 :如果我从java代码中删除MessageDigest,那么输出是相同的。 Why? 为什么? I thought hashing is needed. 我认为需要哈希。

Regards, Eugene 此致,尤金

Ok so I have confirmed it. 好的,我已经确认了。 If I remove the MessageDigest/Hashing code from the java sample code then the two digital signatures are the same. 如果我从java示例代码中删除MessageDigest / Hashing代码,那么两个数字签名是相同的。 Not sure why, but I'll try and find out. 不知道为什么,但我会试着找出来。 If anyone would like to educate me further feel free. 如果有人想教育我进一步感到自由。

Java符号方法基于Signature类的getInstance方法中提供的算法进行散列和签名,因此基本上您在Java中进行了两次哈希处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM