-
crypto 모듈 - 암복호화, MAC, 난수, 서명자바스크립트/모듈 & 내장함수 2023. 8. 6. 20:48
const crypto = require('crypto'); // 암호화 키 (32바이트) const encryptionKey = crypto.randomBytes(32); // 초기화 벡터 (16바이트) const iv = crypto.randomBytes(16); // 암호화할 데이터 const data = 'Hello, World!'; // 암호화 함수 function encrypt(text) { const cipher = crypto.createCipheriv('aes-256-cbc', encryptionKey, iv); let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); return encrypted; } // 복호화 함수 function decrypt(encryptedText) { const decipher = crypto.createDecipheriv('aes-256-cbc', encryptionKey, iv); let decrypted = decipher.update(encryptedText, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } // 데이터 암호화 const encryptedData = encrypt(data); console.log('Encrypted Data:', encryptedData); // 데이터 복호화 const decryptedData = decrypt(encryptedData); console.log('Decrypted Data:', decryptedData);
암복호화 예제
aes 외에 des, bf (blowfish) 등을 사용 가능하다.
출력은 utf8외에 hex, base64, binary, utf8, ascii 등을 사용 가능
const crypto = require('crypto'); // 메시지와 공유 비밀키 const message = 'Hello, HMAC!'; const secretKey = 'mySecretKey'; // HMAC 생성 함수 function generateHmac(message, secretKey) { // sha256 해시 함수를 사용하여 HMAC 생성 const hmac = crypto.createHmac('sha256', secretKey); // 메시지를 HMAC에 업데이트 hmac.update(message); // HMAC 결과를 16진수 문자열로 변환하여 리턴 return hmac.digest('hex'); } // HMAC 생성 예제 실행 const hmacResult = generateHmac(message, secretKey); console.log('HMAC:', hmacResult);
hmac 예제 (메시지 인증 코드)
const crypto = require('crypto'); // 16바이트 길이의 난수 생성 함수 function generateRandomBytes() { const bytes = crypto.randomBytes(16); return bytes.toString('hex'); } // 16바이트 길이의 난수 생성 예제 실행 const randomBytesResult = generateRandomBytes(); console.log('Random Bytes:', randomBytesResult);
난수 생성 예제
const crypto = require('crypto'); // 비밀 키 생성 (테스트용으로 생성) const privateKey = crypto.generateKeyPairSync('ec', { namedCurve: 'secp256k1', publicKeyEncoding: { type: 'spki', format: 'pem', }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', }, }); // 데이터 생성 (테스트용 데이터) const data = 'Hello, world!'; // 서명 생성 함수 function createSignature(privateKey, data) { const sign = crypto.createSign('SHA256'); sign.update(data); sign.end(); const signature = sign.sign(privateKey, 'hex'); return signature; } // 서명 검증 함수 function verifySignature(publicKey, signature, data) { const verify = crypto.createVerify('SHA256'); verify.update(data); verify.end(); return verify.verify(publicKey, signature, 'hex'); } // 서명 생성 const signature = createSignature(privateKey.privateKey, data); console.log('Signature:', signature); // 서명 검증 (유효한 서명인 경우 true 반환) const isSignatureValid = verifySignature(privateKey.publicKey, signature, data); console.log('Is Signature Valid?', isSignatureValid);
전자 서명 예제
'자바스크립트 > 모듈 & 내장함수' 카테고리의 다른 글
JS Math (0) 2023.08.12 NET 모듈로 서버 & 클라이언트 만들기 (0) 2023.08.08 crypto 모듈 - 해싱 (0) 2023.08.06 setTimeout(), setInterval() (0) 2023.08.05 Worker_threads (0) 2023.08.05