-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
62 lines (53 loc) · 1.55 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import * as crypto from "crypto";
import * as readline from "readline";
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
function generateKeys() {
const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
});
return { publicKey, privateKey };
}
function encryptMessage(publicKey: string, message: string): string {
const encrypted = crypto.publicEncrypt(
{
key: publicKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: "sha256",
},
Buffer.from(message)
);
return encrypted.toString("base64");
}
function decryptMessage(privateKey: string, encryptedMessage: string): string {
const decrypted = crypto.privateDecrypt(
{
key: privateKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: "sha256",
},
Buffer.from(encryptedMessage, "base64")
);
return decrypted.toString("utf8");
}
const { publicKey, privateKey } = generateKeys();
function startEncryptionProcess() {
rl.question("Digite a mensagem que deseja cifrar: ", (inputMessage) => {
const encryptedMessage = encryptMessage(publicKey, inputMessage);
console.log("\nMensagem Cifrada:", encryptedMessage);
const decryptedMessage = decryptMessage(privateKey, encryptedMessage);
console.log("Mensagem Decifrada:", decryptedMessage);
rl.close();
});
}
startEncryptionProcess();