1 const crypto = require("crypto");
2 const { generateKeyPair } = require("crypto");
4 const TAG = '[DeviceHome][security.js]';
6 module.exports.Security = class Security {
12 getKeyPairPromise(pincode) {
13 console.log(`${TAG} getKeyPairPromise`);
14 return new Promise((resolve, reject) => {
15 console.log(`${TAG} Generating key will take some time..`);
16 generateKeyPair("rsa", {
25 // TODO: Enable ciper and passphrase
26 //cipher: "aes-256-cbc",
29 }, (err, publicKey, privateKey) => {
30 // Handle errors and use the generated key pair.
33 privateKey: privateKey
39 awaitKeyPair(pincode) {
40 return this.getKeyPairPromise(pincode).then(r => {
41 this.privateKey = r.privateKey;
42 this.publicKey = r.publicKey;
43 console.log(`${TAG}[awaitKeyPair] RSA keys are generated`);
45 console.log(`${TAG} Error : ${err}`);
49 // TODO: Use following APIs instead of JSEncryptLib
50 decryptWithPrivateKey(encryptedString, pincode) {
51 const key = crypto.createPrivateKey({
56 const encrypted = crypto.privateDecrypt(key, Buffer.from(encryptedString, "base64"));
57 const decryptedString = encrypted.toString("utf8");
58 return decryptedString;
61 encryptWithPrivateKey(plain, pincode) {
62 const keyp = crypto.createPrivateKey({
67 const encrypted = crypto.privateEncrypt(keyp, Buffer.from(plain));
68 const encryptedString = encrypted.toString("base64");
69 return encryptedString;
72 decryptWithPublicKey(encryptedString) {
73 const decrypted = crypto.publicDecrypt(this.publicKey, Buffer.from(encryptedString, "base64"));
74 const decryptedString = decrypted.toString("utf8");
75 return decryptedString;
78 encryptWithPublicKey(plain) {
79 const encrypted = crypto.publicEncrypt(this.publicKey, Buffer.from(plain));
80 const encryptedString = encrypted.toString("base64");
81 return encryptedString;
85 console.log(`${TAG} getPrivateKey`);
86 return this.privateKey;
90 console.log(`${TAG} getPublicKey`);
91 return this.publicKey;