java加密算法--MD5加密和哈希散列带秘钥加密算法源码
程序员文章站
2024-03-09 15:51:17
java加密算法--md5加密和哈希散列带秘钥加密算法源码
&...
java加密算法--md5加密和哈希散列带秘钥加密算法源码
最近学习加密算法的知识,利用md5 加密,百度一下网上资料很多,不是很详细,这里就整理下如何实现用md5加密和 哈希散列带秘钥加密算法,大家可以看下。
实现代码:
package com.ompa.common.utils; import java.security.messagedigest; import java.security.nosuchalgorithmexception; import javax.crypto.mac; import javax.crypto.secretkey; import javax.crypto.spec.secretkeyspec; /** * 采用md5加密 * * @author zhangcd * @date 2016-4-29 */ public class encryptutil { private static final string mac_name = "hmacsha1"; private static final string encoding = "utf-8"; private static final string key = "iloveyou"; /*** * md5加码 生成32位md5码 */ public static string string2md5(string instr){ messagedigest md5 = null; try{ md5 = messagedigest.getinstance("md5"); }catch (exception e){ system.out.println(e.tostring()); e.printstacktrace(); return ""; } char[] chararray = instr.tochararray(); byte[] bytearray = new byte[chararray.length]; for (int i = 0; i < chararray.length; i++) bytearray[i] = (byte) chararray[i]; byte[] md5bytes = md5.digest(bytearray); stringbuffer hexvalue = new stringbuffer(); for (int i = 0; i < md5bytes.length; i++){ int val = ((int) md5bytes[i]) & 0xff; if (val < 16) hexvalue.append("0"); hexvalue.append(integer.tohexstring(val)); } return hexvalue.tostring(); } /*** * md5加密 生成32位md5码 */ public static string stringmd5(string instr){ return string2md5(string2md5(instr)); } /** * 加密解密算法 */ public static string convertmd5(string instr){ char[] a = instr.tochararray(); for (int i = 0; i < a.length; i++){ a[i] = (char) (a[i] ^ 't'); } string s = new string(a); return s; } /** * hmac-sha1 * @param encrypttext * @param encryptkey * @return * @throws exception */ public static string hmacsha1encrypt(string encrypttext, string encryptkey) throws exception { byte[] data=encryptkey.getbytes(encoding); secretkey secretkey = new secretkeyspec(data, mac_name); mac mac = mac.getinstance(mac_name); mac.init(secretkey); byte[] text = encrypttext.getbytes(encoding); byte[] str = mac.dofinal(text); // create hex string stringbuffer hexstring = new stringbuffer(); // 字节数组转换为 十六进制 数 for (int i = 0; i < str.length; i++) { string shahex = integer.tohexstring(str[i] & 0xff); if (shahex.length() < 2) { hexstring.append(0); } hexstring.append(shahex); } return hexstring.tostring(); } public static string convertsha1(string instr){ try { return hmacsha1encrypt(instr,key); } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); return ""; } } // 测试主函数 public static void main(string args[]) throws exception { //哈希散列带秘钥加密 string tt = convertsha1("123456"); system.out.println(tt); //md5加密 string s = new string("123456"); system.out.println("原始:" + s); system.out.println("md5后:" + string2md5(s)); system.out.println("md5加密后:" + stringmd5(s)); } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!