Thursday, 12 June 2014

How to encrypt and decrypt data in python



  • Encryption and decryption is standard, well-known algorithms for data secure.
  • The established, efficient pycrypto library provides the algorithm implementations (the cipher used is AES256).
  • It includes a check (an HMAC with SHA256) to warn when ciphertext data are modified.
  • It tries to make things as secure as possible when poor quality passwords are used (PBKDF2 with SHA256, a 256 bit random salt (increased from 128 bits in release 3.0.0), and 10,000 rounds). But that doesn't mean you should use a poor password!.
  • Using a library, rather than writing your own code, means that we have less solutions to the same problem. That means more chance of finding bugs, which means more reliable, more secure code.

How to encrypt data


Step 1: Download the Crypto package from here and install it in your system.

For windows: 
        pycrypto-2.3.win32-py2.7.exe [545 Kb] [Python 2.7] [32 bit] 
        pycrypto-2.3.win-amd64-py2.7.exe [572 Kb] [Python 2.7] [64 bit]
 
For Linux or Mac and other OS: 
        https://www.dlitz.net/software/pycrypto/


Step 2: Keep pkcs7.py file in your root directory.



Step 3: First you have to define a self-created 16 digit key( key and IV will be 16 digit, 32,64…) which you know, only that key will decrypt data otherwise it will not decrypt. Here I am doing encoding by PKCS7 then encryption by crypto and again encoded by base64. 

from Crypto.Cipher import AES
from pkcs7 import PKCS7Encoder
import pkcs7,threading, base64


text=’my secret data’
key = 'secret#456!23key'
iv = 'Key@123Key@123fd'
aes = AES.new(key, AES.MODE_CBC, iv)
encoder = PKCS7Encoder()
pad_text = encoder.encode(text)
cipher = aes.encrypt(pad_text)
enc_cipher = base64.b64encode(cipher)
print enc_cipher



Output is 


CdGubxMcUT1vM0p1XkNscw==

How to decrypt data


For decryption we have to follow apposite procedure means 1st  we have to decode by base64 , decrypt by Crypto and then decode by PKCS7.

decodetext =  base64.b64decode(enc_cipher)
aes = AES.new(key, AES.MODE_CBC, iv)
cipher = aes.decrypt(decodetext)
pad_text = encoder.decode(cipher)
print pad_text


Output is
 

my secret data



Crypto cypher encryption is very secure.
 

No comments:

Post a Comment