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?

[java]任意のハッシュアルゴリズムと文字コードでハッシュ値を生成

Posted at
package com.example.util;

import java.security.MessageDigest;
import java.nio.charset.Charset;

public class HashUtil {

    /**
     * 任意のハッシュアルゴリズムと文字コードでハッシュ値を生成する。
     *
     * @param input      ハッシュ化する文字列
     * @param algorithm  使用するハッシュアルゴリズム(例:SHA-1, SHA-256, MD5)
     * @param charset    使用する文字エンコーディング(例:UTF-8, Shift_JIS)
     * @return           ハッシュ値(16進文字列)
     */
    public static String hash(String input, String algorithm, String charset) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            byte[] bytes = md.digest(input.getBytes(Charset.forName(charset)));
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                result.append(String.format("%02x", b));
            }
            return result.toString();
        } catch ( NoSuchAlgorithmException e) {
            throw new  NoSuchAlgorithmException("指定したアルゴリズムのMessageDigestSpi実装をサポートするプロバイダが存在しないエラーが発生しました", e);
        } catch (DigestException e) {
            throw new DigestException("ハッシュ計算時にエラー発生しました", e);
        } catch (Exception e) {
            throw new RuntimeException("任意のハッシュアルゴリズムと文字コードでハッシュ値を生成にに予期せぬエラーが発生しました", e);
        }
    }
}

使用例

public class MainApp {
    public static void main(String[] args) {
        String input = "こんにちは";
        String hash = HashUtil.hash(input, "SHA-1", "UTF-8");
        System.out.println("SHA-1 hash (UTF-8): " + hash);

        String hashShiftJis = HashUtil.hash(input, "SHA-1", "Shift_JIS");
        System.out.println("SHA-1 hash (Shift_JIS): " + hashShiftJis);
    }
}
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?