전공과목 정리/시스템종합설계(캡스톤디자인)

[💡시스템종합설계(캡스톤디자인)] node.js crypto 이용하기

최연재 2025. 3. 14. 16:40

공통

node.js에서 crypto를 이용하기 위해 npm 명령어로 다운받고 import한다.

import crypto, { Cipher } from "crypto";

 

AES를 이용한 암/복호화

const key = "01234567890123456789012345678901"
const iv =Buffer.alloc(16,0);

// 암호화
const AESencrypt = crypto.createCipheriv("aes-256-cbc", key, iv);
const cipertext = AESencrypt.update("Hello world", "utf-8", "base64") + AESencrypt.final("base64");

console.log(cipertext);

// 복호화
const AESdecrypt = crypto.createDecipheriv("aes-256-cbc", key, iv);
const plaitext =AESdecrypt.update(cipertext, "base64", "utf8") + AESdecrypt.final("utf8");

console.log("plain text = " + plaitext);

 

RSA를 이용한 암/복호화

const {publicKey, privateKey} = crypto.generateKeyPairSync("rsa", {
  modulusLength : 2048
})

console.log("public key: " + publicKey.export({
  type: "pkcs1",format: "pem"
}));
console.log("private key: " + privateKey.export({
  type: "pkcs1",format: "pem"
}));

// 암호화
const rsaCiphertext = crypto.publicEncrypt({
  key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256"
}, Buffer.from("Hello world!")); // string -> buffer에 옮기기

console.log("ciphertext: " + rsaCiphertext.toString("base64"));

// 복호화
const rsaPlaintext = crypto.privateDecrypt({
  key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256"
}, rsaCiphertext);

console.log("plain text : " + rsaPlaintext);

 

디지털 서명

const originaltext = "hi hello nice to meet you";
const {publicKey, privateKey} = crypto.generateKeyPairSync("dsa", {
  modulusLength: 2048
});

console.log("Public key : " + publicKey.export({
  type:"spki", format:"pem"
}));

console.log("private Key : " + privateKey.export({
  type:"pkcs8", format:"pem"
}));

const signature = crypto.sign("SHA256", originaltext, privateKey);
console.log("signature : " + signature.toString("base64"));

const verify = crypto.verify("SHA256", originaltext, publicKey, signature);
console.log("verify : " + verify);