Java HMAC_SHA1 encryption algorithm creationtime--2018 July 14 16:46 Author:marydon1. Prepare for work
ImportJavax.crypto.Mac;ImportJavax.crypto.SecretKey;ImportJavax.crypto.spec.SecretKeySpec;ImportOrg.apache.log4j.Logger;/*** HMAC_SHA1 Encryption Algorithm Tool class * @explain irreversible algorithm *@authorMarydon * @creationTime July 7, 2018 Morning 11:06:58 *@version1.0 *@since* @email*/ Public classHmac_sha1utils {Private StaticLogger log = Logger.getlogger (hmac_sha1utils.class); //Encryption Method Private Static FinalString mac_name = "HmacSHA1"; //Defining character Sets Private Static FinalString ENCODING = "UTF-8";}
2.HMAC_SHA1 encryption
/*** Encryption using the HMAC_SHA1 algorithm * @explain *@paramParamstr * String to encrypt *@paramKey * keys (unlimited in length, can be in Chinese, English, 16 binary strings) *@return16 binary encrypted string with a fixed length of *@throwsException*/ Public Staticstring Encrypt (string paramstr, String key) {//used to store encrypted 16 binary stringsString cipher = ""; Try { // byte[] data =key.getbytes (ENCODING); //constructs a key based on a given byte array, and the second parameter specifies the name of a key algorithm//generate HmacSHA1 Private keySecretkey Secretkey =Newsecretkeyspec (data, mac_name); //generates a Mac object that specifies the MAC algorithmMac Mac =mac.getinstance (mac_name); //Initializes a Mac object with a given keyMac.init (Secretkey); byte[] Text =paramstr.getbytes (ENCODING); //Complete MAC Operation byte[] Encryptbyte =mac.dofinal (text); //will byte[]-->hexstringcipher =Byteutils.tohex (Encryptbyte); } Catch(Exception e) {e.printstacktrace (); Log.error ("HMACSHA1 Encryption failed:" +e.getmessage ()); } log.info ("HMACSHA1 Encryption Result:" +cipher); returncipher;}
3. Check
/*** Determine if the source data is consistent with the encrypted data * @explain *@paramSRCSTR * Original String *@paramSECRETSTR * 16 binary encrypted String *@paramKey * Keys *@returnCheck Results*/ Public Static BooleanVerify (String srcstr, String secretstr, String key) {BooleanFlag =false; String Ciphertext=Encrypt (srcstr, key); if(Ciphertext.equals (SECRETSTR)) flag=true; returnFlag;}
4. Testing
/**@param*/publicstaticvoid Main (String [] args) { = "{\" name\ ": \" marydon\ ", \" website\ ": \" http://www.cnblogs.com/marydon20170307\ "}"; = "Test"; = Hmac_sha1utils.encrypt (JSON, key); SYSTEM.OUT.PRINTLN (cipher); System.out.println (Hmac_sha1utils.verify (JSON, cipher, key));}
Related recommendations:
- Java AES Encryption, decryption
- Java SM3 encryption Algorithm implementation
- Java SM4 Encryption and decryption of State secret algorithm
Java HMAC_SHA1 encryption algorithm