Web Crypto API는 웹 개발자에게 암호화 기능을 제공하는 JavaScript 인터페이스입니다. 이를 통해 개발자는 암호화, 암호 해독, 해싱, 서명 및 디지털 서명 확인과 같은 다양한 암호화 작업을 수행할 수 있습니다. 이러한 작업은 안전하고 효율적인 방식으로 수행될 수 있으므로 개발자가 보안 웹 애플리케이션을 보다 쉽게 구현할 수 있습니다.
다음은 JavaScript에서 Web Crypto API를 사용하는 방법에 대한 몇 가지 예입니다.
난수 생성:
window.crypto.getRandomValues(new Uint32Array(1))[0]
이 코드는 Web Crypto API를 사용하여 임의의 32비트 부호 없는 정수를 생성합니다.
메시지 해싱:
async function hashMessage(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hash = await crypto.subtle.digest('SHA-256', data);
return hash;
}
hashMessage('hello world')
.then(hash => console.log(new Uint8Array(hash)))
.catch(error => console.error(error));
이 코드는 SHA-256 알고리즘을 사용하여 "hello world" 메시지를 해시합니다. `TextEncoder` 인터페이스를 사용하여 메시지를 `ArrayBuffer`로 변환하고 `crypto.subtle.digest` 메서드를 사용하여 해시를 생성합니다.
키 쌍 생성:
async function generateKeyPair() {
const algorithm = { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), hash: 'SHA-256' };
const keys = await crypto.subtle.generateKey(algorithm, true, ['encrypt', 'decrypt']);
return keys;
}
generateKeyPair()
.then(keys => console.log(keys))
.catch(error => console.error(error));
이 코드는 모듈러스 길이가 2048비트이고 공개 지수가 65537(0x010001)이고 OAEP 패딩 체계를 사용하는 RSA 키 쌍을 생성합니다. `crypto.subtle.generateKey` 메서드를 사용하여 키 쌍을 생성하고 키를 반환합니다.
데이터 암호화 및 해독:
async function encryptData(data, publicKey) {
const encryptedData = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, publicKey, data);
return encryptedData;
}
async function decryptData(encryptedData, privateKey) {
const decryptedData = await crypto.subtle.decrypt({ name: 'RSA-OAEP' }, privateKey, encryptedData);
return decryptedData;
}
const message = 'hello world';
const encoder = new TextEncoder();
const data = encoder.encode(message);
generateKeyPair()
.then(keys => {
const publicKey = keys.publicKey;
const privateKey = keys.privateKey;
return encryptData(data, publicKey)
.then(encryptedData => decryptData(encryptedData, privateKey))
.then(decryptedData => {
const decoder = new TextDecoder();
const decryptedMessage = decoder.decode(decryptedData);
console.log(decryptedMessage);
});
})
.catch(error => console.error(error));
이 코드는 RSA 키 쌍을 생성하고 공개 키를 사용하여 "hello world" 메시지를 암호화한 다음 개인 키를 사용하여 암호화된 데이터를 복호화합니다. `crypto.subtle.encrypt` 및 `crypto.subtle.decrypt` 메서드를 사용하여 암호화 및 암호 해독 작업을 수행합니다.
이는 JavaScript에서 Web Crypto API를 사용하는 방법에 대한 몇 가지 예일 뿐입니다. API는 다양한 암호화 작업을 수행하기 위한 더 많은 기능과 알고리즘을 제공합니다.
'IT' 카테고리의 다른 글
자바스크립트 "Web Audio API" (0) | 2023.03.10 |
---|---|
자바스크립트 "Web Authentication API" (0) | 2023.03.10 |
자바스크립트 "Web Locks API" (0) | 2023.03.10 |
자바스크립트 "Web MIDI API" (0) | 2023.03.09 |
자바스크립트 "Web Notifications API" (0) | 2023.03.09 |