🔒 Security

AES

Advanced Encryption Standard

The symmetric-key encryption standard. Supports 128/192/256-bit keys and is the most widely used block cipher algorithm in the world. The de facto standard for data encryption.

📖 Detailed Explanation

AES (Advanced Encryption Standard) is a symmetric-key block cipher algorithm selected by NIST in 2001 to replace DES. The Rijndael algorithm, developed by Belgian cryptographers Joan Daemen and Vincent Rijmen, was selected through an open competition. AES uses a fixed block size of 128 bits and, depending on the key length, is divided into AES-128 (10 rounds), AES-192 (12 rounds), and AES-256 (14 rounds). Because no practical attack is known to date, it is recognized as the most secure symmetric-key cipher.

The internal structure of AES consists of four transformations: SubBytes (byte substitution), ShiftRows (row shifting), MixColumns (column mixing), and AddRoundKey (round key addition). In each round, these transformations are applied sequentially to convert plaintext into ciphertext. On CPUs that support hardware acceleration (AES-NI), encryption performance of several gigabytes per second can be achieved. Thanks to this efficiency, AES is used in almost all security protocols, including TLS, IPsec, and disk encryption.

AES must be used together with a mode of operation. ECB (Electronic Codebook) is vulnerable from a security standpoint because identical plaintext produces identical ciphertext. CBC (Cipher Block Chaining) hides patterns by using an IV (initialization vector), but it is difficult to parallelize. For modern use, GCM (Galois/Counter Mode) is recommended, and it provides encryption and authentication (AEAD) at the same time. CTR mode allows parallel processing and is therefore preferred in high-performance environments.

In AI/ML systems, AES is essential for encrypting model weights, training data, and inference results. Cloud ML platforms protect both data at rest (at-rest) and data in transit (in-transit) with AES-256-GCM. Gradient exchange between clients and servers in federated learning is also encrypted with AES. In preparation for the era of quantum computers, AES-256 maintains a 128-bit security strength even against Grover's algorithm, so it is suitable for long-term security.

💻 Code Example

# AES-256-GCM 암호화/복호화 - Python cryptography 라이브러리
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
import base64

class AESEncryptor:
    """AES-256-GCM 암호화 클래스"""

    def __init__(self, key: bytes = None):
        """
        Args:
            key: 32바이트(256비트) 키. None이면 랜덤 생성
        """
        self.key = key or AESGCM.generate_key(bit_length=256)
        self.aesgcm = AESGCM(self.key)

    def encrypt(self, plaintext: bytes, associated_data: bytes = None) -> dict:
        """
        데이터 암호화

        Args:
            plaintext: 암호화할 데이터
            associated_data: 인증할 추가 데이터 (암호화되지 않음)

        Returns:
            dict: nonce, ciphertext, tag 포함
        """
        # 96비트(12바이트) nonce - GCM 권장 크기
        nonce = os.urandom(12)

        # 암호화 (GCM은 ciphertext에 tag 포함)
        ciphertext = self.aesgcm.encrypt(nonce, plaintext, associated_data)

        return {
            'nonce': base64.b64encode(nonce).decode(),
            'ciphertext': base64.b64encode(ciphertext).decode(),
            'aad': base64.b64encode(associated_data).decode() if associated_data else None
        }

    def decrypt(self, encrypted_data: dict) -> bytes:
        """
        데이터 복호화

        Args:
            encrypted_data: encrypt()의 반환값

        Returns:
            bytes: 복호화된 원본 데이터
        """
        nonce = base64.b64decode(encrypted_data['nonce'])
        ciphertext = base64.b64decode(encrypted_data['ciphertext'])
        aad = base64.b64decode(encrypted_data['aad']) if encrypted_data.get('aad') else None

        return self.aesgcm.decrypt(nonce, ciphertext, aad)

# 사용 예시
if __name__ == "__main__":
    # 암호화 객체 생성
    encryptor = AESEncryptor()

    # ML 모델 가중치 암호화 예시
    model_weights = b"tensor([[0.1, 0.2], [0.3, 0.4]])"
    model_metadata = b"model_v1.0"  # 인증할 메타데이터

    # 암호화
    encrypted = encryptor.encrypt(model_weights, model_metadata)
    print(f"Encrypted: {encrypted['ciphertext'][:50]}...")

    # 복호화
    decrypted = encryptor.decrypt(encrypted)
    print(f"Decrypted: {decrypted.decode()}")

    # 키 저장 (안전하게 보관 필요!)
    print(f"Key (base64): {base64.b64encode(encryptor.key).decode()}")
// AES-256-GCM 암호화/복호화 - Node.js crypto 모듈
const crypto = require('crypto');

class AESEncryptor {
    constructor(key = null) {
        // 32바이트(256비트) 키
        this.key = key || crypto.randomBytes(32);
        this.algorithm = 'aes-256-gcm';
    }

    /**
     * 데이터 암호화
     * @param {Buffer|string} plaintext - 암호화할 데이터
     * @param {Buffer|string} aad - 추가 인증 데이터 (선택)
     * @returns {Object} - iv, ciphertext, authTag, aad
     */
    encrypt(plaintext, aad = null) {
        // 12바이트 IV (GCM 권장)
        const iv = crypto.randomBytes(12);
        const cipher = crypto.createCipheriv(this.algorithm, this.key, iv);

        // AAD 설정 (있는 경우)
        if (aad) {
            cipher.setAAD(Buffer.from(aad));
        }

        // 암호화
        const plaintextBuffer = Buffer.from(plaintext);
        const encrypted = Buffer.concat([
            cipher.update(plaintextBuffer),
            cipher.final()
        ]);

        // 인증 태그 (16바이트)
        const authTag = cipher.getAuthTag();

        return {
            iv: iv.toString('base64'),
            ciphertext: encrypted.toString('base64'),
            authTag: authTag.toString('base64'),
            aad: aad ? Buffer.from(aad).toString('base64') : null
        };
    }

    /**
     * 데이터 복호화
     * @param {Object} encryptedData - encrypt()의 반환값
     * @returns {Buffer} - 복호화된 데이터
     */
    decrypt(encryptedData) {
        const iv = Buffer.from(encryptedData.iv, 'base64');
        const ciphertext = Buffer.from(encryptedData.ciphertext, 'base64');
        const authTag = Buffer.from(encryptedData.authTag, 'base64');

        const decipher = crypto.createDecipheriv(this.algorithm, this.key, iv);
        decipher.setAuthTag(authTag);

        // AAD 설정 (있는 경우)
        if (encryptedData.aad) {
            const aad = Buffer.from(encryptedData.aad, 'base64');
            decipher.setAAD(aad);
        }

        // 복호화
        return Buffer.concat([
            decipher.update(ciphertext),
            decipher.final()
        ]);
    }

    // 키를 Base64로 내보내기
    exportKey() {
        return this.key.toString('base64');
    }
}

// 사용 예시
const encryptor = new AESEncryptor();

// API 응답 데이터 암호화
const sensitiveData = JSON.stringify({
    userId: "user123",
    predictions: [0.85, 0.12, 0.03]
});

// 암호화
const encrypted = encryptor.encrypt(sensitiveData, "api-response-v1");
console.log("Encrypted:", encrypted);

// 복호화
const decrypted = encryptor.decrypt(encrypted);
console.log("Decrypted:", decrypted.toString());

// 키 내보내기
console.log("Key:", encryptor.exportKey());
# AES-256 암호화/복호화 - OpenSSL CLI

# 1. 랜덤 키 생성 (32바이트 = 256비트)
openssl rand -base64 32 > aes_key.txt

# 2. 파일 암호화 (AES-256-CBC)
# -pbkdf2: 비밀번호 기반 키 파생 (권장)
# -iter: PBKDF2 반복 횟수
openssl enc -aes-256-cbc -pbkdf2 -iter 100000 \
    -in model_weights.bin \
    -out model_weights.enc \
    -pass file:aes_key.txt

# 3. 파일 복호화
openssl enc -aes-256-cbc -pbkdf2 -iter 100000 -d \
    -in model_weights.enc \
    -out model_weights_decrypted.bin \
    -pass file:aes_key.txt

# 4. AES-256-GCM으로 암호화 (인증 암호화)
# GCM은 enc 명령어로 직접 지원하지 않으므로 openssl 명령어 사용
# 또는 프로그래밍 방식 권장

# 5. 대용량 파일 스트리밍 암호화 (파이프라인)
cat large_dataset.csv | \
    openssl enc -aes-256-cbc -pbkdf2 -iter 100000 -pass file:aes_key.txt | \
    gzip > large_dataset.csv.enc.gz

# 6. 스트리밍 복호화
gunzip -c large_dataset.csv.enc.gz | \
    openssl enc -aes-256-cbc -pbkdf2 -iter 100000 -d -pass file:aes_key.txt \
    > large_dataset_restored.csv

# 7. 키 정보 확인
# AES-256 키는 32바이트(256비트)
echo "Key length: $(cat aes_key.txt | base64 -d | wc -c) bytes"

# 8. 암호화 알고리즘 목록 확인
openssl enc -list | grep aes

# 9. 벤치마크 (AES 성능 테스트)
openssl speed aes-256-cbc aes-256-gcm

# 10. 실무 팁: 환경변수로 키 전달 (파일 노출 방지)
export AES_KEY=$(openssl rand -base64 32)
echo "secret data" | openssl enc -aes-256-cbc -pbkdf2 -pass env:AES_KEY

🗣️ Say It Like This in Practice

💬 In a Security Architecture Design Meeting
"Let's encrypt data at rest with AES-256-GCM and manage the keys in AWS KMS. GCM mode provides encryption and integrity verification at the same time, so a separate HMAC is not needed. Never use ECB mode."
💬 In an ML Model Security Review
"When storing trained model weights in S3, server-side encryption (SSE-S3) is the default, but if you need stronger control, encrypt with AES-256 using customer-managed keys (SSE-KMS). Key access logs are also recorded in CloudTrail."
💬 In a Performance Optimization Discussion
"On CPUs that support AES-NI, GCM mode is faster than CBC. In our API server benchmark, AES-256-GCM reached over 10GB/s. You can encrypt every response without worrying about encryption overhead."

⚠️ Cautions & Best Practices

❌
Do Not Use ECB Mode

In ECB (Electronic Codebook) mode, identical plaintext blocks produce identical ciphertext. The "penguin problem," where the original pattern is revealed when encrypting an image, is a representative example. Always use CBC, CTR, or GCM mode.

❌
Do Not Reuse an IV/Nonce

Reusing the same IV/nonce with the same key completely defeats the encryption. In GCM mode in particular, nonce reuse even exposes the authentication key. Generate a cryptographically secure random value for every encryption.

❌
Hardcoding Keys in Code

Writing encryption keys directly in source code exposes them through Git history, logs, memory dumps, and the like. Use a secure key management system such as AWS KMS, HashiCorp Vault, or environment variables.

✅
AES Best Practices

Use AES-256-GCM by default. Manage keys in an HSM or KMS, and establish a key rotation policy. Never store encrypted data and keys in the same location. Update encryption libraries regularly.

🔗 Related Terms

📚 Learn More