DEV Community

SilvenLEAF
SilvenLEAF

Posted on • Updated on

RSA Encryption Decryption

RSA Encryption Decryption

How does this work?

  • [x] generate SECRET_KEY and PUBLIC_KEY key pair to encrypt decrypt files
  • [x] share this PUBLIC_KEY of your SECRET_KEY to the decrypter machine
  • [x] encrypt the data on encrypter machine using the given PUBLIC_KEY of the decrypter
  • [x] send this encrypted file to the decrypter machine
  • [x] decrypt the file using the SECRET_KEY of your given PUBLIC_KEY on decrypter machine

Decrypter Machine

  • [x] generate SECRET_KEY and PUBLIC_KEY key pair using this function
const  fs  =  require("fs");
const  crypto  =  require("crypto");

const  keyPair  =  crypto.generateKeyPairSync("rsa", {
modulusLength: 4096, // bits - standard for RSA keys
publicKeyEncoding: {
type: 'pkcs1', // "public key cryptography standards 1"
format: 'pem'  // most common formatting choice
},
privateKeyEncoding: {
type: 'pkcs1', // "public key cryptography standards 1"
format: 'pem'  // most common formatting choice
}
});

fs.writeFileSync(publicKeyLoc, keyPair.publicKey);
fs.writeFileSync(privateKeyLoc, keyPair.privateKey);
Enter fullscreen mode Exit fullscreen mode
  • [x] share the PUBLIC_KEY to the encrypter machine

Encrypter Machine

  • [x] encrypt the data using the given PUBLIC_KEY of the decrypter machine
const  fs  =  require("fs");
const  crypto  =  require("crypto");

const  publicKey  =  fs.readFileSync(publicKeyFileLocation, "utf8");
const  encryptedBuffer  =  crypto.publicEncrypt(publicKey, Buffer.from(fileBuffer));
Enter fullscreen mode Exit fullscreen mode

share this encrypted file to your decrypter machine

Decrypter Machine

  • [x] decrypt the file
const  fs  =  require("fs");
const  crypto  =  require("crypto");

const  privateKey  =  fs.readFileSync(privateKeyFileLocation, "utf8");
const  keyOptions  =  { key: privateKey  };
const  decryptedBuffer  =  crypto.privateDecrypt(keyOptions, Buffer.from(fileBuffer));
const decryptedText =  decryptedBuffer.toString("utf8");
Enter fullscreen mode Exit fullscreen mode

yippie banzai we did it!

Top comments (0)