I have problems with some HMAC on Android. I am using the SHA1 algorithm with the following code that appears all over the web when searching for android hmac-sha1.
String base_string = "This is a test string"; String key = "testKey"; try { Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec secret = new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm()); mac.init(secret); byte[] digest = mac.doFinal(base_string.getBytes()); String enc = new String(digest);
To test this code, I created a simple standard Java program with it (replacing the Log.v calls with the System.out.println calls, of course), so I can compare them with the android version. In both cases, I use the same test values ββfor base_string and key.
In addition, I checked the encoded results with standard Java with some PHP features and a validation server (using some OAuth tokens). The code works fine in the standard Java program, however it does not work in the Android program. I searched many times and could not understand what was wrong. Has anyone ever experienced this?
Here are the results from standard java and android ...
- Java (and PHP):
fH/+pz0J5XcPZH/d608zGSn7FKA= - Android program:
fH/vv73vv709Ce+/vXcPZH/vv73vv71PMxkp77+9FO+/vQ==
Having looked into it a little more, I am sure that this is an hmac function, not Base64 encoding, where it got confused when comparing these hmac values, the Android version has all kinds of additional spaces and other unknown character characters compared to the Java program.
Any help is appreciated!
source share