Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signing a string using a private key, RSA-SHA1 signature and than md5 it in Android

i need to sign a string using RSA-SHA1 signature and a private key from .PFX certificate. Here's my code:

String rawString = "1234567890";

byte[] signed = null;

FileInputStream cert = new FileInputStream("/sdcard/cert.pfx");

KeyStore keyStore = KeyStore.getInstance("pkcs12");
keyStore.load(cert, "cert_password".toCharArray());

String alias = keyStore.aliases().nextElement();
PrivateKey privateKey = (PrivateKey)keyStore.getKey(alias, "cert_password".toCharArray());

Signature instance = Signature.getInstance("SHA1withRSA");
instance.initSign((PrivateKey)privateKey);
instance.update(rawString.getBytes());
signed = instance.sign();

TextView mTextView = (TextView) findViewById(R.id.signed_message);
mTextView.setText(md5(bytes2String(signed)));

and i do get a nice looking MD5, but, i am doing the same thing in PHP also and the result i get with PHP is different than the one in Android. I know the PHP one is correct... so what's wrong with the Android version?

I've noticed that the Android result differs if i use new String(signed) instead of bytes2String(signed) or even if i use signed.toString()

i use this for MD5: https://stackoverflow.com/a/4846511/1176497

and bytes2String from (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();
}
like image 876
Draško Avatar asked Jun 10 '13 13:06

Draško


1 Answers

I've figured it out....

the md5 function I'm using requires a string, but coverts it to byte[]... since i already have byte[] there's no need to covert it!

now i get the same result as in PHP :)

like image 186
Draško Avatar answered Oct 05 '22 11:10

Draško