MD5-java

合集下载

Java文件完整性校验MD5sha1sha256sha224sha384sha512

Java文件完整性校验MD5sha1sha256sha224sha384sha512

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中常用的md5方法

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加密及解密的代码实例分享

Java实现MD5加密及解密的代码实例分享

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校验码方式比较两个文件是否相同

java使用计算md5校验码方式比较两个文件是否相同

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

java实现计算MD5

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用法

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版,编码问题)

对中文进行MD5加密的注意事项(Java版,编码问题)

对中⽂进⾏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 标准的md5

java 标准的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) {。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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]));}}。

相关文档
最新文档