url
모듈은 Node.js에서 URL을 파싱하거나 생성하는 데 사용되는 내장 모듈입니다. 이 모듈은 URL을 쉽게 분석하고, 구성 요소로 분리하거나, 수정할 수 있도록 도와줍니다. 특히, 웹 애플리케이션 개발 시 HTTP 요청 처리나 리소스 주소 관리 등에 유용하게 활용됩니다.
Node.js의 url
모듈은 두 가지 방식으로 사용할 수 있습니다.
1 ) 레거시 API (Node.js 7 이전)
2 ) WHATWG(웹 표준) URL API (Node.js 8부터 지원)
┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│ href │
├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
│ protocol │ │ auth │ host │ path │ hash │
│ │ │ ├─────────────────┬──────┼──────────┬────────────────┤ │
│ │ │ │ hostname │ port │ pathname │ search │ │
│ │ │ │ │ │ ├─┬──────────────┤ │
│ │ │ │ │ │ │ │ query │ │
" https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string #hash "
│ │ │ │ │ hostname │ port │ │ │ │
│ │ │ │ ├─────────────────┴──────┤ │ │ │
│ protocol │ │ username │ password │ host │ │ │ │
├──────────┴──┼──────────┴──────────┼────────────────────────┤ │ │ │
│ origin │ │ origin │ pathname │ search │ hash │
├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
│ href │
└────────────────────────────────────────────────────────────────────────────────────────────────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)
레거시 URL API는 url.parse()
와 url.format()
, url.resolve()
등을 통해 URL을 분석하거나 조작할 수 있습니다.
url.parse(urlString[, parseQueryString][, slashesDenoteHost])
parseQueryString
이 true
이면, 쿼리 문자열을 객체로 변환합니다.const url = require('url');
const parsedUrl = url.parse('https://example.com:8080/path/name?query=string#hash', true);
console.log(parsedUrl.hostname); // 'example.com'
console.log(parsedUrl.port); // '8080'
console.log(parsedUrl.pathname); // '/path/name'
console.log(parsedUrl.query); // { query: 'string' }
console.log(parsedUrl.hash); // '#hash'
url.format(urlObject)
url.parse()
로 분석된 URL 객체를 다시 문자열로 반환합니다.const url = require('url');
const parsedUrl = {
protocol: 'https:',
hostname: 'example.com',
port: '8080',
pathname: '/path/name',
query: { query: 'string' },
hash: '#hash'
};
console.log(url.format(parsedUrl)); // 'https://example.com:8080/path/name?query=string#hash'
url.resolve(from, to)
const url = require('url');
console.log(url.resolve('https://example.com/path/', 'subpath'));
// 'https://example.com/path/subpath'
console.log(url.resolve('https://example.com/path/', '/subpath'));
// 'https://example.com/subpath'
WHATWG(웹 하이퍼텍스트 애플리케이션 기술 작업 그룹) 표준을 따르는 URL API입니다. 이 방식은 브라우저에서 사용하는 URL API와 동일한 방식을 제공합니다.
URL 생성
WHATWG URL 생성은 new URL()
을 사용합니다.
const { URL } = require('url');
const myURL = new URL('https://example.com:8080/path/name?query=string#hash');
console.log(myURL.hostname); // 'example.com'
console.log(myURL.port); // '8080'
console.log(myURL.pathname); // '/path/name'
console.log(myURL.search); // '?query=string'
console.log(myURL.hash); // '#hash'
WHATWG URL API에서 제공하는 주요 속성
href
: 전체 URL 문자열을 반환합니다.origin
: 프로토콜, 호스트, 포트 번호를 포함한 URL의 기본 부분을 반환합니다.protocol
: URL의 프로토콜을 반환합니다 (http:
또는 https:
등).username
, password
: URL의 사용자 이름 및 비밀번호를 반환합니다 (기본 인증 정보 포함).host
: 호스트 이름과 포트를 포함한 값을 반환합니다.hostname
: URL의 호스트 이름을 반환합니다.port
: URL의 포트 번호를 반환합니다.pathname
: URL 경로를 반환합니다.search
: URL의 쿼리 문자열을 반환합니다 (?
포함).searchParams
: URLSearchParams 객체로 쿼리 파라미터를 쉽게 조작할 수 있습니다.hash
: URL의 해시 부분을 반환합니다 (#
포함).searchParams
를 사용한 쿼리 파라미터 처리
searchParams
는 URL의 쿼리 문자열을 다루는 데 매우 유용합니다.
const myURL = new URL('https://example.com/path?name=John&age=30');
// 특정 쿼리 파라미터 조회
console.log(myURL.searchParams.get('name')); // 'John'
// 쿼리 파라미터 추가
myURL.searchParams.append('gender', 'male');
console.log(myURL.href); // 'https://example.com/path?name=John&age=30&gender=male'
// 쿼리 파라미터 수정
myURL.searchParams.set('age', '31');
console.log(myURL.href); // 'https://example.com/path?name=John&age=31&gender=male'
// 쿼리 파라미터 삭제
myURL.searchParams.delete('name');
console.log(myURL.href); // 'https://example.com/path?age=31&gender=male'
crypto
모듈은 다양한 암호화 기능을 제공하는 내장 모듈입니다. 이 모듈을 사용하면 해싱(hashing), 암호화(encryption), 복호화(decryption), HMAC(해시 기반 메시지 인증 코드), 디지털 서명 및 키 생성 등의 작업을 수행할 수 있습니다. 보안이 중요한 애플리케이션(예: 암호 저장, 데이터 무결성 확인, 네트워크 보안 통신)에서 많이 사용됩니다.
해시 함수는 임의의 길이를 가진 데이터를 고정된 길이의 해시 값으로 변환하는 함수입니다. crypto
모듈에서는 다양한 해시 알고리즘을 제공합니다(예: SHA-256
, MD5
, SHA-1
).
const crypto = require('crypto');
// SHA-256 해시 생성
const hash = crypto.createHash('sha256').update('Hello World').digest('hex');
console.log(hash); // 7f83b1657ff1fc53b92dc18148a1d065...
// MD5 해시 생성
const md5Hash = crypto.createHash('md5').update('Hello World').digest('hex');
console.log(md5Hash); // b10a8db164e0754105b7a99be72e3fe5
createHash(algorithm)
: 사용할 해시 알고리즘을 선택 (sha256
, md5
, sha512
등).update(data)
: 해시할 데이터를 입력합니다.digest([encoding])
: 해시값을 생성하며, hex
, base64
, binary
등의 인코딩 방식을 지정할 수 있습니다.HMAC은 메시지의 무결성과 인증을 확인하기 위해 비밀키와 해시 함수를 함께 사용하는 방식입니다.
const crypto = require('crypto');
// HMAC 생성
const secret = 'mysecretkey';
const hmac = crypto.createHmac('sha256', secret).update('Hello World').digest('hex');
console.log(hmac); // a591a6d40bf420404a011733cfb7b190
createHmac(algorithm, key)
: 사용할 해시 알고리즘과 비밀키를 지정.update(data)
: HMAC에 입력할 데이터를 지정합니다.digest([encoding])
: HMAC 값을 생성하며 인코딩 방식을 지정할 수 있습니다. (hex
, base64
, binary
등)대칭키 암호화와 비대칭키 암호화 두 가지 방식이 있습니다.
1 ) 대칭키 암호화 (AES 등)
대칭키 암호화는 암호화와 복호화에 같은 키를 사용하는 방식입니다.
const crypto = require('crypto');
// 암호화에 사용할 키와 초기화 벡터(IV)
const key = crypto.randomBytes(32); // 32 바이트 키 (AES-256)
const iv = crypto.randomBytes(16); // 16 바이트 IV
// 암호화
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update('Hello World', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log('Encrypted:', encrypted);
// 복호화
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log('Decrypted:', decrypted);
createCipheriv(algorithm, key, iv)
: 암호화 알고리즘과 키, 초기화 벡터(IV)를 사용해 암호화 스트림 생성.createDecipheriv(algorithm, key, iv)
: 복호화 스트림 생성.update(data, inputEncoding, outputEncoding)
: 암호화 또는 복호화할 데이터와 인코딩을 지정.final([outputEncoding])
: 암호화 또는 복호화된 최종 결과 반환.2 ) 비대칭키 암호화 (RSA 등)
비대칭키 암호화는 공개키로 암호화하고, 개인키로 복호화하는 방식입니다. 주로 데이터의 무결성 및 서명 검증에 사용됩니다.
const crypto = require('crypto');
// RSA 키 페어 생성
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
// 메시지 암호화
const encryptedMessage = crypto.publicEncrypt(publicKey, Buffer.from('Hello World'));
console.log('Encrypted Message:', encryptedMessage.toString('hex'));
// 메시지 복호화
const decryptedMessage = crypto.privateDecrypt(privateKey, encryptedMessage);
console.log('Decrypted Message:', decryptedMessage.toString());
디지털 서명은 데이터의 무결성을 확인하고, 메시지가 특정 개인에게서 온 것임을 보장하는 데 사용됩니다.
const crypto = require('crypto');
// RSA 키 페어 생성
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
// 메시지 서명 생성
const sign = crypto.createSign('sha256');
sign.update('Hello World');
const signature = sign.sign(privateKey, 'hex');
console.log('Signature:', signature);
// 서명 검증
const verify = crypto.createVerify('sha256');
verify.update('Hello World');
const isValid = verify.verify(publicKey, signature, 'hex');
console.log('Signature valid:', isValid);
createSign(algorithm)
: 서명을 만들 때 사용할 해시 알고리즘을 선택.sign(privateKey, [outputEncoding])
: 개인키를 사용해 서명을 생성.createVerify(algorithm)
: 서명을 검증할 때 사용할 해시 알고리즘 선택.verify(publicKey, signature, [inputEncoding])
: 공개키를 사용해 서명을 검증.암호화에 사용할 대칭키 또는 비대칭키를 생성할 수 있습니다.
const { generateKeyPairSync } = require('crypto');
// RSA 키 페어 생성
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
modulusLength: 2048, // 키 크기 (비트)
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
console.log('Public Key:', publicKey);
console.log('Private Key:', privateKey);