MD5與SHA-1兩種算法使用

   隨着信息技術和Internet 的迅速發展,信息安全和可靠性問題愈來愈重要。如今信息安全面臨兩大基本攻擊:被動式攻擊(獲取消息的內容、業務流分析)和主動攻擊(假冒、消息的篡改、業務拒絕)。前者主要靠加密和解密技術進行有效處理,然後者就要靠消息認證來處理。在金融交易、電子商務、電子信件、手機用戶信息的確認等領域,數據完整性確認和數據來源的真僞鑑定都是很重要的安全服務。實現這些安全服務的最好方法就是使用加密函數中的單項散列(Hash)函數。單項散列(Hash)函數是一種單項密碼體制,它是一個從明文到密文的不可逆函數,也就是說,是沒法解密的。一般應用在只須要加密、不須要解密的特殊應用場合。單項散列(Hash)函數H(M)做用於一任意長度的消息M,它返回一固定長度的散列值h:h=H(M)做爲初始消息的獨一無二的「數字指紋」,從而能保證數據的完整性和唯一性。 java

1.MD5與SHA-1的比較

   因爲MD5 與SHA-1均是從MD4 發展而來,它們的結構和強度等特性有不少類似之處,表(1)是對MD5 與SHA-1 的結構比較。SHA-1與MD5 的最大區別在於其摘要比MD5 摘要長 32 比特。對於強行攻擊,產生任何一個報文使之摘要等於給定報文摘要的難度:MD5 是2128 數量級的操做,SHA-1 是2160 數量級的操做。產生具備相同摘要的兩個報文的難度:MD5是 264 是數量級的操做,SHA-1 是280 數量級的操做。於是,SHA-1 對強行攻擊的強度更大。但因爲SHA-1 的循環步驟比MD5 多(80:64)且要處理的緩存大(160 比特:128 比特),SHA-1 的運行速度比MD5 慢。git

2.算法使用

/**
	 * MD5字符串加密
	 * 
	 * @param str
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public final static String md5(String str) throws NoSuchAlgorithmException {
		final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		byte[] btInput = str.getBytes();
		// 得到MD5摘要算法的 MessageDigest 對象
		MessageDigest md5Inst = MessageDigest.getInstance("MD5");
		// 使用指定的字節更新摘要
		md5Inst.update(btInput);
		// 得到密文
		byte[] bytes = md5Inst.digest();
		StringBuilder strResult = new StringBuilder();
		// 把密文轉換成十六進制的字符串形式
		for (int i = 0; i < bytes.length; i++) {
			strResult.append(hexDigits[(bytes[i] >> 4) & 0x0f]);
			strResult.append(hexDigits[bytes[i] & 0x0f]);
		}
		return strResult.toString();
	}
/**
	 * SHA-1字符串加密
	 * 
	 * @param str
	 * @return
	 * @throws NoSuchAlgorithmException 
	 */
	public final static String sha1(String str) throws NoSuchAlgorithmException {
		final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		byte[] btInput = str.getBytes();
		// 得到SHA-1摘要算法的 MessageDigest 對象
		MessageDigest sha1Inst = MessageDigest.getInstance("SHA-1");
		// 使用指定的字節更新摘要
		sha1Inst.update(btInput);
		// 得到密文
		byte[] bytes = sha1Inst.digest();

		StringBuffer strResult = new StringBuffer();
		// 把密文轉換成十六進制的字符串形式
		for (int i = 0; i < bytes.length; i++) {
			strResult.append(hexDigits[(bytes[i] >> 4) & 0x0f]);
			strResult.append(hexDigits[bytes[i] & 0x0f]);
		}
		return strResult.toString();
	}
相關文章
相關標籤/搜索