-
-
Save a4amaan/7fa9de58b7f137dea148c2af237d3f89 to your computer and use it in GitHub Desktop.
RSA Encryption/Decryption in Python and Nodejs
This file contains 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'); | |
var { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { | |
modulusLength: 4096, | |
publicKeyEncoding: { | |
type: 'spki', | |
format: 'pem' | |
} | |
}); | |
function encryptString (data, publicKey) { | |
// data: text string to be encrypted | |
// publicKey: Crypto Object or PEM | |
const encrypted = crypto.publicEncrypt( | |
{ | |
key: publicKey, | |
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, | |
oaepHash: "sha256", | |
}, | |
Buffer.from(data) | |
) | |
// Return: Base64 encoded encrypted text | |
return encrypted.toString("base64"); | |
} | |
function decryptString (data, privateKey) { | |
// data: base64 encoded encrypted text | |
// privateKey: Crypto Object or PEM | |
const decrypted = crypto.privateDecrypt( | |
{ | |
key: privateKey, | |
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, | |
oaepHash: "sha256", | |
}, | |
Buffer.from(data, 'base64') | |
) | |
// Return: plain text message | |
return decrypted.toString() | |
} |
This file contains 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
from typing import Tuple | |
from Crypto import Random | |
from Crypto.PublicKey import RSA | |
from Crypto.Cipher import PKCS1_OAEP | |
from Crypto.PublicKey.RSA import RsaKey | |
def newkeys(keysize: int) -> Tuple[RsaKey, RsaKey]: | |
random_generator = Random.new().read | |
key = RSA.generate(keysize, random_generator) | |
private, public = key, key.publickey() | |
return public, private | |
def encrypt(message: bytes, pub_key: RsaKey): | |
cipher = PKCS1_OAEP.new(pub_key) | |
return cipher.encrypt(message) | |
def decrypt(ciphertext: bytes, priv_key: RsaKey): | |
cipher = PKCS1_OAEP.new(priv_key) | |
return cipher.decrypt(ciphertext) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment