java 和 javascript CryptoJS 进行HmacSHA1加密
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; /** * * HmacSHA1加密类 * */ public class SHA1 { public static String getHmacSHA1(String password,String loginname, String algorithm){ byte[] keyBytes = password.getBytes(); Key key = new SecretKeySpec(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(); } return byteArrayToHex(mac.doFinal(loginname.getBytes())); } /** * 16进制加密 * @param a * @return */ protected static String byteArrayToHex(byte [] a) { int hn, ln, cx; String hexDigitChars = "0123456789abcdef"; StringBuffer buf = new StringBuffer(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)); } return buf.toString(); } public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, IOException { String loginKey= getHmacSHA1("密码", "用户名", "HmacSHA1"); System.out.println(loginKey);//53b3a8413cf49e939d8711a0ba34916b2ec2db75 String loginKey2= getHmacSHA1("123456", "admin", "HmacSHA1"); System.out.println(loginKey2);//3c39afa93e0b12c28f1f08b18488ebd4ad2e5858 } }
html+JavaScript代码:
<html> <head> <script src="./hmac-sha1.js"></script> <script type="text/javascript"> function genkey() { var userName=document.getElementById("userName").value; var password=document.getElementById("password").value; var hash = CryptoJS.HmacSHA1(userName, password); document.getElementById("key").value=hash; }; </script> </head> <body> 用户名:<input id="userName" value="" type="text"> 密码:<input id="password" value="" type="text"><br> 40位字符key:<input id="key" value="" type="text" style="width:400px"><br> <input id="genKey" value="生成key" type="button" onclick="genkey()"> </body> </html>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。