使用 P12 证书的 Android 签名数据

问题描述:

所以我已经搜索了一段时间,并没有真正找到我需要的东西(因为出现的每个结果都与签署实际包有关).所以基本上我要做的是,WebServices 受会话管理器保护,为了获得会话号,需要将 GUID 发送到 WebService.在 iOS 方面,我们能够获得此设置(因为开发 WebService 的团队有一位 iOS 开发人员可以提供帮助),但由于该团队或这里没有人在 Android 方面有丰富的经验,因此无法试图弄清楚出如何做同样的事情.下面是我到目前为止所尝试过的,但是生成的 GUID 由一些奇怪的字符组成并且不起作用,所以我现在一直在寻找其他选项时被卡住了.

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�ƾ�~��

我发现了问题,代码很好,但是当我将文本转换为字节数组时,我使用了错误的格式 (UTF-8),因为该服务正在使用 (UTF-16LE).只需深入研究该服务即可找到该解决方案.

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.