RSA encryption and decryption in Python

前端 未结 6 1901
别那么骄傲
别那么骄傲 2020-11-28 06:35

I need help using RSA encryption and decryption in Python.

I am creating a private/public key pair, encrypting a message with keys and writing message to a file. Th

6条回答
  •  囚心锁ツ
    2020-11-28 07:15

    In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:

    import Crypto
    from Crypto.PublicKey import RSA
    from Crypto import Random
    import ast
    
    random_generator = Random.new().read
    key = RSA.generate(1024, random_generator) #generate pub and priv key
    
    publickey = key.publickey() # pub key export for exchange
    
    encrypted = publickey.encrypt('encrypt this message', 32)
    #message to encrypt is in the above line 'encrypt this message'
    
    print 'encrypted message:', encrypted #ciphertext
    f = open ('encryption.txt', 'w')
    f.write(str(encrypted)) #write ciphertext to file
    f.close()
    
    #decrypted code below
    
    f = open('encryption.txt', 'r')
    message = f.read()
    
    
    decrypted = key.decrypt(ast.literal_eval(str(encrypted)))
    
    print 'decrypted', decrypted
    
    f = open ('encryption.txt', 'w')
    f.write(str(message))
    f.write(str(decrypted))
    f.close()
    

提交回复
热议问题