How do I encrypt and decrypt a string in python?

后端 未结 8 1422
忘了有多久
忘了有多久 2020-11-28 05:36

I have been looking for sometime on how to encrypt and decrypt a string. But most of it is in 2.7 and anything that is using 3.2 is not letting me print it or add it to a st

相关标签:
8条回答
  • 2020-11-28 06:17

    For Encryption

      def encrypt(my_key=KEY, my_iv=IV, my_plain_text=PLAIN_TEXT): 
    
           key = binascii.unhexlify('ce975de9294067470d1684442555767fcb007c5a3b89927714e449c3f66cb2a4')
           iv = binascii.unhexlify('9aaecfcf7e82abb8118d8e567d42ee86')
    
           padder = PKCS7Padder()
           padded_text = padder.encode(my_plain_text)
    
          encryptor = AES.new(key, AES.MODE_CBC, iv, segment_size=128)  # Initialize encryptor
          result = encryptor.encrypt(padded_text)  
    
         return {
             "plain": my_plain_text,
             "key": binascii.hexlify(key),
             "iv": binascii.hexlify(iv),
             "ciphertext": result
    }
    
    0 讨论(0)
  • 2020-11-28 06:18

    You can do this easily by using the library cryptocode. Here is how you install:

    pip install cryptocode
    

    Encrypting a message (example code):

    import cryptocode
    
    encoded = cryptocode.encrypt("mystring","mypassword")
    ## And then to decode it:
    decoded = cryptocode.decrypt(encoded, "mypassword")
    

    Documentation can be found here

    0 讨论(0)
提交回复
热议问题