
암호학
Web Cryptography APIWeb Cryptography API
Web Cryptography API는 브라우저에서 직접 암호화 작업을 수행하는 표준 JavaScript API다. 키 생성, 서명, 암호화/복호화, 해시, 난수 생성 등을 네이티브로 지원한다.
주요 기능
javascript
const subtle = window.crypto.subtle;
// 1. 해시 (SHA-256)
async function hash(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hashBuffer = await subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
const h = await hash('Hello, World!'); // 'dffd...'
// 2. AES-GCM 대칭 암호화
async function encryptAES(plaintext, key) {
const iv = crypto.getRandomValues(new Uint8Array(12)); // 96비트 IV
const encoded = new TextEncoder().encode(plaintext);
const ciphertext = await subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
encoded
);
return { iv, ciphertext };
}
// 키 생성
const aesKey = await subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true, // extractable
['encrypt', 'decrypt']
);RSA 비대칭 암호화
javascript
// RSA-OAEP 키 쌍 생성
const { publicKey, privateKey } = await subtle.generateKey({
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // 65537
hash: 'SHA-256'
}, true, ['encrypt', 'decrypt']);
// 암호화 (공개 키)
const encrypted = await subtle.encrypt(
{ name: 'RSA-OAEP' },
publicKey,
new TextEncoder().encode('secret message')
);
// 복호화 (개인 키)
const decrypted = await subtle.decrypt(
{ name: 'RSA-OAEP' },
privateKey,
encrypted
);
console.log(new TextDecoder().decode(decrypted));ECDSA 디지털 서명
javascript
// ECDSA 키 쌍
const { publicKey, privateKey } = await subtle.generateKey(
{ name: 'ECDSA', namedCurve: 'P-384' },
true,
['sign', 'verify']
);
const data = new TextEncoder().encode('서명할 데이터');
// 서명
const signature = await subtle.sign(
{ name: 'ECDSA', hash: 'SHA-384' },
privateKey,
data
);
// 검증
const valid = await subtle.verify(
{ name: 'ECDSA', hash: 'SHA-384' },
publicKey,
signature,
data
);
console.log(valid); // true
// 키 내보내기/가져오기
const exported = await subtle.exportKey('jwk', publicKey);
const imported = await subtle.importKey('jwk', exported,
{ name: 'ECDSA', namedCurve: 'P-384' }, true, ['verify']);관련 문서
- •[[subresource-integrity|SRI]]
- •[[browser-security-model|브라우저 보안 모델]]
- •[[wasm-ecosystem|WebAssembly 생태계]]