iT邦幫忙

2025 iThome 鐵人賽

DAY 8
0
自我挑戰組

從0開始學習Java系列 第 8

java.security 練習 Hashing (MD5 加密)

  • 分享至 

  • xImage
  •  

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

public class SecurityTest1 {
	public static void main(String[] args) {
		// 假設這是我們要加密的原始字串
		String originalString = "This is a test string for MD5 hashing";

		System.out.println("原始字串: " + originalString);

		// 注意:hash 方法需要 byte[] 陣列,所以我們用 .getBytes() 來轉換
		String md5Hash = hash(originalString.getBytes(), "MD5");

		System.out.println("MD5 加密後 (32位元長度): " + md5Hash);

		// 你可以試試看,即使只改一個字,產生的 MD5 也會完全不同
		String changedString = "This is a test string for MD5 hashing."; // 多了一個句點
		String anotherMd5Hash = hash(changedString.getBytes(), "MD5");
		System.out.println("改變一個字後的 MD5: " + anotherMd5Hash);
	};


	private final static char[] hexArray = "0123456789ABCDEF".toCharArray();

	/**
	 * 將 byte array 資料做 hash md5或 sha256 運算,並回傳 hex值的字串資料
	 */
	private final static String hash(byte data[], String mode) {
		MessageDigest md = null;
		try {
			if (mode.equals("MD5")) {
				md = MessageDigest.getInstance("MD5");
			} else if (mode.equals("SHA-256")) {
				md = MessageDigest.getInstance("SHA-256");
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return bytesToHex(md.digest(data));
	}

	/**
	 * 將 byte array 資料轉換成 hex字串值
	 */
	private final static String bytesToHex(byte[] bytes) {
		char[] hexChars = new char[bytes.length * 2];
		for (int j = 0; j < bytes.length; j++) {
			int v = bytes[j] & 0xFF;
			hexChars[j * 2] = hexArray[v >>> 4];
			hexChars[j * 2 + 1] = hexArray[v & 0x0F];
		}
		return new String(hexChars);
	}
}

參考資料
https://developers.ecpay.com.tw/


上一篇
java socket 小範例
下一篇
練習 URL 編碼
系列文
從0開始學習Java21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言