Symmetric encryption và AEAD
Cùng một secret key dùng để encrypt/decrypt. AES-GCM và ChaCha20-Poly1305 là AEAD: bảo vệ confidentiality và integrity, đồng thời xác thực Additional Authenticated Data (AAD) không cần mã hóa.
Nonce và tag
- Nonce không cần bí mật nhưng phải unique theo key; nonce reuse với GCM có thể phá cả confidentiality và authentication.
- Verify authentication tag trước khi dùng plaintext.
- AAD phù hợp bind version, tenant, record ID hoặc protocol header vào ciphertext.
- Không dùng AES-ECB; CBC cần encrypt-then-MAC construction đúng và khó dùng hơn AEAD.
byte[] nonce = new byte[12]; new SecureRandom().nextBytes(nonce); Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, nonce)); cipher.updateAAD(context); byte[] ciphertextAndTag = cipher.doFinal(plaintext);