1. 程式人生 > >使用MD5對明文密碼進行加密

使用MD5對明文密碼進行加密

通常情況下,我們不希望任何人知道我們的密碼。

當我們建立了使用者以後,我們的個人資訊將會儲存在伺服器資料庫中,如果有人可以訪問資料庫,便可以輕易的拿到我們的使用者名稱和密碼等一系列重要資料。為防止這種情況,我們可以使用加密的方式對密碼進行加密。

以下是StringUtils工具類,創建出來以後我們可以呼叫encrypt方法將password傳入,並接受返回出來的心得newPassword,然後將newPassword存入資料庫中,當登入時,則是轉換後的newPassword跟資料庫中儲存的password比較,即便系統管理員查看了資料庫中的使用者資訊,也無法根據儲存的password計算出我們登入時所填寫的密碼。因此便增加了資料的安全性。

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class StringUtils {

	/**
	 * Used by the hash method.
	 */
	private static MessageDigest digest = null;

	/**
	 * 利用MD5演算法雜湊字串作為一個十六進位制數的字串返回結果。
	 * @param data
	 * @return
	 */
	public synchronized static final String hash(String data) {
		if (digest == null) {
			try {
				digest = MessageDigest.getInstance("MD5");
			} catch (NoSuchAlgorithmException nsae) {
				System.err.println("Failed to load the MD5 MessageDigest. "
						+ "Jive will be unable to function normally.");
			}
		}
		// Now, compute hash.
		digest.update(data.getBytes());
		return encodeHex(digest.digest());
	}

	/**
	 * 返回一個字串的加密形式。 MD5 演算法
	 */
	public static String encrypt(String originalStr) {
		if (originalStr == null) {
			originalStr = "";
		}
		return hash(originalStr);
	}

	/**
	 * 將位元組陣列變成一個字串,表示每個位元組為一個無符號十六進位制數。
	 * @param bytes
	 * @return
	 */
	public static final String encodeHex(byte[] bytes) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		int i;

		for (i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buf.toString();
	}
	
}