Recently encountered HMAC_SHA1 cross-language encryption problem, only provided to the Java encryption file, did not provide PHP, I use PHP hmac_sha1 built-in functions, get the SIG encryption results are different, welcome the expert to help provide the corresponding PHP code, provide Java class as follows
Welcome to add qq:847036019
Public abstract class Coder {
public static final String Key_sha = "SHA";
public static final String key_md5 = "MD5";
public static final char hexdigits[] = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ',
' A ', ' B ', ' C ', ' d ', ' e ', ' f '};
public static final String Key_mac = "HmacSHA1";
public static byte[] decryptBASE64 (String key) throws Exception {
Return (new Base64decoder ()). Decodebuffer (key);
}
/**
* Initialize HMAC key
*/
public static String Initmackey () throws Exception {
Keygenerator keygenerator = keygenerator.getinstance (KEY_MAC);
Secretkey Secretkey = Keygenerator.generatekey (); Return encryptBASE64 (secretkey.getencoded ()); }/** * HMAC encryption */public static byte[] Encrypthmac (byte[] data, String key) throws Exception { Secretkey Secretkey = new Secretkeyspec (decryptBASE64 (key), KEY_MAC); Mac Mac = Mac.getinstance (Secretkey.getalgorithm ()); Mac.init (Secretkey); return mac.dofinal (data); } public static void Main (string[] args) {try {String param = '; String Appkey = '; byte[] bytes = Coder.encrypthmac ((param). GetBytes ("Utf-8"), Appkey);//['-115 ', '-101 ', ' 97 ', '-26 ', '-80 ', '-109 ', '-92 ' , ' 6 ', ' -122 ', ' -64 ', ' -17 ', ' -29 ', ' -101 ', ' -53 ', ' + ', ' -93 ', ' -22 ', ' -104 '] String sig = new BigInteger (b ytes). toString ();//-653068794747578802236590292838260814592085857640 System.out.println ("SIG:" + sig); } catch (Exception e) {//TODO Auto-generaTed Catch Block E.printstacktrace (); }}} The Java sig has a result of-653068794747578802236590292838260814592085857640
PHP I use the corresponding encryption that PHP comes with the function
$signature = Mhash (MHASH_SHA1, $sigstr, Base64_decode ($appkey));
$hash = Str_split ($signature);
foreach ($hash as $index = = $value) {
if (Ord ($value) >128) {
$hash [$index] = Ord ($value) -128*2;
} else {
$hash [$index] = ord ($value);
}
}
PHP gets an ASCII array of $array ('-115 ', '-101 ', ' 97 ', '-26 ', '-80 ', '-109 ', '-92 ', ' 33 ', '-6 ', ' 71 ', '-122 ', '-64 ', '-17 ', '- 101 ', '-53 ', ' 88 ', '-93 ', '-22 ', '-104 ');
How does the PHP handle get the following value
-653068794747578802236590292838260814592085857640
Java is using new BigInteger (bytes). toString ();p how HP Handles