Java プログラムメモ


トップ

MD5 値の取得方法

メッセージダイジェストの取得は java.security.MessageDigest を使って簡単に可能です。
MessageDigest#getInstance(String algorithm) を使用してアルゴリズムを指定した MessageDigest のインスタンスを取得します。
アルゴリズム には MD5 の他 SHA-1 等有名なメッセージダイジェストは、ほとんど使用可能なようです。

byte 配列から MD5

byte 配列からメッセージダイジェストを取得する場合は非常に簡単で、MessageDigest#digest で取得可能です。 以下にコードのサンプルを書きます。

※パスワードの保存等で利用します。

MessageDigest digest = MessageDigest.getInstance("MD5"); byte[] hash = digest.digest("hoge".getBytes());

InputStream から MD5

InputStram からメッセージダイジェストを取得する場合は、MessageDigest#update と MessageDigest#digest を併用しなければなりません。update ですべての Stream を読み込んだ後に digest で取得します。 公開されている

※アプリケーションの MD5 値を取得する時等に利用します。

InputStream in = new FileInputStream("C:/work/test.xls"); MessageDigest digest = MessageDigest.getInstance("MD5"); try { byte[] buff = new byte[4096]; int len = 0; while ((len = in.read(buff, 0, buff.length)) >= 0) { digest.update(buff, 0, len); } } catch (IOException e) { throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } byte[] hash = digest.digest();

Adapter クラス

java.security.MessageDigest では、InputStream からメッセージダイジェストを取得するのが 面倒なので、Adapter クラスを作成しました。

byte 配列だけでなく文字列も取得可能にしてあります。

クラス

import java.io.*; import java.security.*; public class MessageDigestAdapter { private MessageDigest digest_; public MessageDigestAdapter(String algorithm) throws NoSuchAlgorithmException { digest_ = MessageDigest.getInstance(algorithm); } public synchronized String digest(InputStream in) throws IOException { return toHexString(digestArray(in)); } public synchronized String digest(String str) { return toHexString(digestArray(str)); } public synchronized byte[] digestArray(InputStream in) throws IOException { try { byte[] buff = new byte[4096]; int len = 0; while ((len = in.read(buff, 0, buff.length)) >= 0) { digest_.update(buff, 0, len); } } catch (IOException e) { throw e; } byte[] hash = digest_.digest(); digest_.reset(); return hash; } public synchronized byte[] digestArray(String str) { byte[] hash = digest_.digest(str.getBytes()); digest_.reset(); return hash; } private String toHexString(byte[] arr) { StringBuffer buff = new StringBuffer(arr.length * 2); for (int i = 0; i < arr.length; i++) { String b = Integer.toHexString(arr[i] & 0xff); if (b.length() == 1) { buff.append("0"); } buff.append(b); } return buff.toString(); } }

クライアントクラス

public class MD5Test { public static void main(String[] args) throws Exception { MessageDigestAdapter md5 = new MessageDigestAdapter("MD5"); String hash = md5.digest("test"); System.out.println(hash); InputStream in = new FileInputStream(new File("C:/temp/test.txt")); String hash2 = md5.digest(in); System.out.println(hash2); in.close(); } }

出力結果

098f6bcd4621d373cade4e832627b4f6 0073fd6bfc0ade9c034b3d2b8b0358e4

プログラムメモ アフリカ雑貨・珈琲豆・アールブリュット作品 マゴソスクール クラウドファンディング
SEO [PR] 爆速!無料ブログ 無料ホームページ開設 無料ライブ放送