1. 程式人生 > >先sha256後base64加密 java

先sha256後base64加密 java

 先sha256後base64加密例項:

String password = "a123456";
password = SaltUtils.encryptPassword(password);
public class SaltUtils {
	/**
	 * 
	 * @param password 原始密碼
	 * @return
	 */
	public static String encryptPassword(String password){
		byte[] hashBytes = SHA256Utils.SHA(password);
		return Base64.toBase64String(SHA256Utils.bytetoHex(hashBytes).getBytes());  
	}
	
}
public class SHA256Utils {

	private static final String strType = "SHA-256";

	/***
	 * 字串 SHA 加密
	 * 
	 * @param strSourceText
	 * @return
	 */
	public static byte[] SHA(final String strText) {
		// 是否是有效字串
		if (strText != null && strText.length() > 0) {
			try {
				// SHA 加密開始
				// 建立加密物件 並傳入加密型別
				MessageDigest messageDigest = MessageDigest.getInstance(strType);
				// 傳入要加密的字串
				messageDigest.update(strText.getBytes());
				// 得到 byte 型別結果
				return messageDigest.digest();

			} catch (NoSuchAlgorithmException e) {
				return null;
			}
		}else{
			return null;
		}

	}
	
	/**
     * 將byte轉為16進位制
     * @param bytes
     * @return
     */
    public static String bytetoHex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < bytes.length; i++){
            String temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1){
                //16進位制數值長度為2,長度為1時補0
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}