Importjava.io.IOException;Importjava.io.UnsupportedEncodingException;Importjava.security.InvalidKeyException;ImportJava.security.Key;Importjava.security.NoSuchAlgorithmException;ImportJavax.crypto.Mac;ImportJavax.crypto.spec.SecretKeySpec;/*** * HMACSHA1 Encryption class **/ Public classSHA1 { Public Staticstring getHmacSHA1 (String password,string loginname, string algorithm) {byte[] Keybytes =password.getbytes (); Key Key=NewSecretkeyspec (keybytes, 0, keybytes.length, algorithm); Mac Mac=NULL; Try{mac=mac.getinstance (algorithm); Mac.init (key); } Catch(nosuchalgorithmexception e) {e.printstacktrace (); }Catch(InvalidKeyException e) {e.printstacktrace (); } returnBytearraytohex (Mac.dofinal (Loginname.getbytes ())); } /*** 16 Binary encryption *@paramA *@return */ protected StaticString Bytearraytohex (byte[] a) {intHN, LN, CX; String Hexdigitchars= "0123456789abcdef"; StringBuffer buf=NewStringBuffer (A.length * 2); for(cx = 0; cx < a.length; cx++) {HN= ((int) (A[cx]) & 0X00FF)/16 ; ln= ((int) (A[cx]) & 0x000f); Buf.append (Hexdigitchars.charat (HN)); Buf.append (Hexdigitchars.charat (LN)); } returnbuf.tostring (); } Public Static voidMain (string[] args)throwsnosuchalgorithmexception, Unsupportedencodingexception, IOException {String Loginkey= getHmacSHA1 ("password", "username", "HmacSHA1"); System.out.println (Loginkey);//53b3a8413cf49e939d8711a0ba34916b2ec2db75String loginkey2= getHmacSHA1 ("123456", "admin", "HmacSHA1"); System.out.println (LoginKey2);//3c39afa93e0b12c28f1f08b18488ebd4ad2e5858 }}
Html+javascript Code:
<HTML> <Head> <Scriptsrc= "./hmac-sha1.js"></Script> <Scripttype= "Text/javascript"> functionGenkey () {varUserName=document.getElementById ("UserName"). Value; varPassword=document.getElementById ("Password"). Value; varHash=cryptojs.hmacsha1 (userName, password); document.getElementById ("Key"). Value=Hash; }; </Script> </Head> <Body>User name:<inputID= "UserName"value=""type= "text">Password:<inputID= "Password"value=""type= "text"><BR>40-bit character key:<inputID= "Key"value=""type= "text"style= "width:400px"><BR> <inputID= "Genkey"value= "Generate Key"type= "button"onclick= "Genkey ()"> </Body></HTML>
Java and JS, HTML source code download: Link: http://pan.baidu.com/s/1c0pTIes Password: j77s
Java and JavaScript Cryptojs for HmacSHA1 encryption