JavaでSHA2

SHA2の16進文字列を簡単に取得できるライブラリが無いので書いた。書いたと言ってもアルゴリズムはjava.security.MessageDigest 任せですよ。

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

/**
 * MD5やSHA-512等のDigestを16進文字列で返すクラス。
 */
public class Digest {
    
    public static final String MD5 = "MD5";    
    public static final String SHA1 = "SHA-1";        
    public static final String SHA256 = "SHA-256";
    public static final String SHA384 = "SHA-384";
    public static final String SHA512 = "SHA-512";    

    private MessageDigest messageDigest;
    
    public Digest(String algorithm) {
        super();
        if (algorithm == null) {
            throw new NullPointerException("Algorithm must not be null");
        }
        try {
            this.messageDigest = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            // ignore;
        }
    }
    
    /**
     * 文字列を指定アルゴリズムでdigest化して、バイト列を16進文字列化して返します。
     * 
     * @param algorithm ダイジェストアルゴリズム
     * @param message ダイジェスト化するメッセージ、空文字列が返る場合はアルゴリズム指定が間違っている
     * @return 文字列
     * @throws NullPointerException algorithmまたはmessageがnullの場合
     */
    public static String hex(String algorithm, String message) {
        return new Digest(algorithm).hex(message);
    }
    
    public String hex(String message) {
        if (message == null) {
            throw new NullPointerException("Message must not be null");
        }
        if (this.messageDigest == null) {
            return "";
        }
        
        StringBuilder builder = new StringBuilder();
        
        messageDigest.reset();
        messageDigest.update(message.getBytes());
        byte[] digest = messageDigest.digest();
        for (int i = 0; i < digest.length; i++) {
            int d = digest[i] & 0xff;
            String hex = Integer.toHexString(d);
            if (hex.length() == 1) {
                builder.append("0");
            }
            builder.append(hex);
        }
        return builder.toString();
    }
}

使い方

String digest = Digest.hex(Digest.SHA256, "もとの文字列");

だるい