AES-256を用いたデータ暗号化は、Javaアプリケーションのセキュリティ強化において重要な技術です。JCA(Java Cryptography Architecture)を活用した実装方法を解説します。
暗号化処理を安全に実行するためには、無制限強度暗号化ポリシーファイルの導入が必須です。JDKのセキュリティ設定を確認し、必要に応じてポリシーファイルを更新してください。
暗号化処理の実装手順
暗号化処理は以下の要素で構成されます:
- 暗号化キーの生成と管理
- 初期化ベクトル(IV)の生成
- CBCモードでの暗号化/復号化処理
- Base64エンコーディングによるバイナリデータのテキスト化
コード実装例
安全な実装のため、ECBモードではなくCBCモードを使用し、毎回異なるIVを生成します:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
public class EncryptionUtil {
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
public static EncryptedData encrypt(String plainText, byte[] keyBytes) throws Exception {
// 初期化ベクトルの生成
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
// 暗号化キーの準備
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
// 暗号化処理
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
// IVと暗号文の結合
byte[] combined = new byte[iv.length + encrypted.length];
System.arraycopy(iv, 0, combined, 0, iv.length);
System.arraycopy(encrypted, 0, combined, iv.length, encrypted.length);
return new EncryptedData(Base64.getEncoder().encodeToString(combined), ivSpec);
}
public static String decrypt(String encryptedData, byte[] keyBytes) throws Exception {
byte[] combined = Base64.getDecoder().decode(encryptedData);
byte[] iv = new byte[16];
System.arraycopy(combined, 0, iv, 0, iv.length);
// 復号化処理
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,
new SecretKeySpec(keyBytes, "AES"),
new IvParameterSpec(iv));
byte[] decrypted = cipher.doFinal(combined, 16, combined.length - 16);
return new String(decrypted);
}
static class EncryptedData {
String encodedData;
IvParameterSpec ivSpec;
EncryptedData(String data, IvParameterSpec iv) {
this.encodedData = data;
this.ivSpec = iv;
}
}
}
メイン処理では、256ビットの暗号化キーを安全に生成します:
public static void main(String[] args) throws Exception {
// 256ビットキーの生成(実際の実装では安全な方法で管理)
byte[] key = new byte[32];
new SecureRandom().nextBytes(key);
// 暗号化処理
String original = "暗号化対象のテストデータ";
EncryptedData result = encrypt(original, key);
// 復号化確認
String decrypted = decrypt(result.encodedData, key);
System.out.println("元データ: " + original);
System.out.println("復号データ: " + decrypted);
}
キー管理には特に注意が必要です。実際のシステムでは、キーをハードコードせず、KeyStoreや外部のキーマネジメントサービスを利用してください。IVは毎回ランダムに生成し、暗号文と共に保存することで、同じ平文でも異なる暗号文が生成されるようにします。