|
作为最常用的两种基于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); }
}
|
一共有 0 条评论