0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

文字列をmd5ハッシュ化して返す

Posted at

文字列をmd5Hash化

まあ自分メモです。
ライブラリとかあるみたいなので使わなそうですけど。
この方法はMessageDigestを使います。

下記のソースのstrHash の部分がハッシュ化したい文字列です。
任意の文字列ってことになります。
ハッシュ化した結果はstrの値です。

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

/**
 * md5Hash
 * 入力された文字列をmd5Hash化して返す
 */

public class md5Hash {
    public static void main(String[] args) {
        /**ハッシュ化したい文字列:strHash */
        String strHash = "12345";
        System.out.println("ハッシュ化する文字列:" + strHash);

        try{
            // メッセージダイジェストのインスタンスを生成
            MessageDigest md5 = MessageDigest.getInstance("MD5");

            byte[] result = md5.digest(strHash.getBytes());
            
            // 16進数に変換して桁を整える
            int[] i = new int[result.length];
            StringBuffer sb = new StringBuffer();
            for (int j=0; j < result.length; j++){
                i[j] = (int)result[j] & 0xff;
                if (i[j]<=15){
                    sb.append("0");
                }
                sb.append(Integer.toHexString(i[j]));
            }
            String str = sb.toString();
            System.out.println("ハッシュ化後の文字列:" + str);

        } catch (NoSuchAlgorithmException x){

        }     
    }
}

上記を実行すると下記のような結果が得られるかと思います。

結果
ハッシュ化する文字列:12345
ハッシュ化後の文字列:827ccb0eea8a706c4c34a16891f84e7b

参考

Java で MD5 ダイジェスト値を求める方法
【java】文字列をMD5ハッシュ化

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?