使用MD5对数据库密码进行加密的实例
package com.lxitedu.tools.generate;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.dcivision.framework.Crypt;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
/**
* suit the php
*
* @author Administrator
*
*/
public class MD5 {
// 解密类: Crypt
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) throws Exception {
getMD5EncryptedString("");
String encrptedPwd = Crypt.encrypt("diaoer",
SystemParameterFactory.getSystemParameter(SystemParameterConstant.CRYPTO_SALT));
System.out.println(getMD5EncryptedString("diaoer"));
System.out.println(encrptedPwd);
}
public static String getMD5EncryptedString(String sourceString) throws NoSuchAlgorithmException {
// 加密后的字符串
// 创建具有指定算法名称的信息摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 使用指定的字节数组对摘要进行最后更新,然后完成摘要计算
byte[] results = md.digest(sourceString.getBytes());
return byteArrayToHexString(results);
}
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];
}
}
解密:
/*
* @(#)Crypt.java
*
* Copyright (c) 2003 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
*/
package com.dcivision.framework;
/**
* Crypt.java
*
* This class is to provide encrypt and decrypt function by a password provided.
*
* @author Rollo Chan
* @company DCIVision Limited
* @creation date 25/06/2003
* @version $Revision: 1.6 $
*/
public class Crypt {
public static final String REVISION = "$Revision: 1.6 $";
private Crypt() {
}
/**
* encrypt
*
* Encrypt a string with a password
*
* @param buffer
* The buffer to be encrypted
* @param password
* The password