JAVA SHA256加密程式碼實現
//這裡對密碼進行加密,再存到資料庫
String password3=StringEncrypt.Encrypt(password);
//SHA256加密演算法
public static class StringEncrypt {
/**
* 對字串加密,加密演算法使用MD5,SHA-1,SHA-256,預設使用SHA-256
*
* @param strSrc
* 要加密的字串
* @param encName
* 加密型別
* @return
*/
public static String Encrypt(String strSrc) {
MessageDigest md = null;
String strDes = null;
String encName="SHA-256";
byte[] bt = strSrc.getBytes();
try {
md = MessageDigest.getInstance(encName);
md.update(bt);
strDes = bytes2Hex(md.digest()); // to HexString
} catch (NoSuchAlgorithmException e) {
return null;
}
return strDes;
}
public static String bytes2Hex(byte[] bts) {
String des = "";
String tmp = null;
for (int i = 0; i < bts.length; i++) {
tmp = (Integer.toHexString(bts[i] & 0xFF));
if (tmp.length() == 1) {
des += "0";
}
des += tmp;
}
return des;
}
}