FamiHug

RSA, AES

Nov 10th, 2012
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. # coding: utf-8
  2. from Crypto.Cipher import AES
  3. from Crypto.Hash import SHA
  4. from Crypto.PublicKey import RSA
  5. import commands
  6. import random
  7.  
  8. KEYLEN = 16
  9.  
  10. def gen_16_chars_key():
  11.     outfirst = commands.getoutput("date +%N")
  12.     outfirst += commands.getoutput("date +%N")
  13.     return "".join(outfirst[:KEYLEN])
  14.  
  15.  
  16. def blockize(plain):
  17.     """
  18.    Pad the plaintext with random number
  19.    return paddedtext and number of added chars
  20.    """
  21.     cntr = 0
  22.     while len(plain) % KEYLEN != 0:
  23.         cntr += 1
  24.         plain += str(random.randrange(10))
  25.  
  26.     return (plain, cntr)
  27.    
  28.  
  29. def encrypt(plain, enkey):
  30.     obj = AES.new(enkey, AES.MODE_ECB)
  31.     # because data must has len = k * keysize
  32.     padded_plain, padded = blockize(plain)
  33.     obj.encrypt(padded_plain)
  34.     return (obj.encrypt(padded_plain), padded)
  35.  
  36.  
  37. def decrypt(cypher, enkey, padded):
  38.     obj = AES.new(enkey, AES.MODE_ECB)
  39.     padded_plain = obj.decrypt(cypher)
  40.     plain = "".join(padded_plain[:-padded])
  41.     return plain
  42.  
  43.  
  44. def main():
  45.     key = gen_16_chars_key()
  46.     #plain = "hvnsweeting"
  47.     plain = """
  48.    This fixes the problem with randint() which includes the
  49.    endpoint; in Python this is usually not what you want.
  50.    Do not supply the 'int', 'default', and 'maxwidth' arguments."""
  51.     #print len(plain)
  52.     cypher, padded = encrypt(plain, key)
  53.  
  54.     # base64 the cypher
  55.  
  56.     # RSA the key
  57.     private = RSA.generate(1024)
  58.     public = private.publickey()
  59.  
  60.     pkey = private.exportKey()
  61.     Pkey = public.exportKey()
  62.  
  63.     #print pkey
  64.     #print Pkey
  65.  
  66.     print decrypt(cypher, key, padded)
  67.  
  68.     print "Before trans" , key
  69.     encrypted_key = public.encrypt(key, None)
  70.     #print encrypted_key
  71.     print "transfering over internet..."
  72.     print "After trans",  private.decrypt(encrypted_key)
  73.    
  74.  
  75. """
  76.    secret_key = os.urandom(16)
  77.    # Padding (see explanations below)
  78.    plaintext_length = (Crypto.Util.number.size(rsa.n) - 2) / 8
  79.    padding = '\xff' + os.urandom(16)
  80.    padding += '\0' * (plaintext_length - len(padding) - len(secret_key))
  81. """
  82.  
  83.  
  84. if __name__ == "__main__":
  85.     main()
Advertisement
Add Comment
Please, Sign In to add comment