Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Sign Data with P12 Certificate

So I've searched around for a while and couldn't really find what I needed (since every result that comes up is in regards to signing the actual package). So basically what I have going on is that the WebServices are protected with a Session Manager and in order to get a session number a GUID needs to be sent to the WebService. On the iOS side we were able to get this setup (since the team that did the development of the WebService had a iOS developer there to help) but since no one on that team or here has much experience with Android were struggling on trying to figure out how to do the same thing. Below is what I've tried so far, but the GUID that is produced is composed of some strange characters and doesn't work, so I'm stuck for now while I keep looking for other options.

        String password = "password";
        String text = "545048";
        KeyStore keyStore = KeyStore.getInstance("pkcs12");
        InputStream inputStream = activity.getResources().openRawResource(R.raw.am_client);
        keyStore.load(inputStream, password.toCharArray());

        String alias = keyStore.aliases().nextElement();
        PrivateKey privateKey = (PrivateKey)keyStore.getKey(alias, password.toCharArray());
        X509Certificate certificate = (X509Certificate)keyStore.getCertificate(alias);

        //Sign Data
        byte[] dataToSign = text.getBytes("UTF-8");
        Signature signature1 = Signature.getInstance("SHA1WithRSA");
        signature1.initSign(privateKey);
        signature1.update(dataToSign);
        byte[] signedData = signature1.sign();
        String signed = new String(signedData, "UTF-8");
        Log.d("MESSAGE", "string = " + signed);
        //This is what comes up in the Log: ��m(N� �xp�r���K�V>G3b���M��W08���6#�͞�+�/�]�,�o���N"�$��uVa�ƾ�~��
like image 441
Sal Aldana Avatar asked Dec 01 '25 03:12

Sal Aldana


1 Answers

I figured out the problem, the code was fine but when I was converting the text to a byte array I was using the wrong format (UTF-8) since the service was using (UTF-16LE). Just had to dig into the service to find that solution.

like image 127
Sal Aldana Avatar answered Dec 02 '25 19:12

Sal Aldana