1
0

More than 1 year has passed since last update.

Javaでハッシュ値を生成する

Last updated at Posted at 2023-01-07

JavaでSHA1, SHA256のハッシュ値を作成するには、MessageDigestクラスを使用します。

byte配列を16進数文字列で出力する

Java17から標準クラスライブラリであるHexFormatクラスでbyte配列を16進数文字列で変換することが出来るようになりました。

サンプルプログラム

SHA1, SHA256アルゴリズムでハッシュ値を生成し、出力するプログラムです。

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;

public class HelloWorld_SHA {

	public static void main(String[] args) {

		// SHA-1
		try {
			MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
			byte[] sha1Byte = sha1.digest("Hello World".getBytes());
			
			//Java17以降からしか使用出来ない
			HexFormat hex = HexFormat.of().withLowerCase();
			String hexString = hex.formatHex(sha1Byte);
			System.out.println("SHA1");
			System.out.println(hexString);
		}
		catch (NoSuchAlgorithmException e) {
			
		}
		
		// SHA-256
		try {
			MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
			byte[] sha256Byte = sha256.digest("Hello World".getBytes());
			
			//Java17以降からしか使用出来ない
			HexFormat hex = HexFormat.of().withLowerCase();
			String hexString = hex.formatHex(sha256Byte);
			System.out.println("SHA256");
			System.out.println(hexString);
		}
		catch (NoSuchAlgorithmException e) {
			
		}
	}

}

参考情報

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0