java使用md5加密方法
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5 {
// * 生成32位md5碼
// * @param password
// * @return
// */
public static String m1(String password) {
try {
// 得到一個(gè)信息摘要器
MessageDigest digest = MessageDigest.getInstance("md5");
byte[] result = digest.digest(password.getBytes());
StringBuffer buffer = new StringBuffer();
// 把每一個(gè)byte 做一個(gè)與運(yùn)算 0xff;
for (byte b : result) {
// 與運(yùn)算
int number = b & 0xff;// 加鹽
String str = Integer.toHexString(number);
if (str.length() == 1) {
buffer.append("0");
}
buffer.append(str);
}
// 標(biāo)準(zhǔn)的md5加密后的結(jié)果
return buffer.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
public static String m2(String key){
char hexDigits[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
try {
byte[] btInput = key.getBytes();
// 獲得MD5摘要算法的 MessageDigest 對(duì)象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字節(jié)更新摘要
mdInst.update(btInput);
// 獲得密文
byte[] md = mdInst.digest();
// 把密文轉(zhuǎn)換成十六進(jìn)制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
}import java.security.MessageDigest;
public class Sha1 {
public static String s1(String inStr) throws Exception {
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance("SHA");
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
return "";
}
byte[] byteArray = inStr.getBytes("UTF-8");
byte[] md5Bytes = sha.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
}