Skip to content

Instantly share code, notes, and snippets.

@a4amaan
Forked from PradyumnaKrishna/crypto.js
Created March 28, 2023 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a4amaan/7fa9de58b7f137dea148c2af237d3f89 to your computer and use it in GitHub Desktop.
Save a4amaan/7fa9de58b7f137dea148c2af237d3f89 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment