Encryption & Decryption

The following Python 2.7 encryption examples use the PyCrypto cryptography toolkit or the M2Crypto cryptography toolkit.

Encrypt Message - PyCrypto

Encrypt message using RSA public key with PKCS1-OAEP padding:

def encrypt_RSA(public_key_loc, message):
    '''
    param: public_key_loc Path to public key
    param: message String to be encrypted
    return base64 encoded encrypted string
    '''
    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_OAEP
    key = open(public_key_loc, "r").read()
    rsakey = RSA.importKey(key)
    rsakey = PKCS1_OAEP.new(rsakey)
    encrypted = rsakey.encrypt(message)
    return encrypted.encode('base64')

Decrypt Package - PyCrypto

Decrypt a package using RSA private key with PKCS1-OAEP padding:

def decrypt_RSA(private_key_loc, package):
    '''
    param: public_key_loc Path to your private key
    param: package String to be decrypted
    return decrypted string
    '''
    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_OAEP
    from base64 import b64decode
    key = open(private_key_loc, "r").read()
    rsakey = RSA.importKey(key)
    rsakey = PKCS1_OAEP.new(rsakey)
    decrypted = rsakey.decrypt(b64decode(package))
    return decrypted

Encrypt Message - M2Crypto

Encrypt message using RSA public key with PKCS1-OAEP padding:

def encrypt_RSA(public_key_loc, message):
    '''
    param: public_key_loc Path to public key
    param: message String to be encrypted
    return base64 encoded encrypted string
    '''
    from M2Crypto import RSA, BIO
    key = open(public_key_loc, "r").read()
    pubkey = str(key).encode('utf8')
    bio = BIO.MemoryBuffer(pubkey)
    rsa = RSA.load_pub_key_bio(bio)
    encrypted = rsa.public_encrypt(message, RSA.pkcs1_oaep_padding)
    return encrypted.encode('base64')

Decrypt Package - M2Crypto

Decrypt a package using RSA private key with PKCS1-OAEP padding:

def decrypt_RSA(private_key_loc, package):
    '''
    param: public_key_loc Path to your private key
    param: package String to be decrypted
    return decrypted string
    '''
    from base64 import b64decode
    from M2Crypto import BIO, RSA
    key = open(private_key_loc, "r").read()
    priv_key = BIO.MemoryBuffer(key.encode('utf8'))
    key = RSA.load_key_bio(priv_key)
    decrypted = key.private_decrypt(b64decode(package), RSA.pkcs1_oaep_padding)
    return decrypted

User Contributed

LaunchKey links to user contributed code as a resource to its community. LaunchKey does not in any way guarantee or warrant the quality and security of these code bases. User contributed code is supported by the creators. If you do find a link from the site to user contributed code that is malicious or inappropriate in any way, please report that link to LaunchKey immediately and we will investigate the claim. Submit any issue to LaunchKey support at https://launchkey.com./support. ×