Skip to content

Instantly share code, notes, and snippets.

@PradyumnaKrishna
Last active March 28, 2023 20:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PradyumnaKrishna/68e224c62bf7cdf415a563ab06c14c03 to your computer and use it in GitHub Desktop.
Save PradyumnaKrishna/68e224c62bf7cdf415a563ab06c14c03 to your computer and use it in GitHub Desktop.
RSA Encryption/Decryption in Python and Nodejs
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()
}
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)
@welcomemat-services
Copy link

Please provide an example.

@PradyumnaKrishna
Copy link
Author

PradyumnaKrishna commented Sep 18, 2022

Please provide an example.

Python3

Install pycrypto dependency.

pip3 install pycryptodome  # python >= 3.8
pip3 install pycrypto  # python < 3.8
# Import the functions here.
>>> pub, priv = newkeys(1024)
>>> msg = b'Hello Friend'
>>> encrypted = encrypt(msg, pub)
>>> encrypted
b'\x17\x86Gc\xda\xe8\xaa\xda\x91\x02A\xbb\xf3\x11_q\x8a\xc4\xbf.KC\x87\n\xfb2\xbf\xcf\xf4\xcd\x82\xb4\x7f\x9c\xcf\xd6l\xb9\x97\xf3\x96\x80\xdd<8yGG\xe7:k\x11[\x98\x13\x0f\x049\\\xc8\xf6\x03\x17@1\xb6\\\x9a\xdd\x01\x81\xdai\xcf\xa8&\xdb\xe9\xfb\xa8\x01\xd6w\xf0$=\xe7|\xee\xed\xa9\x9c\xc5\x0f\xb3\x1b\xc1\x98\x1ds7\xe9\xdc\xcc\xf10\xe3\x95\x88\x85\x08\xbdv;\xe5\xec\xb7\x8bJ\x9cz\xc7\x03\xcf\xf2. a'

>>> decrypt(enc_msg, priv)
b'Hello Friend'

Node

> var { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
...     modulusLength: 4096,
...     publicKeyEncoding: {
...         type: 'spki',
...         format: 'pem'
...     }
... });

> encrypted = encryptString("Hello Friend", publicKey)
'EoetC56OEG206efQvNpsIJgiNRU/q413lhmhUjZGl/2Qc3Pa2ddAEYckelqvGeHqFo9KN4RBPV3nrWq0khJIVo5xDPduGkHHOSPpI4aJ2qkD4Dtkhvo6tXXLpqQmdVZvq0rvL3HDOjNq/AE9anp8nOGrupv+BaA3qIUvVY4wrF0oNG3C7T+4gUUWzljxMP6E+OoF6NMv0M02tik2Lgo/iyi/hG5177xBrwKNjXrRIiRNAJFzTPptjvSWtcpBePokXfoSt87wT1tAZ9tBdLZv2/0fDvqL3RkqR56nIX+hW4LW5FkL/1cJpD77bvyLTIkjz9tBlOjUz0F41Ntdob/J33gHkOCy6Zi1suXpiUnGeXZr6hRCBUEI8nU0eNSmof3wXPEWLLAj4xUrq48UzU9vwE6DEgfG9LvGmq0yALPNvXFgLvHPFbDAli5yBJvcHEVDa24YV9E0vpkz4f2X9k6LqNhKh6uMFxJXnBcQ/bRi3CAOT7akX2og3fMHoL4T4dRawg4a4WEj806XDRTiDfMMLsVOIsvbrbkiD02Gb5h/+HYjNCSc8MLGwzcCkw4zMDnTt6AjeN+zHtvntSTeoBC3PDIIOjppg/07MccdLn+mW5I3CKRgx9VztbTy3njQKJzZ9SF6dFkS3zsUWGX6hZwHwpmBxMrz3X8gEVMIEc88Hq4='
> decryptString(encrypted, privateKey)
'Hello Friend'

Nodejs returns the encrypted string in form of base64, where python returns it in form of hex.
I have added type hints in python now.

Edit: If you are interested in client side encryption, FYI, I have done that in my project enigma-protocol.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment