Personal website

16

2013, Oct

Encrypt and decrypt strings using RSA

Keywords rsa, encrypt, django, python

Recently I had to build an encryption/decryption functions to be used in my django project, something I could use to encrypt and decrypt strings, for that, I decided to go with python Crypto module and used a generated SSH keys to handle creation of encryption and decryption. In this blog post, I will walk you through the process and potential problems you may face.

First of all, you will need to generate the SSH keys


ssh-keygen -t rsa
# Creates a new ssh key
# Generating public/private rsa key pair.
# Enter file in which to save the key (/Users/you/.ssh/id_rsa): [Specify folder to dump the keys]
ssh-add id_rsa

Once you have your public and private key generated, copy them somewhere in your project folder for me I used project/misc/encrypt-keys/  now, you can build your encrypt and decrypt functions

 


import os
from django.conf import settings
from django.core.cache import cache
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

def encrypt_func(message):
    """
    return encrypted string
    """
    key = cache.get('public_key', None)
    if key is None:
        base_dir = getattr(settings, 'BASE_DIR')
        public_key_loc = os.path.join(base_dir, 'project/misc/encrypt-keys/rsa.pub')
        key = open(public_key_loc, "r").read()
        cache.set('public_key', key, 60 * 60)

    rsakey = RSA.importKey(key)
    rsakey = PKCS1_OAEP.new(rsakey)
    encrypted = rsakey.encrypt(message)
    return encrypted


def decrypt_func(message):
    """
    return decrypted string
    """
    key = cache.get('private_key', None)
    if key is None:
        base_dir = getattr(settings, 'BASE_DIR')
        private_key_loc = os.path.join(base_dir, 'project/misc/encrypt-keys/rsa')
        key = open(private_key_loc, "r").read()
        cache.set('private_key', key, 60 * 60)

    rsakey = RSA.importKey(key)
    rsakey = PKCS1_OAEP.new(rsakey)
    decrypted = rsakey.decrypt(message)
    return decrypted

 

The above encrypt_func and decrypt_func will store the public and private keys in cached strings, for that to work a cache backend needs to be configured and BASE_DIR to be set as project absolute path in your settings.py file. Hope you find this useful, 

I recommend strongly to use caching, specially if you consume your functions frequently otherwise this would be very expensive operation.

Salam.


comments powered by Disqus