LoginSignup
0
0

More than 1 year has passed since last update.

Python で文字列暗号化のやりかた 覚え書き

Last updated at Posted at 2022-05-20
>>> from cryptography.fernet import Fernet
>>> key = Fernet.generate_key()
>>> f = Fernet(key)
>>> str1 = f.encrypt(b'STRING')
>>> str2 = f.encrypt(b'STRING')
>>> str3 = f.encrypt(b'STRING')
>>> f.decrypt(str1)
b'STRING'
>>> f.decrypt(str2)
b'STRING'
>>> f.decrypt(str3)
b'STRING'
>>> str1
b'gAAAAABihzIr-f-8aNMSgmJOLFldYudDl_UR1poI9WXFhT2xHWuaWnEBtUoggxVufyAf2s27uxbpw_0uv6kiuxfmZfPOUs8HyA=='
>>> str2
b'gAAAAABihzIwApIVnYqTZ5Ltilmmheegl6H1uf4mNZNIaV_bu_T7aSawYvkd73qlQ3YhSKNYh-59a-BLxT4x8JpHsjBqb5n_Ug=='
>>> str3
b'gAAAAABihzI1neTjCSlJ6SJ2D2kkfYT67xhmtJNPyUEpiatVE70oVhbAgX9ln9dr749elm3VUSWA7XyDvGwB7xNJ4e_dMQj0Qw=='
>>>
>>> from Crypto.Cipher import AES
>>> from Crypto.Random import get_random_bytes
>>> key = get_random_bytes(32)
>>> key
b'\xa5)\x8d\xcc@\x97\xe1\x0ec\xac\x07\xec\x92\r"q\xc8L\xe4t^\xb6U\x1e\x02\x9a(=d\xc8H\xc5'
>>> cipher = AES.new(key, AES.MODE_GCM)
>>> enc_str1, tag = cipher.encrypt_and_digest(b'STRING')
>>> enc_str1
b'\xa6\xf1\xdb\x91\x92\xbb'
>>> tag
b'VW\xf8\xac\xb5\x17@K\xa3\xf0\x7f\x8ad\xa7~\xb3'
>>> cipher.nonce
b'f9\xd5\x0e\x99\x96\xd0\xba\xd9\x83Y\xa1\xfe\xcaX\xfd'
>>> f_decrypt = AES.new(key, AES.MODE_GCM, cipher.nonce)
>>> dec_str1 = f_decrypt.decrypt_and_verify(enc_str1, tag)
>>> dec_str1
b'STRING'
>>>
>>> import subprocess, sys
>>> subprocess.check_output('echo "STRING" | openssl enc -e -aes128 -base64 -k "KEY" -pbkdf2', shell=True)
b'U2FsdGVkX1+h4OhHGpWuRBud15Ihdr7kjlOSnBleldY=\n'
>>> subprocess.check_output('echo "U2FsdGVkX18tBZwU+04ED55MKCOzWppPynVL6wZWCrA=" | openssl enc -d -aes128 -base64 -k "KEY" -pbkdf2', shell=True)
b'STRING\n'
>>> 
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0