当前位置:   article > 正文

用python实现AES加密、解密。

python3 aes 字符串加解密示例

下面是使用 Python 实现 AES 加密和解密的示例代码:

  1. import base64
  2. import hashlib
  3. import os
  4. from cryptography.hazmat.backends import default_backend
  5. from cryptography.hazmat.primitives import padding, serialization
  6. from cryptography.hazmat.primitives.ciphers import (
  7. Cipher, algorithms, modes
  8. )
  9. def generate_key(password: str, salt: bytes, iterations: int = 100000, key_size: int = 32):
  10. kdf = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, iterations, key_size)
  11. return kdf
  12. def encrypt(plaintext: str, password: str, salt: bytes):
  13. # Generate key
  14. key = generate_key(password, salt)
  15. # Add padding to the plaintext
  16. padder = padding.PKCS7(algorithms.AES.block_size).padder()
  17. padded_plaintext = padder.update(plaintext.encode()) + padder.finalize()
  18. # Generate a random IV
  19. iv = os.urandom(16)
  20. # Encrypt the plaintext
  21. cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
  22. encryptor = cipher.encryptor()
  23. ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
  24. # Concatenate the IV and the ciphertext
  25. encrypted_message = iv + ciphertext
  26. # Encode the encrypted message as a base64 string
  27. encoded_encrypted_message = base64.b64encode(encrypted_message)
  28. return encoded_encrypted_message
  29. def decrypt(encoded_encrypted_message: str, password: str, salt: bytes):
  30. # Decode the encrypted message from a base64 string
  31. encrypted_message = base64.b64decode(encoded_encrypted_message)
  32. # Split the IV and the ciphertext
  33. iv = encrypted_message[:16]
  34. ciphertext = encrypted_message[16:]
  35. # Generate key
  36. key = generate_key(password, salt)
  37. # Decrypt the ciphertext
  38. cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
  39. decryptor = cipher.decryptor()
  40. padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize()
  41. # Remove padding from the plaintext
  42. unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
  43. plaintext = unpadder.update(padded_plaintext) + unpadder.finalize()
  44. return plaintext.decode()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号