Using Java to implement HASH_HMAC functions in PHP

Source: Internet
Author: User
Package com.trade.com796;
Import java.security.InvalidKeyException;
Import java.security.NoSuchAlgorithmException;
Import Javax.crypto.Mac;

Import Javax.crypto.spec.SecretKeySpec; /** * 1. HMAC_SHA1 encoding results need to be converted into hex format * * 2. The implementation of Base64 in Java is inconsistent with PHP, where Java does not fill the = number at the end of the string to supplement the number of bytes by 8 of the integer * * 3. HMAC_SHA1 is not SHA1, HMAC_SHA1 is a * * @author LEI * * */public class HMACSHA1 {private static final String hmac_s that requires a shared secret key

	HA1 = "HmacSHA1"; /** * Generate signature Data _HMACSHA1 encryption * @param data * @param key * encrypted using key * @throws in Validkeyexception * @throws nosuchalgorithmexception */public static string Getsignature (string data, string key) th
		Rows Exception {byte[] keybytes = Key.getbytes ();
		Constructs a key based on the given byte array.
		Secretkeyspec Signingkey = new Secretkeyspec (keybytes, HMAC_SHA1);
		Mac Mac = Mac.getinstance (HMAC_SHA1);

		Mac.init (Signingkey);

		byte[] Rawhmac = mac.dofinal (Data.getbytes ());
		String hexbytes = Byte2hex (RAWHMAC);
	return hexbytes; } pRivate static string Byte2hex (final byte[] b) {String HS = "";
		String stmp = "";
			for (int n = 0; n < b.length; n++) {//returns the string representation of an integer parameter as a 16-ary (base 16) unsigned integer.
			Stmp = (java.lang.Integer.toHexString (b[n] & 0xFF));
			if (stmp.length () = = 1) {HS = HS + "0" + stmp;
			else {HS = hs + stmp;
	} return HS; ////**//* @param args////public static void main (string[] args) {//try {//System.out.println (HMACSHA1
	. Getsignature ("abc", "abc"));
	catch (Exception e) {//E.printstacktrace ();
 // }
	// }

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.