const crypto = require("crypto");
const myPrivateKeyB64 = "키 입력";
const theirPublicKeyB64 = "키 입력";
function x25519PrivateKeyFromRaw(raw) {
return crypto.createPrivateKey({
key: Buffer.concat([
Buffer.from("302e020100300506032b656e04220420", "hex"),
raw,
]),
format: "der",
type: "pkcs8",
});
}
function x25519PublicKeyFromRaw(raw) {
return crypto.createPublicKey({
key: Buffer.concat([
Buffer.from("302a300506032b656e032100", "hex"),
raw,
]),
format: "der",
type: "spki",
});
}
function deriveKey(myPrivateKeyB64, theirPublicKeyB64) {
const myPrivateKey = x25519PrivateKeyFromRaw(
Buffer.from(myPrivateKeyB64, "base64")
);
const theirPublicKey = x25519PublicKeyFromRaw(
Buffer.from(theirPublicKeyB64, "base64")
);
const sharedSecret = crypto.diffieHellman({
privateKey: myPrivateKey,
publicKey: theirPublicKey,
});
const hkdfKey = crypto.hkdfSync(
"sha256",
sharedSecret,
Buffer.alloc(0),
Buffer.alloc(0),
32
);
return crypto
.createHash("sha256")
.update(Buffer.from(hkdfKey))
.digest();
}
function encrypt(key, plaintext) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv(
"aes-256-gcm",
key,
iv
);
const encrypted = Buffer.concat([
cipher.update(plaintext, "utf8"),
cipher.final(),
]);
const tag = cipher.getAuthTag();
return {
iv: iv.toString("base64"),
ciphertext: encrypted.toString("base64"),
tag: tag.toString("base64"),
};
}
function decrypt(key, data) {
const decipher = crypto.createDecipheriv(
"aes-256-gcm",
key,
Buffer.from(data.iv, "base64")
);
decipher.setAuthTag(
Buffer.from(data.tag, "base64")
);
const decrypted = Buffer.concat([
decipher.update(
Buffer.from(data.ciphertext, "base64")
),
decipher.final(),
]);
return decrypted.toString("utf8");
}
const key = deriveKey(
myPrivateKeyB64,
theirPublicKeyB64
);
const decrypted = decrypt(
key,
encrypted
);
이 코드에서 decrypt 함수 써보세요