느바 2025. 1. 19. 11:57
반응형

Web Crypto API

Web Crypto API는 브라우저에서 암호화 작업을 수행하기 위한 JavaScript API입니다. 데이터를 암호화하거나 복호화하고, 해시를 생성하며, 디지털 서명이나 인증을 처리할 수 있는 기능을 제공합니다. 이 API는 보안적으로 안전한 방식으로 설계되었으며, 민감한 데이터를 처리하는 웹 애플리케이션에 적합합니다.

특징

  1. 브라우저 내장: 별도의 라이브러리를 설치하지 않아도 사용 가능.
  2. 보안성: 암호학적으로 강력한 난수 생성 및 암호화 알고리즘 사용.
  3. Promise 기반: 비동기로 동작하여 메인 스레드의 차단을 방지.
  4. 주요 작업:
    • 데이터 암호화/복호화
    • 해시 생성
    • 키 생성 및 관리
    • 디지털 서명 및 검증

사용되는 사례

  1. 데이터 암호화:
    • 사용자의 민감한 데이터를 클라이언트에서 암호화한 후 서버로 전송.
  2. 사용자 인증:
    • 디지털 서명 및 공개 키를 이용한 인증.
  3. 데이터 무결성 확인:
    • 데이터를 해싱하여 원본 데이터의 변경 여부 확인.
  4. API 요청 보호:
    • 클라이언트와 서버 간 통신에서 암호화를 통해 데이터 보안을 강화.

주요 기능과 사용법

1. 암호학적 난수 생성

암호학적으로 안전한 난수를 생성하여 키나 토큰을 만들 때 사용됩니다.

const randomValues = new Uint8Array(16);
window.crypto.getRandomValues(randomValues);
console.log(randomValues);
// 출력 예: Uint8Array(16) [123, 45, 67, 89, ...]
 
/* Assuming that self.crypto.randomUUID() is available */

let uuid = crypto.randomUUID();
console.log(uuid); // for example "36b8f84d-df4e-4d49-b662-bcde71a8764f"

2. 데이터 해싱

데이터의 고정된 크기의 해시값을 생성합니다. 해시는 데이터의 무결성을 검증하거나 비밀번호를 저장할 때 주로 사용됩니다.

async function hashData(message) {
    const encoder = new TextEncoder();
    const data = encoder.encode(message);
    const hashBuffer = await crypto.subtle.digest('SHA-256', data);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    return hashHex;
}

hashData('Hello, World!').then(hash => console.log(hash));
// 출력 예: "315f5bdb76d078c43b8ac0064e4a016461a79de2291a334c6a59c74e6c6f9cf7"
 

3. 데이터 암호화 및 복호화

대칭 키 알고리즘(AES-GCM)을 사용하여 데이터를 암호화/복호화합니다.

async function encryptData(data) {
    const key = await crypto.subtle.generateKey(
        { name: 'AES-GCM', length: 256 },
        true,
        ['encrypt', 'decrypt']
    );

    const iv = window.crypto.getRandomValues(new Uint8Array(12)); // 초기화 벡터
    const encodedData = new TextEncoder().encode(data);
    const encrypted = await crypto.subtle.encrypt(
        { name: 'AES-GCM', iv },
        key,
        encodedData
    );

    return { encrypted, key, iv };
}

async function decryptData(encrypted, key, iv) {
    const decrypted = await crypto.subtle.decrypt(
        { name: 'AES-GCM', iv },
        key,
        encrypted
    );
    return new TextDecoder().decode(decrypted);
}

// 사용 예시
encryptData('Hello, World!').then(async ({ encrypted, key, iv }) => {
    console.log('암호화된 데이터:', new Uint8Array(encrypted));
    const decrypted = await decryptData(encrypted, key, iv);
    console.log('복호화된 데이터:', decrypted);
});
 

4. 디지털 서명 및 검증

비대칭 키(RSA-PSS)를 사용하여 데이터를 서명하고, 이를 검증합니다.

async function signAndVerify() {
    const keyPair = await crypto.subtle.generateKey(
        {
            name: 'RSA-PSS',
            modulusLength: 2048,
            publicExponent: new Uint8Array([1, 0, 1]),
            hash: 'SHA-256',
        },
        true,
        ['sign', 'verify']
    );

    const data = new TextEncoder().encode('This is a test message');
    const signature = await crypto.subtle.sign(
        { name: 'RSA-PSS', saltLength: 32 },
        keyPair.privateKey,
        data
    );

    const isValid = await crypto.subtle.verify(
        { name: 'RSA-PSS', saltLength: 32 },
        keyPair.publicKey,
        signature,
        data
    );

    console.log('서명:', new Uint8Array(signature));
    console.log('검증 결과:', isValid); // true
}

signAndVerify();
 

Web Crypto API의 장점

  1. 보안성:
    • API는 CORS(Cross-Origin Resource Sharing) 정책에 따라 보호되며, 암호학적 난수를 사용합니다.
  2. 표준화:
    • 모든 주요 브라우저에서 지원되므로 호환성이 높습니다.
  3. 비동기성:
    • Promise 기반 설계로 성능에 미치는 영향을 최소화합니다.

브라우저 지원

Web Crypto API는 대부분의 최신 브라우저에서 지원됩니다. 하지만 사용 전 브라우저 호환성을 확인하는 것이 좋습니다.


Web Crypto API는 브라우저 환경에서 안전하고 효율적으로 암호화 관련 작업을 처리하는 데 필수적인 도구입니다. 이를 사용하면 클라이언트-서버 간 통신을 보호하거나, 데이터 무결성을 보장하고, 인증 시스템을 구현할 수 있습니다.

 

https://developer.mozilla.org/ko/docs/Web/API/Crypto

 

Crypto - Web API | MDN

Crypto 인터페이스는 현재 환경에서 사용 가능한 기본적인 암호화 기법을 제공합니다. 이 인터페이스를 통해 암호학적으로 강력한 무작위 숫자 생성기나 암호화에 필요한 기본 요소에 접근할 수

developer.mozilla.org