Hướng dẫn python encryption code examples

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In this article, we will learn about Encryption, Decryption and implement them with Python. 

    Encryption:

    Encryption is the process of encoding the data. i.e converting plain text into ciphertext. This conversion is done with a key called an encryption key.

    Decryption:

    Decryption is the process of decoding the encoded data. Converting the ciphertext into plain text. This process requires a key that we used for encryption.

    We require a key for encryption. There are two main types of keys used for encryption and decryption. They are Symmetric-key and Asymmetric-key.

    Symmetric-key Encryption:

    In symmetric-key encryption, the data is encoded and decoded with the same key. This is the easiest way of encryption, but also less secure. The receiver needs the key for decryption, so a safe way need for transferring keys. Anyone with the key can read the data in the middle.

    Example:

    Install the python cryptography library with the following command. 

    pip install cryptography

    Steps:

    • Import Fernet
    • Then generate an encryption key, that can be used for encryption and decryption.
    • Convert the string to a byte string, so that it can be encrypted.
    • Instance the Fernet class with the encryption key.
    • Then encrypt the string with the Fernet instance.
    • Then it can be decrypted with Fernet class instance and it should be instanced with the same key used for encryption.

    Python3

    from cryptography.fernet import Fernet

    message = "hello geeks"

    key = Fernet.generate_key()

    fernet = Fernet(key)

    encMessage = fernet.encrypt(message.encode())

    print("original string: ", message)

    print("encrypted string: ", encMessage)

    decMessage = fernet.decrypt(encMessage).decode()

    print("decrypted string: ", decMessage)

    Output:

    Hướng dẫn python encryption code examples

    Asymmetric-key Encryption:

    In Asymmetric-key Encryption, we use two keys a public key and a private key. The public key is used to encrypt the data and the private key is used to decrypt the data. By the name, the public key can be public (can be sent to anyone who needs to send data). No one has your private key, so no one in the middle can read your data.

    Example:

    Install the python rsa library with the following command. 

    pip install rsa

    Steps:

    • Import rsa library
    • Generate public and private keys with rsa.newkeys() method.
    • Encode the string to byte string.
    • Then encrypt the byte string with the public key.
    • Then the encrypted string can be decrypted with the private key.
    • The public key can only be used for encryption and the private can only be used for decryption.

    Python3

    import rsa

    publicKey, privateKey = rsa.newkeys(512)

    message = "hello geeks"

    encMessage = rsa.encrypt(message.encode(),

                             publicKey)

    print("original string: ", message)

    print("encrypted string: ", encMessage)

    decMessage = rsa.decrypt(encMessage, privateKey).decode()

    print("decrypted string: ", decMessage)

    Output:

    Hướng dẫn python encryption code examples


    Chúng ta hãy minh họa các khái niệm mã hóa AES và giải mã AES thông qua Python.

    Ví dụ đầu tiên dưới đây sẽ minh họa một mã hóa AES dựa trên mật khẩu đơn giản (PBKDF2 + AES-CTR) mà không có xác thực tin nhắn (mã hóa không được xác thực). Ví dụ tiếp theo sẽ thêm xác thực tin nhắn (sử dụng chế độ AES-GCM), sau đó sẽ thêm mật khẩu vào khoá dẫn (AES-256-GCM + Scrypt).

    Simple AES-CTR Example

    Hãy bắt đầu với mã hóa không xác thực AES-256-CTR đơn giản.
    Cài đặt thư viện Python pyaespbkdf2
    Đầu tiên, cài đặt các thư viện Python thực hiện thuật toán mã hóa khóa đối xứng AES:

    Tiếp theo, cài đặt thư viện Python pbkdf2 thực hiện thuật toán dẫn xuất mật khẩu PBKDF2:

    pip install pbkdf2

    Password với Key derivation

    Đầu tiên bắt đầu bằng Key derivation: từ mật khẩu đến khóa mã hóa 256 bit.

    Đoạn mã trên lấy được khóa 256 bit bằng thuật toán Key Derivation PBKDF2 từ mật khẩu s3cr3t * c0d3. Nó sử dụng một salt derivation mật khẩu ngẫu nhiên (128-bit). Salt này nên được lưu trữ trong đầu ra, cùng với ciphertext, bởi vì không có nó, decryption key không thể được lấy lại và việc giải mã sẽ không thể thực hiện được.

    Key derivation bao gồm 64 chữ số hex (32 byte), đại diện cho số nguyên 256 bit. Sẽ khác nếu bạn chạy đoạn mã trên nhiều lần, bởi vì một salt ngẫu nhiên được sử dụng mỗi lần. Nếu bạn sử dụng cùng một salt, cùng một khóa sẽ được chuyển hoá ở đầu ra.

    AES Encryption (CTR Block Mode)

    Tiếp theo, tạo một vectơ ban đầu 256 bit ngẫu nhiên (IV) cho mode AES CTR block và thực hiện mã hóa AES-256-CTR:

    Hướng dẫn python encryption code examples

    Đầu ra từ mã trên có thể trông như thế này:

    Ciphertext bao gồm 38 chữ số hex (19 byte, 152 bit). Đây là kích thước của dữ liệu đầu vào: “How do you know that?”
    Lưu ý rằng sau khi mã hóa AES-CTR, vectơ ban đầu (IV) phải được lưu trữ cùng với Ciphertext, vì nếu không có nó, việc decrypt sẽ là không thể. IV nên được tạo ngẫu nhiên cho mỗi mã hóa AES (không được mã hóa cứng) để bảo mật cao hơn.

    AES Decryption (CTR Block Mode)

    Bây giờ hãy xem cách decrypt một Ciphertext bằng thuật toán AES-CTR-256. Đầu vào bao gồm bản mã + encryption key + IV cho bộ đếm CTR. Đầu ra là plaintext. Mã này khá đơn giản:

    Đầu ra của ở trên nên như thế này:

    Lưu ý rằng object aes nên được khởi tạo lại, bởi vì thuật toán CTR block mode giữ trạng thái bên trong thay đổi theo thời gian. Cũng lưu ý rằng đoạn mã trên không thể phát hiện key sai, ciphertext sai hoặc IV sai. Nếu bạn sử dụng khóa không chính xác để giải mã bản mã, bạn sẽ nhận được một văn bản không thể đọc được. Điều này được hiển thị rõ ràng bằng mã dưới đây:

    Đầu ra của nỗ lực giải mã không chính xác ở trên có thể như sau:

    Next topic: AES Encryption / Decryption (AES-CTR) – Examples in Python

    Source: cryptobook.nakov.com