Skip to content

Instantly share code, notes, and snippets.

@ninovsnino
Created November 30, 2015 06:57
Show Gist options
  • Save ninovsnino/35bc50ab6c8d7e716102 to your computer and use it in GitHub Desktop.
Save ninovsnino/35bc50ab6c8d7e716102 to your computer and use it in GitHub Desktop.
RSA key gen, encrypt/decrypt, and sign/verify with PyCrypto
# using pycrypto (2.3)
from Crypto.PublicKey import RSA
# generate(self, bits, randfunc=None, progress_func=None) method of Crypto.PublicKey.RSA.RSAImplementation instance
new_key = RSA.generate(bits=2048)
# exportKey(self, format='PEM') method of Crypto.PublicKey.RSA._RSAobj instance
# Export the RSA key. A string is returned
# with the encoded public or the private half
# under the selected format.
#
# format: 'DER' (PKCS#1) or 'PEM' (RFC1421)
public_key = new_key.publickey().exportKey("PEM")
private_key = new_key.exportKey("PEM")
tpl = new_key.encrypt('ninovsnino', 12345670)
print new_key.decrypt(tpl[0]) # 'ninovsnino'
tpl = new_key.sign('ninovsnino', 01234567)
print new_key.verify('ninovsnino', tpl) # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment