博主资料

留言 加为好友 收藏

用户名:  moonstone2007
来自:  浙江 杭州

文章搜索

文章列表

最近访问的人:

满庭芳
2008-10-04 13:52:46
常州赛维思环境试..
2008-09-30 16:17:41
sdgjhgekjuiwe
2008-06-14 15:34:54
泌尿系结石
2008-06-03 14:15:13
兵,器
2008-06-03 10:04:56
电子商务研究(B2C)
2008-06-02 15:12:38
直流电源,直流稳压..
2008-06-02 11:17:38
玩ERP
2008-06-02 08:32:57
李雪
2008-05-14 15:29:59
三笑数码科技--电..
2008-05-14 15:17:37

日志文章

2007年05月07日 23:52:01

利用Java API实现MD5与SHA加密

作为最常用的两种基于Hash算法的单向加密技术,MD5与SHA已经得到广泛的应用。Java API对此也提供了MessageDigest类予以支持。就信息系统的实践而言,这两种加密技术的不可逆特征对于保护信息的私密性与完整性是有重要意义的,尤其在网络计算环境下,信息传输可能被劫持、篡改、存储、转发,此时以digest的方式进行信息验证,不失为确认信息完整性的有效途径。

目前流行的Acegi也为MD5与SHA提供了支持,尤其是对于用户密码的数据库存储。在与Spring配合使用时,开发人员能够简单地通过PasswordDaoAuthenticator类实现对用户身份的确认。

下述源代码是一个简单且实用的MD5/SHA实现,其中利用了J2SE的MessageDigest:


import java.math.BigInteger;
import java.security.MessageDigest;

public class Encrypt
{

 
  public String MD5(String s)
    throws Exception
  {
    String s1 = "";
    if(s.trim() == null)
        return "null";
    try
    {
        s1 = System.getProperty("MD5.algorithm", "MD5");
    }
    catch(SecurityException _ex) { }
    MessageDigest messagedigest = MessageDigest.getInstance(s1);
    byte abyte0[] = s.getBytes();
    for(int i = 0; i < s.length(); i++)
        messagedigest.update(abyte0, 0, i);

    byte abyte1[] = messagedigest.digest();
    BigInteger biginteger = new BigInteger(abyte1);
    return biginteger.toString(16);
  }

  public String SHA(String s)
    throws Exception
  {
    String s1 = "";
    if(s.trim() == null)
        return "null";
    try
    {
        s1 = System.getProperty("SHA.algorithm", "SHA");
    }
    catch(SecurityException _ex) { }
    MessageDigest messagedigest = MessageDigest.getInstance(s1);
    byte abyte0[] = s.getBytes();
    messagedigest.update(abyte0);
    byte abyte1[] = messagedigest.digest();
    BigInteger biginteger = new BigInteger(abyte1);
    return biginteger.toString(32);
  }

 
}

Tags: 加密   MD5   SHA   Spring  

类别: 软件开发技术 |  评论(0) |  浏览(2989) |  收藏
发表评论
看不清楚,换一张