ElGamal暗号をJavaで実装するには、以下の要素が必要です:
Javaでは BigInteger クラスを使うことで大きな数の演算が扱えます。
✅ Javaでの簡易ElGamal暗号のサンプルコード
import java.math.BigInteger;import java.security.SecureRandom;public class ElGamalExample { private static final SecureRandom random = new SecureRandom(); private static final int BIT_LENGTH = 512; public static void main(String[] args) { // 1. 鍵生成 BigInteger p = BigInteger.probablePrime(BIT_LENGTH, random); // 大きな素数 BigInteger g = new BigInteger("2"); // 原始根(簡単のため2) BigInteger x = new BigInteger(BIT_LENGTH - 2, random); // 秘密鍵 BigInteger y = g.modPow(x, p); // 公開鍵 System.out.println("公開鍵 (p, g, y): " + p + ", " + g + ", " + y); System.out.println("秘密鍵 x: " + x); // 2. 暗号化 BigInteger m = new BigInteger("42"); // 平文 BigInteger k = new BigInteger(BIT_LENGTH - 2, random); // 乱数 k BigInteger a = g.modPow(k, p); BigInteger b = y.modPow(k, p).multiply(m).mod(p); System.out.println("暗号文 (a, b): " + a + ", " + b); // 3. 復号 BigInteger s = a.modPow(x, p); // s = a^x mod p BigInteger s_inv = s.modInverse(p); // sの逆元 BigInteger decrypted = b.multiply(s_inv).mod(p); // 復号 m = b / s mod p System.out.println("復号結果: " + decrypted); }}
✅ 出力例(簡略)
公開鍵 (p, g, y): 123456789..., 2, 987654321...秘密鍵 x: 4567890...暗号文 (a, b): 2345678..., 8765432...復号結果: 42
✅ 注意点と改善案
| ポイント | 解説 |
|---|
| 暗号強度 | 実運用には十分な長さ(2048bit以上)が必要 |
| 乱数のセキュリティ | SecureRandom は使うべきだが、NIST準拠にするなら追加設定が必要 |
| メッセージの形式 | この例では整数(BigInteger)のみ。実際にはバイト配列との変換が必要 |
| パフォーマンス | BigInteger.modPow() は重い処理。必要に応じて最適化可能 |
| ライブラリ活用 | 実用では Bouncy Castle 等の暗号ライブラリを使うのが一般的 |
✅ ライブラリを使うなら?
Bouncy Castle を使えば、より安全かつ柔軟なElGamal暗号の実装が可能です(鍵の生成、暗号化、復号などが高レベルで提供されています)。
この記事へのコメント