I am currently creating a sign hash by encrypting data by public key and then signing it using RSACryptoServiceProvider.SignData method
String data = "some string here";
// **Step 1: encrypt data with public key**
Byte[] encryptedData = publicKeyRsa.Encrypt(System.Text.Encoding.UTF8.GetBytes(data), false);
// **Step 2: sign the encrypted data with private key**
Byte[] sign = privateKeyRsa.SignData(encryptedData, new SHA1CryptoServiceProvider());
// **Step 3: get hash for sign**
String signHash = System.Web.HttpServerUtility.UrlTokenEncode(sign);
I am unable to successfully implement the same algorithm in Java. This is what I currently have
Base64 base64Encoder = new Base64();
// initialize cipher to encrypt
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
// **Step 1: encrypt data with public key**
byte[] encBytes = cipher.doFinal(VALUE.getBytes("UTF-8"));
byte[] encryptedData = base64Encoder.encode(encBytes);
String encryptedDataString = bytes2String(encryptedData);
System.out.println("data encrypted: " + encryptedData);
// **Step 2: sign the encrypted data with private key**
Signature sig = Signature.getInstance("SHA1WithRSA");
sig.initSign(privKey);
sig.update(encryptedData);
byte[] signData = sig.sign();
// **Step 3: get hash for sign**
byte[] signDataEncrypted = base64Encoder.encode(signData);
String signDataString = bytes2String(signDataEncrypted);
System.out.println("hash: "+signDataString);
my implementation of bytes2String is from here
Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher
private static String bytes2String(byte[] bytes) {
StringBuilder string = new StringBuilder();
for (byte b : bytes) {
String hexString = Integer.toHexString(0x00FF & b);
string.append(hexString.length() == 1 ? "0" + hexString : hexString);
}
return string.toString();
}
The C# code works perfectly, but the java code does not provide the "right values" (as per the server). Does the Java code look correct? Is there something I am doing wrong as compared to the C# code?
Thanks