JAVA MD5加密源码
- 格式:pdf
- 大小:66.91 KB
- 文档页数:2
Java实现MD5加密及解密的代码实例分享基础:MessageDigest类的使⽤其实要在Java中完成MD5加密,MessageDigest类⼤部分都帮你实现好了,⼏⾏代码⾜矣:/*** 对字符串md5加密** @param str* @return*/import java.security.MessageDigest;public static String getMD5(String str) {try {// ⽣成⼀个MD5加密计算摘要MessageDigest md = MessageDigest.getInstance("MD5");// 计算md5函数md.update(str.getBytes());// digest()最后确定返回md5 hash值,返回值为8为字符串。
因为md5 hash值是16位的hex值,实际上就是8位的字符// BigInteger函数则将8位的字符串转换成16位hex值,⽤字符串来表⽰;得到字符串形式的hash值return new BigInteger(1, md.digest()).toString(16);} catch (Exception e) {throw new SpeedException("MD5加密出现错误");}}进阶:加密及解密类Java实现MD5加密以及解密类,附带测试类,具体见代码。
MD5加密解密类——MyMD5Util,代码如下package com.zyg.security.md5;import java.io.UnsupportedEncodingException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.util.Arrays;public class MyMD5Util {private static final String HEX_NUMS_STR="0123456789ABCDEF";private static final Integer SALT_LENGTH = 12;/*** 将16进制字符串转换成字节数组* @param hex* @return*/public static byte[] hexStringToByte(String hex) {int len = (hex.length() / 2);byte[] result = new byte[len];char[] hexChars = hex.toCharArray();for (int i = 0; i < len; i++) {int pos = i * 2;result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4| HEX_NUMS_STR.indexOf(hexChars[pos + 1]));}return result;}/*** 将指定byte数组转换成16进制字符串* @param b* @return*/public static String byteToHexString(byte[] b) {StringBuffer hexString = new StringBuffer();for (int i = 0; i < b.length; i++) {String hex = Integer.toHexString(b[i] & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}hexString.append(hex.toUpperCase());}return hexString.toString();}/*** 验证⼝令是否合法* @param password* @param passwordInDb* @return* @throws NoSuchAlgorithmException* @throws UnsupportedEncodingException*/public static boolean validPassword(String password, String passwordInDb)throws NoSuchAlgorithmException, UnsupportedEncodingException {//将16进制字符串格式⼝令转换成字节数组byte[] pwdInDb = hexStringToByte(passwordInDb);//声明盐变量byte[] salt = new byte[SALT_LENGTH];//将盐从数据库中保存的⼝令字节数组中提取出来System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH);//创建消息摘要对象MessageDigest md = MessageDigest.getInstance("MD5");//将盐数据传⼊消息摘要对象md.update(salt);//将⼝令的数据传给消息摘要对象md.update(password.getBytes("UTF-8"));//⽣成输⼊⼝令的消息摘要byte[] digest = md.digest();//声明⼀个保存数据库中⼝令消息摘要的变量byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH];//取得数据库中⼝令的消息摘要System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); //⽐较根据输⼊⼝令⽣成的消息摘要和数据库中消息摘要是否相同if (Arrays.equals(digest, digestInDb)) {//⼝令正确返回⼝令匹配消息return true;} else {//⼝令不正确返回⼝令不匹配消息return false;}}/*** 获得加密后的16进制形式⼝令* @param password* @return* @throws NoSuchAlgorithmException* @throws UnsupportedEncodingException*/public static String getEncryptedPwd(String password)throws NoSuchAlgorithmException, UnsupportedEncodingException {//声明加密后的⼝令数组变量byte[] pwd = null;//随机数⽣成器SecureRandom random = new SecureRandom();//声明盐数组变量byte[] salt = new byte[SALT_LENGTH];//将随机数放⼊盐变量中random.nextBytes(salt);//声明消息摘要对象MessageDigest md = null;//创建消息摘要md = MessageDigest.getInstance("MD5");//将盐数据传⼊消息摘要对象md.update(salt);//将⼝令的数据传给消息摘要对象md.update(password.getBytes("UTF-8"));//获得消息摘要的字节数组byte[] digest = md.digest();//因为要在⼝令的字节数组中存放盐,所以加上盐的字节长度pwd = new byte[digest.length + SALT_LENGTH];//将盐的字节拷贝到⽣成的加密⼝令字节数组的前12个字节,以便在验证⼝令时取出盐 System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH);//将消息摘要拷贝到加密⼝令字节数组从第13个字节开始的字节System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length);//将字节数组格式加密后的⼝令转化为16进制字符串格式的⼝令return byteToHexString(pwd);}}测试类——Client,代码如下:package com.zyg.security.md5;import java.io.UnsupportedEncodingException;import java.security.NoSuchAlgorithmException;import java.util.HashMap;import java.util.Map;public class Client {private static Map users = new HashMap();public static void main(String[] args){String userName = "zyg";String password = "123";registerUser(userName,password);userName = "changong";password = "456";registerUser(userName,password);String loginUserId = "zyg";String pwd = "1232";try {if(loginValid(loginUserId,pwd)){System.out.println("欢迎登陆");}else{System.out.println("⼝令错误,请重新输⼊");}} catch (NoSuchAlgorithmException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** 注册⽤户** @param userName* @param password*/public static void registerUser(String userName,String password){String encryptedPwd = null;try {encryptedPwd = MyMD5Util.getEncryptedPwd(password);users.put(userName, encryptedPwd);} catch (NoSuchAlgorithmException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** 验证登陆** @param userName* @param password* @return* @throws UnsupportedEncodingException* @throws NoSuchAlgorithmException*/public static boolean loginValid(String userName,String password)throws NoSuchAlgorithmException, UnsupportedEncodingException{String pwdInDb = (String)users.get(userName);if(null!=pwdInDb){ // 该⽤户存在return MyMD5Util.validPassword(password, pwdInDb);}else{System.out.println("不存在该⽤户");return false;}}}PS:这⾥再为⼤家提供2款MD5加密⼯具,感兴趣的朋友可以参考⼀下:MD5在线加密⼯具:在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密⼯具:。
为⼤家经常为md5加密过的常⽤admin,admin888,0000密
码
admin 加密后代码:
16位加密(7a57a5a743894a0e)
32位加密(21232f297a57a5a743894a0e4a801fc3)
admin888 加密后代码:
16位加密(469e80d32c0559f8)
0000 加密后代码:
16位加密(14474e4033ac29cc)
32位加密(4a7d1ed414474e4033ac29ccb8653d9b)
知道了有什么⽤?
针对⼀些⽹站程序后台⽆法登陆的情况,如果是因为后台管理⽤户与密码错误所致,可以利⽤这个来解决。
1、先检查数据库连接⽂件,查看⾥⾯的数据库连接路径,这样可以准确找出数据库⽂件。
(常见的数据库连接⽂件:conn.asp、Config.asp,如果有Include⽂件夹,⼀般在这个⽂件夹下。
)
2、找到数据库⽂件后,⽤ACCESS打开进⾏修改。
(ACCESS数据库的后缀是.MDB,有的⽹站程序为了安全,会将数据库⽂件后缀更改为.ASP或.asa 。
如果发现数据库不是.MDB后缀,可以直接将后缀改成.MDB后再⽤ACCESS打开,修改完后再改回原后缀名。
)
3、打开数据库后找到管理⽤户的表,进去进⾏修改管理⽤户与密码。
(有的数据库是明⽂密码,没有进⾏加密,如果是这样可以直接把密码修改成⾃⼰需要的;有的程序进⾏了16位或者32位MD5加密,这样的就需要修改成加密后的密码,可以按上⾯提供的加密后的代码修改。
)
4、修改完成后保存退出。
java中如何给⽂件加密1、根据⾃⼰定的,从⽂件流中读取字节进⾏加密2、将加密后的字节写⼊⽂件。
md5加密:package com.ncs.pki.util;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class MD5Test {private static MessageDigest digest = null;public synchronized static final String hash(String data) {if (digest == null) {try {digest = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException nsae) {System.err.println("Failed to load the MD5 MessageDigest. "+ "Jive will be unable to function normally.");nsae.printStackTrace();}}// Now, compute hash.digest.update(data.getBytes());return encodeHex(digest.digest());}public static final String encodeHex(byte[] bytes) {StringBuffer buf = new StringBuffer(bytes.length * 2);int i;for (i = 0; i < bytes.length; i++) {if (((int) bytes[i] & 0xff) < 0x10) {buf.append("0");}buf.append(Long.toString((int) bytes[i] & 0xff, 16));}return buf.toString();}public static String test(){return null;}/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println(MD5Test.hash("123456"));}}3des加密:package com.ncs.pki.util;import java.security.Key;import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;public class DesEncrypt {/**** 使⽤DES加密与解密,可对byte[],String类型进⾏加密与解密密⽂可使⽤String,byte[]存储.** ⽅法: void getKey(String strKey)从strKey的字条⽣成⼀个Key** String getEncString(String strMing)对strMing进⾏加密,返回String密⽂ String* getDesString(String strMi)对strMin进⾏解密,返回String明⽂**byte[] getEncCode(byte[] byteS)byte[]型的加密 byte[] getDesCode(byte[] * byteD)byte[]型的解密*/Key key;/*** 根据参数⽣成KEY** @param strKey*/public void getKey(String strKey) {try {KeyGenerator _generator = KeyGenerator.getInstance("DES");_generator.init(new SecureRandom(strKey.getBytes()));this.key = _generator.generateKey();_generator = null;} catch (Exception e) {e.printStackTrace();}}/*** 加密String明⽂输⼊,String密⽂输出** @param strMing* @return*/public String getEncString(String strMing) {byte[] byteMi = null;byte[] byteMing = null;String strMi = "";BASE64Encoder base64en = new BASE64Encoder();try {byteMing = strMing.getBytes("UTF8");byteMi = this.getEncCode(byteMing);strMi = base64en.encode(byteMi);} catch (Exception e) {e.printStackTrace();} finally {base64en = null;byteMing = null;byteMi = null;}return strMi;}/*** 解密以String密⽂输⼊,String明⽂输出** @param strMi* @return*/public String getDesString(String strMi) {BASE64Decoder base64De = new BASE64Decoder();byte[] byteMing = null;byte[] byteMi = null;String strMing = "";try {byteMi = base64De.decodeBuffer(strMi);byteMing = this.getDesCode(byteMi);strMing = new String(byteMing, "UTF8");} catch (Exception e) {e.printStackTrace();} finally {base64De = null;byteMing = null;byteMi = null;}}return strMing;}/*** 加密以byte[]明⽂输⼊,byte[]密⽂输出** @param byteS* @return*/private byte[] getEncCode(byte[] byteS) {byte[] byteFina = null;Cipher cipher;try {cipher = Cipher.getInstance("DES");cipher.init(Cipher.ENCRYPT_MODE, key);byteFina = cipher.doFinal(byteS);} catch (Exception e) {e.printStackTrace();} finally {cipher = null;}return byteFina;}/*** 解密以byte[]密⽂输⼊,以byte[]明⽂输出** @param byteD* @return*/private byte[] getDesCode(byte[] byteD) {Cipher cipher;byte[] byteFina = null;try {cipher = Cipher.getInstance("DES");cipher.init(Cipher.DECRYPT_MODE, key);byteFina = cipher.doFinal(byteD);} catch (Exception e) {e.printStackTrace();} finally {cipher = null;}return byteFina;}public static void main(String[] args) {System.out.println("des demo");DesEncrypt des = new DesEncrypt();// 实例化⼀个对像des.getKey("MYKEY");// ⽣成密匙System.out.println("key=MYKEY");String strEnc = des.getEncString("111111");// 加密字符串,返回String的密⽂ System.out.println("密⽂=" + strEnc);String strDes = des.getDesString(strEnc);// 把String 类型的密⽂解密System.out.println("明⽂=" + strDes);}}。
jsp使用md5加密进行登录验证JSP(JavaServer Pages)是一种用于动态生成HTML页面的技术,而MD5(Message Digest Algorithm 5)是一种常用的加密算法。
在使用JSP进行登录验证时,可以结合MD5算法对用户密码进行加密存储,提高安全性。
下面我将为你详细介绍如何在JSP中使用MD5加密进行登录验证。
1.导入MD5算法库2.加密用户密码在用户注册或者保存密码的过程中,将用户输入的密码通过MD5算法进行加密,然后将加密后的密文保存到数据库中。
可以在JSP页面中编写一个函数,调用MD5算法库实现密码的加密过程。
例如:```javaString plainPassword = request.getParameter("password");String encryptedPassword = encryptPassword(plainPassword);//加密函数public String encryptPassword(String password)tryMessageDigest md = MessageDigest.getInstance("MD5");byte[] messageDigest = md.digest(password.getBytes();StringBuilder sb = new StringBuilder(;for (byte b : messageDigest)sb.append(String.format("%02x", b));}return sb.toString(;} catch (NoSuchAlgorithmException e)e.printStackTrace(;}return null;```3.登录验证在登录过程中,将用户输入的密码同样进行MD5加密,然后与存储在数据库中的密文进行比对。
java 标准的md5Java标准的MD5。
在Java编程中,MD5(Message Digest Algorithm 5)是一种广泛使用的加密算法,用于对数据进行加密和摘要处理。
MD5算法产生的摘要长度为128位,通常以32位十六进制数表示,它是一种不可逆的加密算法,即无法通过MD5摘要逆向推导出原始数据。
在本文中,我们将详细介绍Java标准的MD5算法的使用方法和相关注意事项。
首先,我们需要了解如何在Java中使用MD5算法对数据进行加密。
Java标准库中提供了java.security.MessageDigest类来实现MD5算法。
下面是一个简单的示例代码:```java。
import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class MD5Example {。
public static void main(String[] args) {。
String input = "Hello, MD5!";try {。
MessageDigest md = MessageDigest.getInstance("MD5");md.update(input.getBytes());byte[] digest = md.digest();StringBuffer sb = new StringBuffer();for (byte b : digest) {。
sb.append(String.format("%02x", b & 0xff));}。
System.out.println("MD5 hash: " + sb.toString());} catch (NoSuchAlgorithmException e) {。
JSP使用MD5加密进行登录验证使用MD5加密进行登录验证是常见的一种方式,本文将详细介绍如何在JSP中使用MD5加密进行登录验证。
一、什么是MD5加密MD5是一种常用的加密算法,它将任意长度的数据转化为固定长度的密文,且不可逆。
即使输入数据只发生了一个字符的改变,也会导致加密后的密文发生巨大的变化,因此MD5加密是一种非常安全的加密方式。
在应用中,用户的账号和密码都是敏感信息,为了保护用户的隐私,通常会对用户的密码进行加密保存。
使用MD5加密是一种常见的方式,因为MD5加密后的密文很难被破解,即使被黑客获取到密文,也无法还原出原始密码。
三、如何在JSP中使用MD5加密1. 引入MD5加密算法的Java类库在JSP中,我们可以使用Java提供的MessageDigest类来实现MD5加密。
首先,需要引入java.security.MessageDigest类库,在JSP页面的顶部添加如下代码:```java```2.创建MD5加密方法创建一个方法来实现MD5加密,代码如下:```javapublic String md5Encryption(String input) throws ExceptionMessageDigest messageDigest =MessageDigest.getInstance("MD5");byte[] digest = messageDigest.digest(input.getBytes();StringBuilder result = new StringBuilder(;for (byte b : digest)result.append(String.format("%02x", b & 0xff));}return result.toString(;```这个方法接受一个输入参数,将其转换为字节数组后再进行加密计算,最后将结果转换为十六进制字符串形式返回。
JAVA生成MD5校验码及算法实现在Java中,java.security.MessageDigest (rt.jar中)已经定义了MD5 的计算,所以我们只需要简单地调用即可得到MD5 的128 位整数。
然后将此128 位计16 个字节转换成16 进制表示即可。
下面是一个可生成字符串或文件MD5校验码的例子,测试过,可当做工具类直接使用,其中最主要的是getMD5String(String s)和getFileMD5String(File file)两个方法,分别用于生成字符串的md5校验值和生成文件的md5校验值,getFileMD5String_old(File file)方法可删除,不建议使用:package com.why.md5;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class MD5Util {/*** 默认的密码字符串组合,用来将字节转换成16 进制表示的字符,apache 校验下载的文件的正确性用的就是默认的这个组合*/protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };protected static MessageDigest messagedigest = null;static {try {messagedigest = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException nsaex) {System.err.println(MD5Util.class.getName()+ "初始化失败,MessageDigest不支持MD5Util。
hutool-all 密码加密方法全文共四篇示例,供读者参考第一篇示例:在应用程序开发中,密码加密是一项非常重要的安全措施。
Hutool是一个Java工具类库,提供了一系列简便易用的密码加密方法,可以帮助开发者轻松实现数据加密和解密的功能。
本文将介绍Hutool-all中的一些常用密码加密方法,并讨论如何在实际项目中应用这些方法保护用户数据安全。
Hutool-all是一个功能强大的Java工具类库,其中包含了丰富的工具方法和类,可以帮助开发者简化程序开发过程。
在密码加密方面,Hutool-all提供了多种加密算法,包括MD5、SHA-1、SHA-256、AES等。
接下来,我们将逐一介绍这些加密算法的用法和特点。
我们来看一下最常用的MD5加密算法。
MD5是一种消息摘要算法,可以将任意长度的数据转换为一个128位的数字指纹。
在Hutool-all中,可以通过如下代码来实现对字符串进行MD5加密:```String password = "123456";String md5Password = SecureUtil.md5(password);System.out.println("MD5加密后的密码:" + md5Password);```通过上面的代码,我们可以看到将字符串"123456"加密为MD5后的密码。
MD5是一种单向加密算法,不可逆,但可以用于验证原始数据的完整性。
在实际应用中,可以将用户的密码存储为MD5加密后的值,确保数据安全。
除了MD5之外,Hutool-all还提供了SHA系列的加密算法,包括SHA-1和SHA-256。
这些算法可以生产更长的摘要结果,提高了加密的安全性。
下面是一个使用SHA-256加密算法的示例代码:通过以上代码,我们可以看到将密码"123456"使用SHA-256算法加密后的结果。
Java详解单向加密--MD5、SHA和HMAC及简单实现实例Java 详解单向加密--MD5、SHA和HMAC及简单实现实例概要:MD5、SHA、HMAC这三种加密算法,可谓是⾮可逆加密,就是不可解密的加密⽅法。
MD5MD5即Message-Digest Algorithm 5(信息-摘要算法5),⽤于确保信息传输完整⼀致。
MD5是输⼊不定长度信息,输出固定长度128-bits的算法。
MD5算法具有以下特点:1、压缩性:任意长度的数据,算出的MD5值长度都是固定的。
2、容易计算:从原数据计算出MD5值很容易。
3、抗修改性:对原数据进⾏任何改动,哪怕只修改1个字节,所得到的MD5值都有很⼤区别。
4、强抗碰撞:已知原数据和其MD5值,想找到⼀个具有相同MD5值的数据(即伪造数据)是⾮常困难的。
MD5还⼴泛⽤于操作系统的登陆认证上,如Unix、各类BSD系统登录密码、数字签名等诸多⽅⾯。
如在Unix系统中⽤户的密码是以MD5(或其它类似的算法)经Hash运算后存储在⽂件系统中。
当⽤户登录的时候,系统把⽤户输⼊的密码进⾏MD5 Hash运算,然后再去和保存在⽂件系统中的MD5值进⾏⽐较,进⽽确定输⼊的密码是否正确。
通过这样的步骤,系统在并不知道⽤户密码的明码的情况下就可以确定⽤户登录系统的合法性。
这可以避免⽤户的密码被具有系统管理员权限的⽤户知道。
MD5将任意长度的“字节串”映射为⼀个128bit的⼤整数,并且通过该128bit反推原始字符串是⾮常困难的。
SHASHA(Secure Hash Algorithm,安全散列算法),数字签名等密码学应⽤中重要的⼯具,被⼴泛地应⽤于电⼦商务等信息安全领域。
虽然SHA与MD5通过碰撞法都被破解了,但是SHA仍然是公认的安全加密算法,较之MD5更为安全。
SHA所定义的长度下表中的中继散列值(internal state)表⽰对每个数据区块压缩散列过后的中继值(internal hash sum)。
Java和JSMD5加密-附盐值加密demo JAVA和JS的MD5加密经过测试:字母和数据好使,中⽂不好使。
源码如下:*** 类MD5Util.java的实现描述:**/public class MD5Util {// 获得MD5摘要算法的 MessageDigest 对象private static MessageDigest _mdInst = null;private static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};private static MessageDigest getMdInst() {if (_mdInst == null) {try {_mdInst = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException e) {e.printStackTrace();}}return _mdInst;}private MD5Util() {}/*** Returns a MessageDigest for the given <code>algorithm</code>.** @return An MD5 digest instance.* @throws RuntimeException when a {@link NoSuchAlgorithmException} is caught*/static MessageDigest getDigest() {try {return MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException e) {throw new RuntimeException(e);}}/*** Calculates the MD5 digest and returns the value as a 16 element <code>byte[]</code>.** @param data Data to digest* @return MD5 digest*/public static byte[] md5(byte[] data) {return getDigest().digest(data);}/*** Calculates the MD5 digest and returns the value as a 16 element <code>byte[]</code>.** @param data Data to digest* @return MD5 digest*/public static byte[] md5(String data) {return md5(data.getBytes());}/*** Calculates the MD5 digest and returns the value as a 32 character hex string.** @param data Data to digest* @return MD5 digest as a hex string*//*public static String md5Hex(byte[] data) {return HexUtil.toHexString(md5(data));}*//*** Calculates the MD5 digest and returns the value as a 32 character hex string. ** @param data Data to digest* @return MD5 digest as a hex string*//*public static String md5Hex(String data) {return HexUtil.toHexString(md5(data));}*//*** 对密码字符串进⾏MD5加密** @param pass* @return*/public static String encoding(String pass) {if (pass == null) {return "";} else {StringBuffer buf = null;MessageDigest md5 = null;try {// 获取md5摘要md5 = MessageDigest.getInstance("MD5");// 指定utf-8编码md5.update(pass.getBytes("utf-8"));byte[] b = md5.digest();int i;buf = new StringBuffer("");for (int offset = 0; offset < b.length; offset++) {i = b[offset];if (i < 0) {i += 256;}if (i < 16) {buf.append("0");}// 产⽣16进制保存buf.append(Integer.toHexString(i));}} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}return buf.toString();}}public final static String encode(String s) {try {byte[] btInput = s.getBytes();// 使⽤指定的字节更新摘要getMdInst().update(btInput);// 获得密⽂byte[] md = getMdInst().digest();// 把密⽂转换成⼗六进制的字符串形式int j = md.length;char str[] = new char[j * 2];int k = 0;for (int i = 0; i < j; i++) {byte byte0 = md[i];str[k++] = hexDigits[byte0 >>> 4 & 0xf];str[k++] = hexDigits[byte0 & 0xf];}return new String(str);} catch (Exception e) {e.printStackTrace();return null;}}}md5.js/** A JavaScript implementation of the RSA Data Security, Inc. MD5 Message* Digest Algorithm, as defined in RFC 1321.* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet* Distributed under the BSD License* See /crypt/md5 for more info.*//** Configurable variables. You may need to tweak these to be compatible with* the server-side, but the defaults work in most cases.*/var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode *//** These are the functions you'll usually want to call* They take string arguments and return either hex or base-64 encoded strings*/function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));} function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));} function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));} function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); } function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); } function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); } /** Perform a simple self-test to see if the VM is working*/function md5_vm_test(){return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";}/** Calculate the MD5 of an array of little-endian words, and a bit length*/function core_md5(x, len){/* append padding */x[len >> 5] |= 0x80 << ((len) % 32);x[(((len + 64) >>> 9) << 4) + 14] = len;var a = 1732584193;var b = -271733879;var c = -1732584194;var d = 271733878;for(var i = 0; i < x.length; i += 16){var olda = a;var oldb = b;var oldc = c;var oldd = d;a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);c = md5_ff(c, d, a, b, x[i+10], 17, -42063);b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);a = safe_add(a, olda);b = safe_add(b, oldb);c = safe_add(c, oldc);d = safe_add(d, oldd);}return Array(a, b, c, d);}/** These functions implement the four basic operations the algorithm uses. */function md5_cmn(q, a, b, x, s, t){return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);}function md5_ff(a, b, c, d, x, s, t){return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);}function md5_gg(a, b, c, d, x, s, t){return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);}function md5_hh(a, b, c, d, x, s, t){return md5_cmn(b ^ c ^ d, a, b, x, s, t);}function md5_ii(a, b, c, d, x, s, t){return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);}/** Calculate the HMAC-MD5, of a key and some data*/function core_hmac_md5(key, data){var bkey = str2binl(key);if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);var ipad = Array(16), opad = Array(16);for(var i = 0; i < 16; i++){ipad[i] = bkey[i] ^ 0x36363636;opad[i] = bkey[i] ^ 0x5C5C5C5C;}var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);return core_md5(opad.concat(hash), 512 + 128);}/** Add integers, wrapping at 2^32. This uses 16-bit operations internally* to work around bugs in some JS interpreters.*/function safe_add(x, y){var lsw = (x & 0xFFFF) + (y & 0xFFFF);var msw = (x >> 16) + (y >> 16) + (lsw >> 16);return (msw << 16) | (lsw & 0xFFFF);}/** Bitwise rotate a 32-bit number to the left.*/function bit_rol(num, cnt){return (num << cnt) | (num >>> (32 - cnt));}/** Convert a string to an array of little-endian words* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.*/function str2binl(str){var bin = Array();var mask = (1 << chrsz) - 1;for(var i = 0; i < str.length * chrsz; i += chrsz)bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);return bin;}/** Convert an array of little-endian words to a string*/function binl2str(bin){var str = "";var mask = (1 << chrsz) - 1;for(var i = 0; i < bin.length * 32; i += chrsz)str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);return str;}/** Convert an array of little-endian words to a hex string.*/function binl2hex(binarray){var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";var str = "";for(var i = 0; i < binarray.length * 4; i++){str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);}return str;}/** Convert an array of little-endian words to a base-64 string*/function binl2b64(binarray){var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var str = "";for(var i = 0; i < binarray.length * 4; i += 3){var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);for(var j = 0; j < 4; j++){if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);}}return str;}测试DEMO类(⼯具类加密后转成⼩写):public class Test {public static void main(String[] args) throws Exception {String source = "123AB";String salt = "asdklsakjfdlsadjfl";System.out.printf("source is %s,result is %s",salt+source,MD5Util.encode(salt+source).toLowerCase()); }}运⾏结果:source is asdklsakjfdlsadjfl123AB,result is d5976dad58ad32000e3867f0601e236c。