java 实现MD5加密算法的简单实例
程序员文章站
2024-02-24 18:46:34
java 实现md5加密算法的简单实例
实现代码:
import java.security.nosuchalgorithmexception;
p...
java 实现md5加密算法的简单实例
实现代码:
import java.security.nosuchalgorithmexception; public class md5hashutil { private messagedigest md = null; private static md5hashutil md5 = null; private static final char[] hexchars ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; /** * constructor is private so you must use the getinstance method */ private md5hashutil() throws nosuchalgorithmexception { md = messagedigest.getinstance("md5"); } /** * this returns the singleton instance */ public static md5hashutil getinstance()throws nosuchalgorithmexception { if (md5 == null) { md5 = new md5hashutil(); } return (md5); } public static string hashcode(string datatohash) throws nosuchalgorithmexception{ return getinstance().hashdata(datatohash.getbytes()); } public static string hashcode(byte[] datatohash) throws nosuchalgorithmexception{ return getinstance().hashdata(datatohash); } public string hashdata(byte[] datatohash) { return hexstringfrombytes((calculatehash(datatohash))).tolowercase(); } private byte[] calculatehash(byte[] datatohash) { md.update(datatohash, 0, datatohash.length); return (md.digest()); } public string hexstringfrombytes(byte[] b) { string hex = ""; int msb; int lsb = 0; int i; // msb maps to idx 0 for (i = 0; i < b.length; i++) { msb = ((int)b[i] & 0x000000ff) / 16; lsb = ((int)b[i] & 0x000000ff) % 16; hex = hex + hexchars[msb] + hexchars[lsb]; } return(hex); } public static void main(string args[]) throws nosuchalgorithmexception { string string = "my name is zhangli"; system.out.println(string); system.out.println(hashcode(string)); } }
如上代码为java语言实现md5加密算法,输出为加密后的密文!
通常将加密后的密文保存在数据库中,如果需要比较只比较他们的用md5加密过后的密文。
同时,md5加密算法是不可逆的,破解的难度很高。
以上就是java md5加密算法的实例详解,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!