1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pycryptoの暗号化と復号化

Last updated at Posted at 2020-04-25
import string
import random

#pip install pycrypto
from Crypto.Cipher import AES


key = ''.join(
    random.choice(string.ascii_letters) for _ in range(AES.block_size)) #内包表記

iv = ''.join(
    random.choice(string.ascii_letters) for _ in range(AES.block_size)) #内包表記

plaintext = 'fdsfsdgsgsfgs'
cipher = AES.new(key, AES.MODE_CBC, iv)
padding_length = AES.block_size - len(plaintext) % AES.block_size #paddingする文字列の長さを計算
plaintext += chr(padding_length) * padding_length #paddingする
cipher_text = cipher.encrypt(plaintext) #暗号化
print(cipher_text)

cipher2 = AES.new(key, AES.MODE_CBC, iv)
decrypted_text = cipher2.decrypt(cipher_text) #復号化
print(decrypted_text[:-decrypted_text[-1]]) #paddingした文字列を取り除いて表示
b'\xba\xb5\xf6\x0f\x87\xe0N\xa1?I\xf6O\x1d\x96]\x88'
b'fdsfsdgsgsfgs'
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?