for文とかif文とかできれば使いたくないよね。
DigestUtilsが使えればそれがいいと思うんだけど標準じゃないのがちとネック。
2016/10/02 修正:そこそこアクセスあるのに間違えていた...
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5ハッシュ
*/
public class MD5Hash {
/**
* MD5ハッシュの作成
* @param source 元の文字列
* @return ハッシュ後の文字列
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static String create(String source) throws UnsupportedEncodingException, NoSuchAlgorithmException {
byte[] str_bytes = source.getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5_bytes = md.digest(str_bytes);
BigInteger big_int = new BigInteger(1, md5_bytes);
// String md5_str = big_int.toString(16); 間違い!!
String md5_str = new String( String.format("%032x", big_int); // こっちが正解
return md5_str;
}
}
以下手順
1. 文字列をバイト配列へ
2. バイト配列をmd5でハッシュ化
3. BigInteger型へ代入
4. 16進表記したものを文字列化
わざわざ解説する必要が無いほどそのままですね。
どこかの誰かのソースを参考にしたはずだが忘れてしまった
ごめんね、ありがとう知らない人