安全需要 編寫程序時少不了對密碼的加密
MD5加密
首先把字符串轉換爲相應的byte,之後創建方法
MessageDigest mdInit = MessageDigest.getInstance("md5")
聲明採用MD5加密算法,對傳入的字節碼進行MD5加密byte[] btInput =md5.digest(s),得到一個字節數組,得到字節數組之後,可以自己定義一個16位的char類型的數組,裏面的值可以自己定義。char[] c ={‘0’,‘1’,‘2’,‘3’,‘4’,‘5’,‘6’,‘7’,‘8’,‘9’,‘A’,‘B’,‘C’,‘D’,‘E’,‘F’};。然後用定義的這個數組來轉換密碼。
public static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] btInput = s.getBytes();
// 獲得MD5摘要算法的 MessageDigest 對象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字節更新摘要
mdInst.update(btInput);
// 獲得密文
byte[] md = mdInst.digest();
// 把密文轉換成十六進制的字符串形式
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) {
e.printStackTrace();
return null;
}
}