MD5-java
- 格式:doc
- 大小:45.50 KB
- 文档页数:19
Java⽂件完整性校验MD5sha1sha256sha224sha384sha512由于项⽬中需要使⽤⽂件做备份,并且要提供备份⽂件的下载功能。
备份⽂件体积较⼤,为确保下载后的⽂件与原⽂件⼀致,需要提供⽂件完整性校验。
⽹上有这么多此类⽂章,其中不少使⽤到了mons.codec.digest.DigestUtils包中的⽅法,但是⼜⾃⼰做了⼤⽂件的拆分及获取相应校验码的转换。
DigestUtils 包已经提供了为⽂件流⽣成校验码的功能,可以直接调⽤。
经测试10⼏G的⽂件在30秒内可完成计算。
(⽹上提供的⼀些⾃⼰拆分⼤⽂件的⽰例,⽂件较⼩时结果正确,⽂件较⼤时结果就不太可靠了)实现步骤如下:1. pom.xml 添加依赖<dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.12</version></dependency>2. 实现类:package file.integrity.check;import mons.codec.digest.DigestUtils;import java.io.File;import java.io.FileInputStream;public class Application {public static void main(String[] args) throws Exception {File file = new File("/path/filename");FileInputStream fileInputStream = new FileInputStream(file);String hex = DigestUtils.sha512Hex(fileInputStream);System.out.println(hex);}}3. 或者:import mons.codec.digest.DigestUtils;import static mons.codec.digest.MessageDigestAlgorithms.SHA_512;import java.io.File;public class Application {public static void main(String[] args) throws Exception {File file = new File("/path/filename");String hex = new DigestUtils(SHA_512).digestAsHex(file);System.out.println(hex);}}。
java中常用的md5方法Java是一种广泛使用的编程语言,特别适合用于开发各种类型的应用程序。
在Java中,MD5(Message-Digest Algorithm 5)是一种常用的哈希算法,用于产生唯一的消息摘要。
本文将详细介绍在Java中常用的MD5方法。
第一步:导入相关的包使用MD5算法需要导入Java的Security包。
在代码的开头加上以下导入语句:import java.security.MessageDigest;第二步:创建一个方法在Java中,我们可以创建一个方法用于计算MD5消息摘要。
下面是一个示例:public static String getMD5(String input) {try {MessageDigest md =MessageDigest.getInstance("MD5"); 创建MD5加密对象byte[] messageDigest = md.digest(input.getBytes()); 获取二进制摘要值转化为十六进制字符串形式StringBuilder hexString = new StringBuilder();for (byte b : messageDigest) {String hex = Integer.toHexString(0xFF & b);if (hex.length() == 1) {hexString.append('0');}hexString.append(hex);}return hexString.toString();} catch (Exception ex) {ex.printStackTrace();return null;}}第三步:调用方法要使用这个方法,只需在代码中调用getMD5()方法,并传递要进行MD5加密的消息作为参数。
以下是一个使用示例:String input = "Hello World";String md5Hash = getMD5(input);System.out.println("MD5加密后的结果:" + md5Hash);以上代码将输出:MD5加密后的结果:0a4d55a8d778e5022fab701977c5d840第四步:解释代码让我们来解释一下上面的代码。
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加密⼯具:。
java使⽤计算md5校验码⽅式⽐较两个⽂件是否相同复制代码代码如下:public class MD5Check {/*** 默认的密码字符串组合,⽤来将字节转换成 16 进制表⽰的字符,apache校验下载的⽂件的正确性⽤的就是默认的这个组合*/protected char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };protected MessageDigest messagedigest = null;{try {messagedigest = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException e) {e.printStackTrace();}}public String getFileMD5String(File file) throws IOException {InputStream fis;fis = new FileInputStream(file);byte[] buffer = new byte[1024];int numRead = 0;while ((numRead = fis.read(buffer)) > 0) {messagedigest.update(buffer, 0, numRead);}fis.close();return bufferToHex(messagedigest.digest());}public String getFileMD5String(InputStream in) throws IOException {byte[] buffer = new byte[1024];int numRead = 0;while ((numRead = in.read(buffer)) > 0) {messagedigest.update(buffer, 0, numRead);}in.close();return bufferToHex(messagedigest.digest());}private String bufferToHex(byte bytes[]) {return bufferToHex(bytes, 0, bytes.length);}private String bufferToHex(byte bytes[], int m, int n) {StringBuffer stringbuffer = new StringBuffer(2 * n);int k = m + n;for (int l = m; l < k; l++) {appendHexPair(bytes[l], stringbuffer);}return stringbuffer.toString();}private void appendHexPair(byte bt, StringBuffer stringbuffer) {char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中⾼ 4 位的数字转换// 为逻辑右移,将符号位⼀起右移,此处未发现两种符号有何不同char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换stringbuffer.append(c0);stringbuffer.append(c1);}}。
java实现计算MD5 import java.io.FileInputStream;import java.security.DigestInputStream;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class MD5Class {// 计算字符串的MD5public static String conVertTextToMD5(String plainText) {try {MessageDigest md = MessageDigest.getInstance("MD5");md.update(plainText.getBytes());byte b[] = md.digest();int i;StringBuffer 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");buf.append(Integer.toHexString(i));}// 32位加密return buf.toString();// 16位的加密// return buf.toString().substring(8, 24);} catch (NoSuchAlgorithmException e) {e.printStackTrace();return null;}} //计算⽂件的MD5,⽀持4G⼀下的⽂件(⽂件亲测,⼤⽂件未亲测)public static String conVertFileToMD5(String inputFilePath) {int bufferSize = 256 * 1024;FileInputStream fileInputStream = null;DigestInputStream digestInputStream = null;try {// 拿到⼀个MD5转换器(同样,这⾥可以换成SHA1)MessageDigest messageDigest = MessageDigest.getInstance("MD5");// 使⽤DigestInputStreamfileInputStream = new FileInputStream(inputFilePath);digestInputStream = new DigestInputStream(fileInputStream,messageDigest);// read的过程中进⾏MD5处理,直到读完⽂件byte[] buffer = new byte[bufferSize];while (digestInputStream.read(buffer) > 0);// 获取最终的MessageDigestmessageDigest = digestInputStream.getMessageDigest();// 拿到结果,也是字节数组,包含16个元素byte[] resultByteArray = messageDigest.digest();// 同样,把字节数组转换成字符串return byteArrayToHex(resultByteArray);} catch (Exception e) {return null;} finally {try {digestInputStream.close();} catch (Exception e) {}try {fileInputStream.close();} catch (Exception e) {}}}private static String byteArrayToHex(byte[] byteArray) {// ⾸先初始化⼀个字符数组,⽤来存放每个16进制字符char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','A', 'B', 'C', 'D', 'E', 'F' };// new⼀个字符数组,这个就是⽤来组成结果字符串的(解释⼀下:⼀个byte是⼋位⼆进制,也就是2位⼗六进制字符(2的8次⽅等于16的2次⽅))char[] resultCharArray = new char[byteArray.length * 2];// 遍历字节数组,通过位运算(位运算效率⾼),转换成字符放到字符数组中去int index = 0;for (byte b : byteArray) {resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];resultCharArray[index++] = hexDigits[b & 0xf];}// 字符数组组合成字符串返回return new String(resultCharArray);}public static void main(String[] args) {// 测试System.out.println(MD5Class.conVertTextToMD5("hello"));System.out.println(conVertFileToMD5("C:\\Users\\administrator1\\Downloads\\StarUML-v2.8.0.msi"));}}。
java中的md5用法Java中的MD5用法什么是MD5MD5是一种常见的哈希算法,用于对任意长度的数据进行加密。
它可以将任意长度的数据转化为定长的128位(16字节)哈希值。
使用场景MD5主要用于密码存储、数据完整性校验、数字签名等场景。
使用步骤1.导入类:import ;2.创建MD5对象:MessageDigest md = ("MD5");此处也可以使用其他哈希算法,如”SHA-1”等。
3.将要加密的数据转换为字节数组:String data = "Hello, World!";byte[] dataBytes = ();4.将字节数组更新到MD5对象中:(dataBytes);5.计算MD5的哈希值:byte[] md5Bytes = ();6.将MD5的哈希值转化为字符串表示:StringBuilder sb = new StringBuilder();for (byte b : md5Bytes) {(("%02x", b & 0xff));}String md5 = ();通过上述步骤,我们即可得到原始数据的MD5加密结果。
实际应用密码存储在用户注册或登录时,常常需要对用户输入的密码进行加密后才能进行存储或验证。
以下是一个示例代码:public static String getMD5(String data) {String md5 = null;try {MessageDigest md = ("MD5");byte[] dataBytes = ();(dataBytes);byte[] md5Bytes = ();StringBuilder sb = new StringBuilder();for (byte b : md5Bytes) {(("%02x", b & 0xff));}md5 = ();} catch (Exception e) {();}return md5;}在注册时,可以将用户输入的密码使用上述方法加密后存储到数据库中。
对中⽂进⾏MD5加密的注意事项(Java版,编码问题)在⼯作中需要和第三⽅进⾏Http通信,在通信内容中有⼏个参数涉及到了中⽂。
⾃⼰在进⾏MD5加密验证过程中,遇到了⼀些很奇怪(本⼈认为MD5是⼀个通⽤简单的加密,应该很稳定很完美了吧!)的问题:问题1:接收到的问题乱码了解决:这个问题很常见,⽹上有很多说明。
由于http协议在传输过程中使⽤的都是iso_8859_1编码,所以在接收到参数之后,⽤value = new String(value.getBytes("ISO-8859-1"),"UTF-8"); ⽅法转成utf-8就可以了。
问题2:按照问题1的解决办法,⽣成MD5加密之前的字符串(⽇志中显⽰中⽂没有乱码),但是MD5加密之后字符串和本地的⽣成的不⼀样。
解决:这个问题就⽐较奇怪了。
我⼜详细的查看了查看了第三⽅的开发问题,发现其中有"台通知参数都⽤URLEncoder.encode("xxx","UTF-8")做了编码处理"这句话,是不是这个原因引起的呢?⾃⼰做了尝试将参数⼜通过value=URLDecoder.decode(value, "UTF-8")进⾏了解码。
出来,加密的字符串⼀致了。
问题3:这个问题就更奇怪了,在测试环境MD5之后是⼀样的,在正式环境就不⼀样了,并且正式环境的tomcat重新启动之后就正常了,但是⼀段时间之后⼜出现问题了。
解决:这个问题是由于MD5中⽤的String.getBytes()没有显⽰的指定编码格式导致的。
如果⽅法String.getBytes()不显⽰指定编码格式,本⽅法将返回该默认的编码格式的字节数组。
(这个问题还有个疑问就是为什么重启tomcat之后⼜正常了)总结:这个Http通信时,对⽅进⾏了怎么样的正向操作,你就要逆向把它解析出来。
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) {。
MD5加密Java工具类//十六进制下数字到字符的映射数组private final static String[] hexDigits = { 0 , 1 , 2 , 3 , 4 ,5 ,6 ,7 ,8 ,9 , a , b , c , d , e , f* 用户密码加密,盐值为:私盐+公盐* @param password 密码* @param salt 私盐* @return MD5加密字符串public static String encryptPassword(String password,String salt){ return encodeByMD5(PUBLIC_SALT+password+salt);* md5加密算法* @param originString* @returnprivate static String encodeByMD5(String originString){if (originString != null){try{//创建具有指定算法名称的信息摘要MessageDigest md = MessageDigest.getInstance( MD5//使用指定的字节数组对摘要进行最后更新,然后完成摘要计算 byte[] results = md.digest(originString.getBytes());//将得到的字节数组变成字符串返回String resultString = byteArrayToHexString(results);return resultString.toUpperCase();} catch(Exception ex){ex.printStackTrace();return null;/*** 转换字节数组为十六进制字符串* @param 字节数组* @return 十六进制字符串private static String byteArrayToHexString(byte[] b){ StringBuffer resultSb = new StringBuffer();for (int i = 0; i b.length; i++){resultSb.append(byteToHexString(b[i]));return resultSb.toString();/** 将一个字节转化成十六进制形式的字符串*/ private static String byteToHexString(byte b){int n = b;if (n 0)n = 256 + n;int d1 = n / 16;int d2 = n % 16;return hexDigits[d1] + hexDigits[d2];}。
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。
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获取md5值的两种⽅法Message Digest Algorithm MD5(中⽂名为消息摘要算法第五版)为计算机安全领域⼴泛使⽤的⼀种散列函数,是⼀种⽐较常⽤的哈希算法。
复制代码代码如下:public class md5_test {//MD5的字符串常量private final static String[] hexDigits = { "0", "1", "2", "3", "4","5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };public static void main(String[] args) {// TODO Auto-generated method stubtry {MessageDigest messageDigest= MessageDigest.getInstance("MD5");System.out.println(byteArrayToHexString(messageDigest.digest("".getBytes())));} catch (NoSuchAlgorithmException e) {// TODO Auto-generated catch blocke.printStackTrace();}}private static String byteArrayToHexString(byte[] b) {StringBuffer resultSb = new StringBuffer();for (int i = 0; i < b.length; i++) {resultSb.append(byteToHexString(b[i]));}return resultSb.toString();}/** 将⼀个字节转化成⼗六进制形式的字符串 */private static String byteToHexString(byte b) {int n = b;if (n < 0)n = 256 + n;int d1 = n / 16;int d2 = n % 16;return hexDigits[d1] + hexDigits[d2];}}复制代码代码如下:import mons.codec.digest.DigestUtils;public class ToMain {public static void main(String[] args) {System.out.println(DigestUtils.md5Hex(""));}}。
MD5的使⽤⽅法MD5加密的Java实现在各种应⽤系统中,如果需要设置账户,那么就会涉及到存储⽤户账户信息的问题,为了保证所存储账户信息的安全,通常会采⽤MD5加密的⽅式来,进⾏存储。
⾸先,简单得介绍⼀下,什么是MD5加密。
MD5的全称是Message-Digest Algorithm 5 (信息-摘要算法),在90年代初,由MIT Laboratory for Computer Scientce 和RSA Data Security Inc 的 Ronald L.Rivest开发出来,经MD2、MD3和MD4发展⽽来。
是让⼤容量信息在⽤数字签名软件签署私⼈密匙前被"压缩"成⼀种保密的格式(就是把⼀个任意长度的字节串变换成⼀定长的⼤整数)。
不管是MD2、MD4还是MD5,它们都需要获得⼀个随机长度的信息并产⽣⼀个128位的信息摘要。
虽然这些算法的结构或多或少有些相似,但MD2的设计与MD4和MD5完全不同,那是因为MD2是为8位机器做过设计优化的,⽽MD4和MD5却是⾯向32位的电脑。
这三个算法的描述和C语⾔源代码在Internet RFCs 1321中有详细的描述,这是⼀份最权威的⽂档,由Ronald L.Rivest在1992年8⽉向IETF提交。
(⼀)消息摘要简介⼀个消息摘要就是⼀个数据块的数字指纹。
即对⼀个任意长度的⼀个数据块进⾏计算,产⽣⼀个唯⼀指印(对于SHA1是产⽣⼀个20字节的⼆进制数组)。
消息摘要是⼀种与消息认证码结合使⽤以确保消息完整性的技术。
主要使⽤单向散列函数算法,可⽤于检验消息的完整性,和通过散列密码直接以⽂本形式保存等,⽬前⼴泛使⽤的算法由MD4、MD5、SHA-1.消息摘要有两个基本属性:1.两个不同的报⽂难以⽣成相同的摘要2.难以对指定的摘要⽣成⼀个报⽂,⽽可以由改报⽂反推算出该指定的摘要代表:美国国家标准技术研究所的SHA1和⿇省理⼯学院Ronald Rivest提出的MD5(⼆)对字符串进⾏加密package test;import java.io.UnsupportedEncodingException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import sun.misc.BASE64Encoder;/*** 对字符串进⾏加密* @param str 待加密的字符串* @return 加密后的字符串* @throws NoSuchAlgorithmException 没有这种产⽣消息摘要的算法* @throws UnsupportedEncodingException*/public class Demo01 {public static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException{//确定算法MessageDigest md5 = MessageDigest.getInstance("MD5");BASE64Encoder base64en = new BASE64Encoder();//加密后的字符串String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));return newstr;}public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {String str = "0123456789";System.out.println(EncoderByMd5(str));}}(三)验证密码是否正确package test;import java.io.UnsupportedEncodingException;import java.security.NoSuchAlgorithmException;/*** 判断⽤户密码是否正确* @param newpasswd ⽤户输⼊的密码* @param oldpasswd 数据库中存储的密码--⽤户密码的摘要* @return* @throws NoSuchAlgorithmException* @throws UnsupportedEncodingException**/public class Demo02 {public static boolean checkpassword(String newpasswd, String oldpasswd) throws NoSuchAlgorithmException, UnsupportedEncodingException{if (Demo01.EncoderByMd5(newpasswd).equals(oldpasswd)) {return true;} else {return false;}}public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {System.out.println("old:"+Demo01.EncoderByMd5("123"));System.out.println("new:"+Demo01.EncoderByMd5("123"));System.out.println(checkpassword("123",Demo01.EncoderByMd5("123")));}}因为MD5是基于消息摘要原理的,消息摘要的基本特征就是很难根据摘要推算出消息报⽂,因此要验证密码是否正确,就必须对输⼊密码(消息报⽂)重新计算其摘要,和数据库中存储的摘要进⾏对⽐(即数据库中存储的其实为⽤户密码的摘要),若两个摘要相同,则说明密码正确,不同,则说明密码错误。
java的md5util.encodemd5string方法Java的MD5Util.encodeMD5String方法是一种常见的加密方法,用于将任意长度的字符串转化成固定长度的MD5值。
在本文中,我们将一步一步地回答有关这个方法的问题,从而全面地了解它的使用和原理。
1. 什么是MD5?MD5(Message-Digest Algorithm 5)是一种广泛使用的哈希函数,常用于对密码或其他敏感信息进行加密。
它产生一个唯一的128位(32个字符)MD5值,不同的输入会产生不同的输出,且无法从MD5值反推出原始数据。
2. 什么是加密方法?加密是一种将数据转化为不可读的密文的过程,以保护数据的安全性。
而加密方法则指用于执行加密操作的算法或函数。
3. MD5Util.encodeMD5String方法的作用是什么?MD5Util.encodeMD5String方法用于将字符串转化为MD5值。
通过将用户输入的字符串进行哈希处理,可以将其变为不可逆的MD5值。
这样一来,即使有人获取了MD5值,也无法从中获取原始数据。
4. 这个方法的使用步骤是什么?使用MD5Util.encodeMD5String方法有以下几个步骤:- 导入MD5Util类。
- 创建一个字符串变量,用来存储需要加密的字符串。
- 调用MD5Util.encodeMD5String方法并传入需要加密的字符串作为参数。
- 获取返回的MD5值并进行后续操作,如存储、比较等。
5. encodeMD5String方法的参数和返回值是什么?encodeMD5String方法的参数是一个字符串类型的明文数据。
它返回一个字符串类型的MD5值,即将明文数据转化后的加密结果。
6. 如何导入MD5Util类?要使用MD5Util类,首先需要确保该类已存在于项目中。
如果该类来自于外部库或框架,则需要先在项目的构建路径中导入相关的依赖。
然后,在Java代码的开头导入MD5Util类。
Java MD5 加密原理一、MD5 简介在计算机领域,MD5(Message Digest Algorithm 5)是一种广泛应用的哈希算法。
它将任意长度的消息作为输入,通过一系列的运算,生成一个128位(16字节)的哈希值。
MD5 由 Ronald Rivest 设计于 1991 年,至今仍被广泛使用。
本文将详细讨论 MD5 加密的原理及其在 Java 中的实现。
二、MD5 加密原理MD5 加密算法的核心思想是将输入的消息分成若干个大小相等的块,并通过一系列的变换,逐步产生最终的哈希值。
具体步骤如下:1. 填充数据首先,需要将输入的消息填充到一个 512 位的块中。
填充规则如下: - 如果消息的长度(以字节为单位)对 512 取余的结果小于 448,需要填充的位数为 448 减去余数; - 如果消息的长度对 512 取余的结果大于 448,则填充的位数为 512减去余数加上 448。
填充后,消息的长度必然是 512 的整数倍。
2. 填充长度在填充数据的末尾,需要附加消息的原始长度(以位为单位),表示消息的实际长度。
原始长度需要用 64 位表示,因此填充长度的过程是将原始长度转换为 64 位的二进制形式,并附加在填充数据之后。
3. 初始化参数MD5 算法还需要定义一些初始参数,包括四个 32 位的寄存器(A、B、C、D),初始时分别对应如下的十六进制值: - A: 0x67452301 - B: 0xEFCDAB89 - C:0x98BADCFE - D: 0x103254764. 循环运算将填充后的消息划分为 N 个 512 位的块,每个块又被划分为 16 个 32 位的子块。
通过循环运算,分别对每个块进行如下的处理: - 将寄存器 A、B、C、D 的当前值分别赋给 a、b、c、d; - 使用子块的数据和一系列的位运算,更新寄存器中的值; - 将更新后的寄存器值赋给 A、B、C、D。
循环运算的次数等于子块的个数。
使⽤JAVA⽣成MD5编码MD5即Message-Digest Algorithm 5(信息-摘要算法5),是⼀种⽤于产⽣数字签名的单项散列算法,在1991年由MIT Laboratory for Computer Science(IT计算机科学实验室)和RSA Data Security Inc(RSA数据安全公司)的Ronald L. Rivest教授开发出来,经由MD2、MD3和MD4发展⽽来。
MD5算法的使⽤不需要⽀付任何版权费⽤。
它的作⽤是让⼤容量信息在⽤数字签名软件签私⼈密匙前被"压缩"成⼀种保密的格式(将⼀个任意长度的“字节串”通过⼀个不可逆的字符串变换算法变换成⼀个128bit的⼤整数,换句话说就是,即使你看到源程序和算法描述,也⽆法将⼀个MD5的值变换回原始的字符串,从数学原理上说,是因为原始的字符串有⽆穷多个,这有点象不存在反函数的数学函数。
)在 Java 中,java.security.MessageDigest 中已经定义了 MD5 的计算,所以我们只需要简单地调⽤即可得到 MD5 的128 位整数。
然后将此 128 位计 16 个字节转换成 16 进制表⽰即可。
代码如下:/**** <p>* Created on 2011-11-25* </p>*/package com.util;import java.io.UnsupportedEncodingException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;/*** 功能:MD5加密算法* 公司名称:夏影* 修改时间:2011-11-15*/public class Md5Encrypt {/*** Used building output as Hex*/private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };/*** 对字符串进⾏MD5加密** @param text* 明⽂** @return密⽂*/public static String md5(String text) {MessageDigest msgDigest = null;try {msgDigest = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException e) {throw new IllegalStateException("System doesn't support MD5 algorithm.");}try {msgDigest.update(text.getBytes("GBK")); //这个加密算法是按照GBK编码进⾏加密} catch (UnsupportedEncodingException e) {throw new IllegalStateException("System doesn't support your EncodingException.");}byte[] bytes = msgDigest.digest();String md5Str = new String(encodeHex(bytes));return md5Str;}public static char[] encodeHex(byte[] data) {int l = data.length;char[] out = new char[l << 1];// two characters form the hex value.for (int i = 0, j = 0; i < l; i++) {out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];out[j++] = DIGITS[0x0F & data[i]];}return out;}}测试代码如下:package com.util;public class TestMD5 {public static void main(String[] args) {// 计算 "a" 的 MD5 代码,应该为:0cc175b9c0f1b6a831c399e269772661System.out.println(Md5Encrypt.md5("a"));}}MD5的典型应⽤是对⼀段Message(字节串)产⽣fingerprint(指纹),以防⽌被"篡改"。
Java常见摘要算法——md5、sha1、sha256⽬录实现sha256的代码和sha1的代码相似摘要算法简介 摘要算法,也是加密算法的⼀种,还有另外⼀种叫法:指纹。
摘要算法就是对指定的数据进⾏⼀系列的计算,然后得出⼀个串内容,该内容就是该数据的摘要。
不同的数据产⽣的摘要是不同的,所以,可以⽤它来进⾏⼀些数据加密的⼯作:通过对⽐两个数据加密后的摘要是否相同,来判断这两个数据是否相同。
还可以⽤来保证数据的完整性,常见的软件在发布之后,会同时发布软件的md5和sha值,这个md5和sha值就是软件的摘要。
当⽤户将软件下载之后,然后去计算软件的摘要,如果计算所得的摘要和软件发布⽅提供的摘要相同,则证明下载的软件和发布的软件⼀模⼀样,否则,就是下载过程中数据(软件)被篡改了。
常见的摘要算法包括:md、sha这两类。
md包括md2、md4、md5;sha包括sha1、sha224、sha256、sha384、sha512。
md5 md摘要算法包括多种算法:分别是md2、md4、md5。
现在⼀般都是使⽤md5进⾏加密。
Java中实现md5加密,有三种⽅式: 使⽤jdk内置的⽅法实现实现md5加密package cn.ganlixin.security;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import mons.codec.binary.Hex;public class JdkMD5 {public static void main(String[] args) throws NoSuchAlgorithmException {String plainText = "this is plain text";// 通过调⽤MessageDigest(数据摘要类)的getInstance()静态⽅法,传⼊加密算法的名称,获取数据摘要对象。
MD5加密算法java实现import ng.reflect.*;/*************************************************md5 类实现了RSA Data Security, Inc.在提交给IETF的RFC1321中的MD5 message-digest 算法。
*************************************************/public class MD5 {/* 下面这些S11-S44实际上是一个4*4的矩阵,在原始的C实现中是用#define 实现的,这里把它们实现成为static final是表示了只读,切能在同一个进程空间内的多个Instance间共享*/static final int S11 = 7;static final int S12 = 12;static final int S13 = 17;static final int S14 = 22;static final int S21 = 5;static final int S22 = 9;static final int S23 = 14;static final int S24 = 20;static final int S31 = 4;static final int S32 = 11;static final int S33 = 16;static final int S34 = 23;static final int S41 = 6;static final int S42 = 10;static final int S43 = 15;static final int S44 = 21;static final byte[] PADDING = { -128, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };/* 下面的三个成员是MD5计算过程中用到的3个核心数据,在原始的C实现中被定义到MD5_CTX结构中*/private long[] state = new long[4]; // state (ABCD)private long[] count = new long[2]; // number of bits, modulo 2^64 (lsb first)private byte[] buffer = new byte[64]; // input buffer/* digestHexStr是MD5的唯一一个公共成员,是最新一次计算结果的 16进制ASCII表示.*/public String digestHexStr;/* digest,是最新一次计算结果的2进制内部表示,表示128bit的MD5值.*/private byte[] digest = new byte[16];/*getMD5ofStr是类MD5最主要的公共方法,入口参数是你想要进行MD5变换的字符串返回的是变换完的结果,这个结果是从公共成员digestHexStr取得的.*/public String getMD5ofStr(String inbuf) {md5Init();md5Update(inbuf.getBytes(), inbuf.length());digestHexStr = "";for (int i = 0; i < 16; i++) {digestHexStr += byteHEX(digest[i]);}return digestHexStr;}// 这是MD5这个类的标准构造函数,JavaBean要求有一个public 的并且没有参数的构造函数public MD5() {md5Init();return;}/* md5Init是一个初始化函数,初始化核心变量,装入标准的幻数 */private void md5Init() {count[0] = 0L;///* Load magic initialization constants.state[0] = 0x67452301L;state[1] = 0xefcdab89L;state[2] = 0x98badcfeL;state[3] = 0x10325476L;return;}/* F, G, H ,I 是4个基本的MD5函数,在原始的MD5的C实现中,由于它们是简单的位运算,可能出于效率的考虑把它们实现成了宏,在java 中,我们把它们实现成了private方法,名字保持了原来C中的。
*/private long F(long x, long y, long z) {return (x & y) | ((~x) & z);}private long G(long x, long y, long z) {return (x & z) | (y & (~z));}private long H(long x, long y, long z) {return x ^ y ^ z;}private long I(long x, long y, long z) {return y ^ (x | (~z));}/*FF,GG,HH和II将调用F,G,H,I进行近一步变换FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent recomputation. */private long FF(long a, long b, long c, long d, long x, long s, long ac) {a += F (b, c, d) + x + ac;a = ((int) a << s) | ((int) a >>> (32 - s));a += b;return a;private long GG(long a, long b, long c, long d, long x, long s, long ac) {a += G (b, c, d) + x + ac;a = ((int) a << s) | ((int) a >>> (32 - s));a += b;return a;}private long HH(long a, long b, long c, long d, long x, long s, long ac) {a += H (b, c, d) + x + ac;a = ((int) a << s) | ((int) a >>> (32 - s));a += b;return a;}private long II(long a, long b, long c, long d, long x, long s, long ac) {a += I (b, c, d) + x + ac;a = ((int) a << s) | ((int) a >>> (32 - s));a += b;return a;/*md5Update是MD5的主计算过程,inbuf是要变换的字节串,inputlen是长度,这个函数由getMD5ofStr调用,调用之前需要调用md5init,因此把它设计成private的*/private void md5Update(byte[] inbuf, int inputLen) {int i, index, partLen;byte[] block = new byte[64];index = (int)(count[0] >>> 3) & 0x3F;// /* Update number of bits */if ((count[0] += (inputLen << 3)) < (inputLen << 3))count[1]++;count[1] += (inputLen >>> 29);partLen = 64 - index;// Transform as many times as possible.if (inputLen >= partLen) {md5Memcpy(buffer, inbuf, index, 0, partLen);md5Transform(buffer);for (i = partLen; i + 63 < inputLen; i += 64) {md5Memcpy(block, inbuf, 0, i, 64);md5Transform (block);}index = 0;} elsei = 0;///* Buffer remaining input */md5Memcpy(buffer, inbuf, index, i, inputLen - i); }/*md5Final整理和填写输出结果*/private void md5Final () {byte[] bits = new byte[8];int index, padLen;///* Save number of bits */Encode (bits, count, 8);///* Pad out to 56 mod 64.index = (int)(count[0] >>> 3) & 0x3f;padLen = (index < 56) ? (56 - index) : (120 - index);md5Update (PADDING, padLen);///* Append length (before padding) */md5Update(bits, 8);///* Store state in digest */Encode (digest, state, 16);}/* md5Memcpy是一个内部使用的byte数组的块拷贝函数,从input的inpos开始把len长度的字节拷贝到output的outpos位置开始*/private void md5Memcpy (byte[] output, byte[] input,int outpos, int inpos, int len){int i;for (i = 0; i < len; i++)output[outpos + i] = input[inpos + i];}/*md5Transform是MD5核心变换程序,有md5Update调用,block 是分块的原始字节*/private void md5Transform (byte block[]) {long a = state[0], b = state[1], c = state[2], d = state[3];long[] x = new long[16];Decode (x, block, 64);/* Round 1 */d = FF (d, a, b, c, x[1], S12, 0xe8c7b756L); /* 2 */c = FF (c, d, a, b, x[2], S13, 0x242070dbL); /* 3 */ b = FF (b, c, d, a, x[3], S14, 0xc1bdceeeL); /* 4 */a = FF (a, b, c, d, x[4], S11, 0xf57c0fafL); /* 5 */d = FF (d, a, b, c, x[5], S12, 0x4787c62aL); /* 6 */c = FF (c, d, a, b, x[6], S13, 0xa8304613L); /* 7 */b = FF (b, c, d, a, x[7], S14, 0xfd469501L); /* 8 */a = FF (a, b, c, d, x[8], S11, 0x698098d8L); /* 9 */ d = FF (d, a, b, c, x[9], S12, 0x8b44f7afL); /* 10 */ c = FF (c, d, a, b, x[10], S13, 0xffff5bb1L); /* 11 */b = FF (b, c, d, a, x[11], S14, 0x895cd7beL); /* 12 */ a = FF (a, b, c, d, x[12], S11, 0x6b901122L); /* 13 */ d = FF (d, a, b, c, x[13], S12, 0xfd987193L); /* 14 */c = FF (c, d, a, b, x[14], S13, 0xa679438eL); /* 15 */ b = FF (b, c, d, a, x[15], S14, 0x49b40821L); /* 16 *//* Round 2 */a = GG (a, b, c, d, x[1], S21, 0xf61e2562L); /* 17 */ d = GG (d, a, b, c, x[6], S22, 0xc040b340L); /* 18 */ c = GG (c, d, a, b, x[11], S23, 0x265e5a51L); /* 19 */b = GG (b, c, d, a, x[0], S24, 0xe9b6c7aaL); /* 20 */d = GG (d, a, b, c, x[10], S22, 0x2441453L); /* 22 */ c = GG (c, d, a, b, x[15], S23, 0xd8a1e681L); /* 23 */ b = GG (b, c, d, a, x[4], S24, 0xe7d3fbc8L); /* 24 */ a = GG (a, b, c, d, x[9], S21, 0x21e1cde6L); /* 25 */ d = GG (d, a, b, c, x[14], S22, 0xc33707d6L); /* 26 */ c = GG (c, d, a, b, x[3], S23, 0xf4d50d87L); /* 27 */ b = GG (b, c, d, a, x[8], S24, 0x455a14edL); /* 28 */ a = GG (a, b, c, d, x[13], S21, 0xa9e3e905L); /* 29 */ d = GG (d, a, b, c, x[2], S22, 0xfcefa3f8L); /* 30 */ c = GG (c, d, a, b, x[7], S23, 0x676f02d9L); /* 31 */ b = GG (b, c, d, a, x[12], S24, 0x8d2a4c8aL); /* 32 *//* Round 3 */a = HH (a, b, c, d, x[5], S31, 0xfffa3942L); /* 33 */ d = HH (d, a, b, c, x[8], S32, 0x8771f681L); /* 34 */ c = HH (c, d, a, b, x[11], S33, 0x6d9d6122L); /* 35 */b = HH (b, c, d, a, x[14], S34, 0xfde5380cL); /* 36 */ a = HH (a, b, c, d, x[1], S31, 0xa4beea44L); /* 37 */ d = HH (d, a, b, c, x[4], S32, 0x4bdecfa9L); /* 38 */c = HH (c, d, a, b, x[7], S33, 0xf6bb4b60L); /* 39 */ b = HH (b, c, d, a, x[10], S34, 0xbebfbc70L); /* 40 */d = HH (d, a, b, c, x[0], S32, 0xeaa127faL); /* 42 */ c = HH (c, d, a, b, x[3], S33, 0xd4ef3085L); /* 43 */ b = HH (b, c, d, a, x[6], S34, 0x4881d05L); /* 44 */ a = HH (a, b, c, d, x[9], S31, 0xd9d4d039L); /* 45 */ d = HH (d, a, b, c, x[12], S32, 0xe6db99e5L); /* 46 */ c = HH (c, d, a, b, x[15], S33, 0x1fa27cf8L); /* 47 */ b = HH (b, c, d, a, x[2], S34, 0xc4ac5665L); /* 48 *//* Round 4 */a = II (a, b, c, d, x[0], S41, 0xf4292244L); /* 49 */d = II (d, a, b, c, x[7], S42, 0x432aff97L); /* 50 */c = II (c, d, a, b, x[14], S43, 0xab9423a7L); /* 51 */ b = II (b, c, d, a, x[5], S44, 0xfc93a039L); /* 52 */a = II (a, b, c, d, x[12], S41, 0x655b59c3L); /* 53 */ d = II (d, a, b, c, x[3], S42, 0x8f0ccc92L); /* 54 */c = II (c, d, a, b, x[10], S43, 0xffeff47dL); /* 55 */b = II (b, c, d, a, x[1], S44, 0x85845dd1L); /* 56 */ a = II (a, b, c, d, x[8], S41, 0x6fa87e4fL); /* 57 */d = II (d, a, b, c, x[15], S42, 0xfe2ce6e0L); /* 58 */ c = II (c, d, a, b, x[6], S43, 0xa3014314L); /* 59 */b = II (b, c, d, a, x[13], S44, 0x4e0811a1L); /* 60 */a = II (a, b, c, d, x[4], S41, 0xf7537e82L); /* 61 */d = II (d, a, b, c, x[11], S42, 0xbd3af235L); /* 62 */c = II (c, d, a, b, x[2], S43, 0x2ad7d2bbL); /* 63 */b = II (b, c, d, a, x[9], S44, 0xeb86d391L); /* 64 */state[0] += a;state[1] += b;state[2] += c;state[3] += d;}/*Encode把long数组按顺序拆成byte数组,因为java的long类型是64bit的,只拆低32bit,以适应原始C实现的用途*/private void Encode (byte[] output, long[] input, int len) {int i, j;for (i = 0, j = 0; j < len; i++, j += 4) {output[j] = (byte)(input[i] & 0xffL);output[j + 1] = (byte)((input[i] >>> 8) & 0xffL);output[j + 2] = (byte)((input[i] >>> 16) & 0xffL);output[j + 3] = (byte)((input[i] >>> 24) & 0xffL);}}/*Decode把byte数组按顺序合成成long数组,因为java的long 类型是64bit的,只合成低32bit,高32bit清零,以适应原始C实现的用途*/private void Decode (long[] output, byte[] input, int len) {int i, j;for (i = 0, j = 0; j < len; i++, j += 4)output[i] = b2iu(input[j]) |(b2iu(input[j + 1]) << 8) |(b2iu(input[j + 2]) << 16) |(b2iu(input[j + 3]) << 24);return;}b2iu是我写的一个把byte按照不考虑正负号的原则的"升位"程序,因为java没有unsigned运算*/public static long b2iu(byte b) {return b < 0 ? b & 0x7F + 128 : b;}/*byteHEX(),用来把一个byte类型的数转换成十六进制的ASCII表示,因为java中的byte的toString无法实现这一点,我们又没有C语言中的sprintf(outbuf,"%02X",ib)*/public static String byteHEX(byte ib) {char[] Digit = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };char [] ob = new char[2];ob[0] = Digit[(ib >>> 4) & 0X0F];ob[1] = Digit[ib & 0X0F];String s = new String(ob);return s;public static void main(String args[]) {MD5 m = new MD5();if (Array.getLength(args) == 0) { //如果没有参数,执行标准的Test SuiteSystem.out.println("MD5 Test suite:");System.out.println("MD5(\"\"):"+m.getMD5ofStr(""));System.out.println("MD5(\"a\"):"+m.getMD5ofStr("a"));System.out.println("MD5(\"abc\"):"+m.getMD5ofStr("abc"));System.out.println("MD5(\"message digest\"):"+m.getMD5of Str("message digest"));System.out.println("MD5(\"abcdefghijklmnopqrstuvwxyz\"):" +m.getMD5ofStr("abcdefghijklmnopqrstuvwxyz"));System.out.println("MD5(\"ABCDEFGHIJKLMNOPQRSTU VWXYZabcdefghijklmnopqrstuvwxyz0123456789\"):"+m.getMD5ofStr("ABCDEFGHIJKLMNOPQRSTUVWXY Zabcdefghijklmnopqrstuvwxyz0123456789"));}elseSystem.out.println("MD5(" + args[0] + ")=" + m.getMD5o fStr(args[0]));}}。