Skip to content

Instantly share code, notes, and snippets.

@Snegovikufa
Created March 25, 2013 05:14
Show Gist options
  • Save Snegovikufa/5235069 to your computer and use it in GitHub Desktop.
Save Snegovikufa/5235069 to your computer and use it in GitHub Desktop.
Encrypt file with AES and RSA private key
# -*- coding: utf-8 -*-
__author__ = 'Rustam Safin'
import base64
from M2Crypto.RSA import (load_key, pkcs1_padding, gen_key)
from Crypto.Cipher import AES
from Crypto import Random
from sys import getfilesystemencoding
def encodeToUTF8 (s) :
"""
@param s: unicode or string
@return: unicode in UTF-8
"""
if isinstance(s, str) :
try :
s = s.decode (getfilesystemencoding())
except (UnicodeDecodeError, UnicodeEncodeError) :
return s
if isinstance(s, unicode) :
try :
s = s.encode ('utf-8')
except UnicodeEncodeError :
return s
return s
def gimmepw(*args):
"""
@return: private key password
"""
return 'mypassword'
k = gen_key(1024, 65537)
k.save_key('/home/user/private.pem', callback=gimmepw)
k.save_pub_key('/home/user/public.pem')
def main (key_filename, in_filename, out_filename) :
key_filename = encodeToUTF8(key_filename)
in_filename = encodeToUTF8(in_filename)
out_filename = encodeToUTF8(out_filename)
with open (in_filename) as f :
text_to_encrypt = f.read ()
# Encrypting with AES
key = b'veryInterestingKeyWith32Length:)'
iv = Random.new ().read (AES.block_size)
cipher = AES.new (key, AES.MODE_CFB, iv)
msg = cipher.encrypt (text_to_encrypt)
# Encrypting AES key with RSA private key
pri = load_key (key_filename, gimmepw)
encrypted_aes_key = pri.private_encrypt (iv, pkcs1_padding)
with open (out_filename, "wb") as f :
f.write (encrypted_aes_key + msg)
if __name__ == "__main__" :
import sys
if len (sys.argv[1:]) < 3 :
print ("Usage: python encrypter.py "
"/home/user/private_key.pem "
"/home/user/input.txt "
"/home/user/output.txt")
main (*sys.argv[1:])
@masoudr
Copy link

masoudr commented Oct 11, 2017

Could you please add the decryption script too?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment