1

So I am not the Crypto wizard by any means but here is some code I have that works in C# but does not return the same b64 string in Java.
c#


 string _Cert = "long b64 string here"; string _Pass = "my password"; string lvreturn = "Test"; byte[] lvCertBytes = Convert.FromBase64String(_Cert); X509Certificate2 lvCertFromBytes = new X509Certificate2(lvCertBytes, _Pass); SHA1Managed lvSHA1 = new SHA1Managed(); byte[] lvData = Encoding.Unicode.GetBytes(lvReturn); byte[] lvHash = lvSHA1.ComputeHash(lvData); RSACryptoServiceProvider lvCryptoProvider = (RSACryptoServiceProvider)lvCertFromBytes.PrivateKey; byte[] lvSignedBytes = lvCryptoProvider.SignHash(lvHash, CryptoConfig.MapNameToOID("SHA1")); string lvToken = Convert.ToBase64String(lvSignedBytes); 

Java


String certB64 = "long b64 string here"; char[] Pass = "text password".toCharArray(); String alias = "guid looking ID here"; String plaintext = "Test"; byte[] certbytes = Base64.getDecoder().decode(certB64); InputStream in = new ByteArrayInputStream(certbytes); KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(in,Pass); KeyStore.PrivateKeyEntry pvk = (KeyStore.PrivateKeyEntry)keystore.getEntry(alias, new KeyStore.PasswordProtection(Pass)); PrivateKey pkey = (PrivateKey)pvk.getPrivateKey(); Signature rsa = Signature.getInstance("SHA1withRSA"); rsa.initSign(pkey); rsa.update(plaintext.getBytes()); System.out.println("Hash: " + Base64.getEncoder().encodeToString(rsa.sign())); 

I have Cert.pfx file that I want to use to use the privatekey to encrypt a https auth segment. I am just ripping the file to a base64 string and stuffing it into the "_Cert" var in C#. I do the same in Java. I want to sign the plaintext message using the private key of the cert and SHA1. The C# code below works and the https server provides a response. Java however is not spitting out the same base64 encoded string. Thanks for some help!

Update: I found a link to another post that is the same as mine but with a couple small diffs, and I didn't want to necro post on it. I followed it exactly removing the messagedigest piece of my original code. I tried reading directly from the pfx file or using the b64 string directly in the code. I am still not getting the same between Java and C#. At this point it has to be something small I am missing with encoding in Java because the C# is basically identical to mine.

Java Digital Signature different to C#

1
  • Finally figured it out. I don't know why but apparently Encoding.Unicode.GetBytes in C# equals plaintext.getBytes("UTF-16LE") in Java. Maybe someone that understands encoding and "endianness" could explain. I thought Java was natively unicode, and endianness only mattered if you went between processor types. Commented Feb 23, 2017 at 23:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.