Java digital signature is different from 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"))); } 

Then I created what I thought was 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 help would be greatly appreciated. Thanks in advance.

EDIT . If I remove MessageDigest from java code, then the output will be the same. What for? I thought that hashing was necessary.

Regards, Eugene

+4
source share
2 answers

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

+2
source

Ok, so I confirmed it. If I remove the MessageDigest / Hashing code from the java example code, the two digital signatures will be the same. I don’t know why, but I’ll try to find out. If someone would like to educate me further, do not be shy.

+2
source

Source: https://habr.com/ru/post/1488442/


All Articles