-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathencrypting.js
73 lines (60 loc) · 1.54 KB
/
encrypting.js
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
63
64
65
66
67
68
69
70
71
72
73
const crypto = require('crypto');
const fs = require('fs');
// Using a function generateKeyFiles
function generateKeyFiles() {
const keyPair = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'pass',
},
});
// Creating private key file
fs.writeFileSync('private_key', keyPair.privateKey);
}
// Generate keys
generateKeyFiles();
// Creating a function to encrypt string
function encryptString(plaintext, privateKeyFile) {
const privateKey = fs.readFileSync(privateKeyFile, 'utf8');
// privateEncrypt() method with its parameters
const encrypted = crypto.publicEncrypt(
{
key: privateKey,
passphrase: 'pass',
},
Buffer.from(plaintext),
);
return encrypted.toString('hex');
}
// DO NOT MODIY BELOW //
// Defining a text to be encrypted
const plainText = 'hello';
// Defining encrypted text
const encrypted = encryptString(plainText, './private_key');
// Prints plain text
console.log('Plaintext:', plainText);
// Prints encrypted text
console.log('Encrypted: ', encrypted);
const prvkeyStr = fs.readFileSync('./private_key', {
encoding: 'utf8',
flag: 'r',
});
const prvkey = crypto.createPrivateKey({
key: prvkeyStr,
format: 'pem',
passphrase: 'pass',
});
let plaintext = crypto.privateDecrypt(
{
key: prvkey,
},
Buffer.from(encrypted, 'hex'),
);
console.log('decrypted: ', plaintext.toString());