備忘録

備忘録

JavaでAES

public byte[] AesEncrypt(String str) throws Exception
{
  // IV無し
  // ブロック暗号モード: ECB
  // パディング: PKCS7
  Cipher cipher = Cipher.getInstance("AES");
  cipher.init(Cipher.ENCRYPT_MODE, "0123456789ABCDEF"); // Keyは16文字(32bit)

  return cipher.doFinal(str.getBytes());
}
public static String EncryptAES (String str) throws Exception
{
  var bytes = str.getBytes(StandardCharsets.UTF_8);
  var key = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
  var iv = "bbbbbbbbbbbbbbbb";

  SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
  Cipher instance = Cipher.getInstance("AES/CBC/PKCS5Padding");
  instance.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)));
  var encryptedBytes = instance.doFinal(bytes);
  return Base64.getEncoder().encodeToString(encryptedBytes);
}