Created
May 20, 2020 02:55
-
-
Save deskoh/8d0ac1c1d6200ac6ea426efb4ffd0493 to your computer and use it in GitHub Desktop.
NodeJS RSA Cryptoraphy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const crypto = require('crypto'); | |
| const keyPair = crypto.generateKeyPairSync('rsa', { | |
| // Max length of plaintext = (512 / 8) - 42 = 22 bytes | |
| modulusLength: 512, | |
| publicKeyEncoding: { | |
| type: 'spki', | |
| format: 'pem' | |
| }, | |
| privateKeyEncoding: { | |
| type: 'pkcs8', | |
| format: 'pem', | |
| cipher: 'aes-256-cbc', | |
| passphrase: '' | |
| } | |
| }); | |
| // Defining a text to be encrypted | |
| const plainText = "1234567890123456789012"; | |
| // Defining encrypted text | |
| const encrypted = crypto.publicEncrypt(keyPair.publicKey, Buffer.from(plainText, 'utf-8')).toString('base64'); | |
| const decrypted = crypto.privateDecrypt(keyPair.privateKey, Buffer.from(encrypted, 'base64')).toString('utf-8') | |
| console.log("Plaintext:", plainText); | |
| console.log("Encrypted:", encrypted); | |
| console.log("Decrypted:", decrypted); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment