Javaの文字列からSHA1ハッシュを生成する方法

SHA1ハッシュは、ApacheコモンズのDigestUtilsを使って生成できます。

構文:

	sha1 = org.apache.commons.codec.digest.DigestUtils.sha1Hex( value );

SHA1ハッシュは、jdkのMessageDigestクラスを使用して直接生成することもできます。

構文:

	MessageDigest digest = MessageDigest.getInstance("SHA-1");
	digest.reset();
	digest.update(value.getBytes("utf8"));
	sha1 = String.format("%040x", new BigInteger(1, digest.digest()));

以下は "これはテストです"という文字列のsha1を作成する例です。 まず、jdkのMessageDigestクラスを使用するメソッドを使用します。 その後、ApacheコモンズのDigestUtilsクラスを使用します。 生成されたsha1はコンソールに書き込まれます。

1-次のJavaファイルを作成します。

import java.math.BigInteger;
import java.security.MessageDigest;

public class SHA1 {

	public static void main(String[] argv){

		String value = "this is a test";

		String sha1 = "";
		
		// With the java libraries
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
	        digest.reset();
	        digest.update(value.getBytes("utf8"));
	        sha1 = String.format("%040x", new BigInteger(1, digest.digest()));
		} catch (Exception e){
			e.printStackTrace();
		}

		System.out.println( "The sha1 of \""+ value + "\" is:");
		System.out.println( sha1 );
		System.out.println();

		// With Apache commons
		sha1 = org.apache.commons.codec.digest.DigestUtils.sha1Hex( value );

		System.out.println( "The sha1 of \""+ value + "\" is:");
		System.out.println( sha1 );

     }
}

出力は次のようになります。

The sha1 of "this is a test" is:
fa26be19de6bff93f70bc2308434e4a440bbad02

The sha1 of "this is a test" is:
fa26be19de6bff93f70bc2308434e4a440bbad02

参考文献:

Java 8
Online tool generating SHA1
SHA1 Decoder

最近のコメント