(转帖)一个实现MD5的简洁的java类

来自:http://www.javaresearch.org/article/showarticle.jsp?column=33&thread=10461

×××××××××××××××××××××××××××××××××××××××××××××××××××××

                         正文

一个实现MD5的简洁的java类

Jagie 原创  (参与分:100322,专家分:3090)   发表:2003-11-18 17:14   更新:2003-11-19 08:34   版本:1.0   阅读:6307次 

 

关键词:md5

由于消息摘要唯一性和不可逆性的特点,所以不失为一种简单的常用的加密手段,比如你可以用md5来加密你的应用中的用户口令。

package test;

import java.security.MessageDigest;

/**

 * <p>Title: </p>

 * <p>Description: </p>

 * <p>Copyright: Copyright (c) 2003</p>

 * <p>Company: </p>

 * @author unascribed

 * @version 1.0

 */

public class StringUtil {

  private final static String[] hexDigits = {

      "0", "1", "2", "3", "4", "5", "6", "7",

      "8", "9", "a", "b", "c", "d", "e", "f"};

  /**

   * 转换字节数组为16进制字串

   * @param b 字节数组

   * @return 16进制字串

   */

  public 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];

  }

  public static String MD5Encode(String origin) {

    String resultString = null;

    try {

      resultString=new String(origin);

      MessageDigest md = MessageDigest.getInstance("MD5");

      resultString=byteArrayToHexString(md.digest(resultString.getBytes()));

    }

    catch (Exception ex) {

    }

    return resultString;

  }

  public static void main(String[] args){

    System.err.println(MD5Encode("a"));

  }

}

在RFC 1321中,给出了Test suite用来检验你的实现是否正确:

MD5 ("") = d41d8cd98f00b204e9800998ecf8427e

MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661

MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72

MD5 ("message digest") = f96b697d7cb7938d525a2f31aaf161d0

MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b

参考资料:《java security handbook》 jamie jaworski

版权声明   给作者写信  本篇文章对您是否有帮助?  投票: 是    否     投票结果:     24       1

 

 

 

作者其它文章:

在MIDP2.0中操作图片像素

用MMAPI拍照

如何在Swing中实现文件路径选择的TableCellEditor

MIDP中一个简单的折行文本绘制办法

在MIDP1.0下实现图片翻转

作者全部文章 

 

 

  评论人:yipsilon    参与分: 15609    专家分: 290    来自: Dalian

 发表时间: 2003-11-20 19:29 

使用这种方式的前提是必需有JCE支持。如果在J2SDK 1.3中,则必需下载额外的jce包。 

 

  评论人:Jagie    参与分: 100322    专家分: 3090    来自: 北京

 发表时间: 2003-11-21 11:11 

java.security.MessageDigest是jdk自带的,无需使用javax.crypto包,所以无需下载jce.

至少我在运行这个例子的时候就没有下载jce

 

 

  评论人:rower    参与分: 167    专家分: 0  发表时间: 2004-04-10 17:10 

实际测试,在J2SDK 1.3中无需下载额外的jce包,运行良好。 

 

  评论人:huangyafei    参与分: 80    专家分: 0  发表时间: 2005-03-06 13:41 

怎么我在运行上面的程序的时候出错了:出错信息为:

D:\works\java\MD5Encode.java:12: class StringUtil is public, should be declared in a file named StringUtil.java

public class StringUtil {

       ^

1 error

 

 

  评论人:yifenggege    参与分: 259    专家分: 70  发表时间: 2005-07-13 14:12 

好! 

 

  评论人:keli    参与分: 34262    专家分: 1320  发表时间: 2005-11-16 17:24 

加密是可以的,但是解密就难了。呵呵。

我看第5个答复想笑,哈哈哈哈。 

 

  评论人:gui_jq    参与分: 73813    专家分: 1070    来自: 广州天河

 发表时间: 2005-12-01 18:28 

写得不错,我最近要写个radius协议分析的工具想用java来编写,所以第一得弄java下面的MD5实现,没有想到如此简单,jdk原来就带有了,最坏的打算我还想用c的代码改一个呢。呵呵。在这里我补充一下:

1,MD5本来就是不可逆的,加密只是保证在网络传输中内容不被修改,可以通过md5来检查,防止有人修改包内容进行模仿发包,所以服务端在受到包写更加对方的算法来md5一次然后在处理包内容,如果不通过则直接丢弃包。另外就是用来验证下载的重要文件是否正确和完整。

2,程序中的打印16进制方法有点欠妥,在c里面可以通过printf("%02x",buf[])就可以,但是java对byte的处理没有这个。所以我推荐下面的方法:

private static String dumpBytes(byte[] bytes) {

    int i;

    StringBuffer sb = new StringBuffer();

    for (i = 0; i < bytes.length; i++) {

      if (i % 32 == 0 && i != 0) {

        sb.append("\n");

      }

      String s = Integer.toHexString(bytes[i]);

      if (s.length() < 2) {

        s = "0" + s;

      }

      if (s.length() > 2) {

        s = s.substring(s.length() - 2);

      }

      sb.append(s);

    }

    return sb.toString();

  }

这个更加灵活高效。

补充结束。谢谢大家。呵呵。 

 

 

JAVA开发者应该去的20个英文网站-转贴

JAVA开发者应该去的20个英文网站-转贴  发表时间: 2005-05-16 17:52  

 

[http://www.javaalmanac.com] - Java开发者年鉴一书的在线版本. 要想快速查到某种Java技巧的用法及示例代码, 这是一个不错的去处.

[http://www.onjava.com] - O'Reilly的Java网站. 每周都有新文章.

[http://java.sun.com] - 官方的Java开发者网站 - 每周都有新文章发表.

[http://www.developer.com/java] - 由Gamelan.com 维护的Java技术文章网站.

[http://www.java.net] - Sun公司维护的一个Java社区网站.

[http://www.builder.com] - Cnet的Builder.com网站 - 所有的技术文章, 以Java为主.

[http://www.ibm.com/developerworks/java] - IBM的Developerworks技术网站; 这是其中的Java技术主页.

[http://www.javaworld.com] - 最早的一个Java站点. 每周更新Java技术文章.

[http://www.devx.com/java] - DevX维护的一个Java技术文章网站.

[http://www.fawcette.com/javapro] - JavaPro在线杂志网站.

[http://www.sys-con.com/java] - Java Developers Journal的在线杂志网站.

[http://www.javadesktop.org] - 位于Java.net的一个Java桌面技术社区网站.

[http://www.theserverside.com] - 这是一个讨论所有Java服务器端技术的网站.

[http://www.jars.com] - 提供Java评论服务. 包括各种framework和应用程序.

[http://www.jguru.com] - 一个非常棒的采用Q&A形式的Java技术资源社区.

[http://www.javaranch.com] - 一个论坛,得到Java问题答案的地方,初学者的好去处。

[http://www.ibiblio.org/javafaq/javafaq.html] - comp.lang.java的FAQ站点 - 收集了来自comp.lang.java新闻组的问题和答案的分类目录.

http://java.sun.com/docs/books/tutorial/] - 来自SUN公司的官方Java指南 - 对于了解几乎所有的java技术特性非常有帮助.

http://www.javablogs.com] - 互联网上最活跃的一个Java Blog网站.

http://java.about.com/] - 来自About.com的Java新闻和技术文章网站.

 

基础问题出错:String的split(String str)方法用法

  如果一行只有一个回车换行符,那么这行用这个方法分开得到是一个0长度字符串,

下面这一句:

        if (charArray[0] != ' ') {

        sB.append(lineStr);

        sB.append("<br>");

      }

  就会出现indexOutOfBoundary这样的错误。

    //replace space at beginning and add "<br>" at end of every line

    String[] strArray = tempStr.split("\n");

    StringBuffer sB = new StringBuffer();

    for (int i = 0; i < strArray.length; i++) {

      String lineStr = strArray[i];

      //System.out.println(i +" : lineStr is: " + lineStr+"ok");

      char[] charArray = lineStr.toCharArray();

 

      //if no any char in this line,then add a <br> to the end of sB,

      //continue loop(don't excute the code behind continue in this loop).

      if (charArray.length == 0){

        sB.append("<br>");

        //System.out.println("come here.");

        continue;

      } 

     

      if (charArray[0] != ' ') {

        sB.append(lineStr);

        sB.append("<br>");

      }

完整代码:

package com.learndiary.website.util;

//import com.learndiary.util.*;

public class Util {

   

  public static String htmlFormat(String source) {

    //if (source==null) return null;//WHEN the source is "",run at line 33,will happen ArrayIndexOutOfBoundsException.

    //because char[0] don't exist a charactor.

    if ((source==null)||(source.length()==0)) return "";

    //replace "<>"

    String tempStr = source.replaceAll("<", "<").replaceAll(">", ">");

   

    //replace space at beginning and add "<br>" at end of every line

    String[] strArray = tempStr.split("\n");

    StringBuffer sB = new StringBuffer();

    for (int i = 0; i < strArray.length; i++) {

      String lineStr = strArray[i];

      //System.out.println(i +" : lineStr is: " + lineStr+"ok");

      char[] charArray = lineStr.toCharArray();

 

      //if no any char in this line,then add a <br> to the end of sB,

      //continue loop(don't excute the code behind continue in this loop).

      if (charArray.length == 0){

        sB.append("<br>");

        //System.out.println("come here.");

        continue;

      } 

     

      if (charArray[0] != ' ') {

        sB.append(lineStr);

        sB.append("<br>");

      } else {

      for (int j = 0; j < charArray.length; j++) {//if the first char of this String is space,need convert the first space to " "

        if (charArray[j] == ' ')//if there are several spaces at the begin of this String,need convert every space to " ".

          sB.append(" ");  

          else {//once meet a char isn't a space,then every space after this char needn't to be converted to " " in this string.

                //we can add the all charaters after this char,then ,add "<br>" to the end of this String.

            sB.append(charArray, j, charArray.length - j);

            //sB.append("<br>");

            break;

          }

        }

        sB.append("<br>");//need add " " to the end of this string.why put this sentence at here?

                          //if every character is space in this string,it also needs adding "<br>" at the end of this string.

      }

    }

   

    String resultTemp = sB.toString();

    String result = resultTemp.substring(0, resultTemp.length() - 4);       

    return result;

    //replaceAll(" ", " ").

  } 

 

  // Simple test:

  /* 

  public static void main(String[] args) throws Exception {

    String file = TextFile.read("gb5.txt");

    System.out.println("file is: \n" + file);

    String result = htmlFormat(file);

    System.out.println("result is \n" + result);

    write("test.txt", file);

    TextFile text = new TextFile("test.txt");

    text.write("test2.txt");

  }

   */

}

jdk1.4的文档:(还没有看懂,记在这里,慢慢看)

split

public String[] split(String regex,

                      int limit)

Splits this string around matches of the given regular expression.

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

The string "boo:and:foo", for example, yields the following results with these parameters:

Regex Limit Result

: 2 { "boo", "and:foo" }

: 5 { "boo", "and", "foo" }

: -2 { "boo", "and", "foo" }

o 5 { "b", "", ":and:f", "", "" }

o -2 { "b", "", ":and:f", "", "" }

o 0 { "b", "", ":and:f" }

An invocation of this method of the form str.split(regex, n) yields the same result as the expression

Pattern.compile(regex).split(str, n)

Parameters:

regex - the delimiting regular expression

limit - the result threshold, as described above

Returns:

the array of strings computed by splitting this string around matches of the given regular expression

Throws:

PatternSyntaxException - if the regular expression's syntax is invalid

Since:

1.4

See Also:

Pattern

--------------------------------------------------------------------------------

split

public String[] split(String regex)

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result

: { "boo", "and", "foo" }

o { "b", "", ":and:f" }

Parameters:

regex - the delimiting regular expression

Returns:

the array of strings computed by splitting this string around matches of the given regular expression

Throws:

PatternSyntaxException - if the regular expression's syntax is invalid

Since:

1.4

See Also:

Pattern

String类中concat(String str)方法的使用问题

这里的参数str是不能为null的,否则会出现:java.lang.NullPointerException错误,

如:   String currentURL = request.getServletPath().concat("?").concat(request.getQueryString());

 System.out.println("currentURL is: " + currentURL);

如果:request.getQueryString()==null,就会报错。

查看jdk1.4中String.java的源码如下:

    public String concat(String str) {

int otherLen = str.length();//这里首先检索新字符串的长度,所以str不能为null.

if (otherLen == 0) {

    return this;

}

char buf[] = new char[count + otherLen];

getChars(0, count, buf, 0);

str.getChars(0, otherLen, buf, count);

return new String(0, count + otherLen, buf);

    }

所以:如果不知道一个字符串是否会为null,而且不再乎字符串中会跟一个null,就不应该用这种方法,可以这样用:

String currentURL = request.getServletPath().concat("?")+ request.getQueryString();

System.out.println("currentURL is: " + currentURL);

结果为:currentURL is: /bulletinAction.do?null

jdk1.4APIDOC中这个方法的文档:

concat

public String concat(String str)

Concatenates the specified string to the end of this string.

If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.

Examples:

 "cares".concat("s") returns "caress"

 "to".concat("get").concat("her") returns "together"

 

Parameters:

str - the String that is concatenated to the end of this String.

Returns:

a string that represents the concatenation of this object's characters followed by the string argument's characters.

暑假学习

今天接到老板的电话,知道暑假不能回家了,要去宁波那边做项目了。还说要用java编程的,关于java,我只粗略的看过一些书,具体没动手做过,她在电话跟我说用java实现的什么什么,我脑子里真是一点概念都没有。但我真的很想向老板证明一下自己的实力。明天最后一门考试,本来完了想回家的,但现在看来学java才是正道,等到她让我编程的时候,我还说要看看书,那不是完了,但我知道java不是几天能够学成的,有高手可指教否,我的qq:5826807

我加入这个学习日记小组,是为了学习更多的知识,也磨炼一下自己,我很想学习JAVA和英语方面的知识,有利于我以后的发展需要,我也很希望能为你们做点什么,但是,我的专业知识还很弱,我希望能在此实现我现在的目标,以后,还请你们多多帮助了啊 ,我在此谢谢你们。