Before formally writing various encryption and decryption, let’s write a small case first, as follows.
Basic encryption and decryption-source code
# Encryptiondef encode(): source01 = 'Leyin' for c in source01: ascii01 = ord(c) ascii01 += 1 print(chr(ascii01), end='') # Decryptdef decode(): source02 = 'Tea' for c in source02: ascii01 = ord(c) ascii01 -= 1 print(chr(ascii01), end='') if __name__ == '__main__': # encode() decode()
Basic encryption and decryption-source code analysis
This code contains two functions: encode() and decode(), and a main program entry
encode() function
The function of this function is to encrypt the string "Leyin". The encryption method is to add 1 to each character's ASCII code value and then convert the new ASCII code value back to the character.
Define a string source01 with the value "Leyin".
Use for loop to loop through each character c in source01.
Use the ord() function to get the ASCII code value of the character c and assign it to ascii01.
Add the value of ascii01 to 1.
Use the chr() function to convert the new ASCII code value back to characters and print it out. Note that the end='' parameter is used here so that the print result does not wrap lines.
decode() function
The function of this function is to decrypt the string "Buzizi". The decryption method is to decrypt the ASCII code value of each character by 1, and then convert the new ASCII code value back to the character.
Defines a string source02 with the value "Nan Zizi".
Use for loop to loop through each character c in source02.
Use the ord() function to get the ASCII code value of the character c and assign it to ascii01.
Decrement the value of ascii01 by 1.
Use the chr() function to convert the new ASCII code value back to characters and print it out. Note that the end='' parameter is used here so that the print result does not wrap lines.
Main program entry
In the main program entry, call the decode() function for decryption operation. If encryption is required, you can cancel the comment before the encode() function and comment out the call to the decode() function.
The main purpose of this code is to demonstrate a simple character encryption and decryption method, which is to add or subtract the ASCII code value of each character by 1 or minus 1. This method is very simple, but has low security and is not suitable for actual security needs.
base64 encryption and decryption-source code
# base64 encryptionimport base64 # Binary and hexadecimal are completely equivalent in computers, and every four binary bits are equal to one hexadecimal bit source = 'echo' print(base64.b64encode(())) # base64 decryptionsource = 'ZWNobw==' print(base64.b64decode(())) def decode(): de_source = 'ZWNobw==' print(base64.b64decode(de_source).decode()) # Encode the filedef file_encode(): with open('File Reference/', 'rb') as file: data = () print(base64.b64encode(data).decode()) # Restore base64 to filedef file_decode(): file_source = 'iVBORw0KGgoAAAANSUhEUgA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xgGOuPDCt4csn1moEMkYjcyewRu6/bNdO7hyP/bDczxfqbpTEGSPZrLdVZj8Tk6U2tKwzSAzElmmnYJcsCiM6sBoYwXNMuN4F9nwi4ygYxcJ7gT6JDSz7dpdjFlgXdEegV6K8d3kVmWkqBvPTE3Hfq3WUJp6VrTLr7b8zIj0wgA/wUFnPmH2GVRJAAAAABJRU5ErkJggg==' data = base64.b64decode(file_source) with open('File reference/index_1.png', 'wb') as file: (data) if __name__ == '__main__': # file_encode() file_decode()
Base64 encryption and decryption-source code analysis
This code mainly demonstrates how to use Python's base64 library for encoding and decoding operations
base64 encoding part
import base64 source = 'echo' print(base64.b64encode(()))
Import base64 library.
Defines a string source with the value 'echo'.
Use the base64.b64encode() function to encode the string. Note that b64encode needs to receive byte type data, so use() to convert the string to bytes.
Print the encoded result.
base64 decoding part
source = 'ZWNobw==' print(base64.b64decode(()))
Define a string source with the value 'ZWNobw==', which is the base64 encoding result of 'echo'.
Use the base64.b64decode() function to decode the string. Likewise, the string needs to be converted to bytes first.
Print the decoded result.
decode function
def decode(): de_source = 'ZWNobw==' print(base64.b64decode(de_source).decode())
This function is the same as the decoded part above, but converts the decoded byte data back to a string and prints it.
file_encode function
def file_encode(): with open('File Reference/', 'rb') as file: data = () print(base64.b64encode(data).decode())
Open a file named 'File Reference/' and read in binary mode.
Read the file content to the data variable.
Base64 encoding of the file contents and print the encoded results.
file_decode function
def file_decode(): file_source = 'iVBORw0KGgoAAAANSUhEUgAA...' data = base64.b64decode(file_source) with open('File reference/index_1.png', 'wb') as file: (data)
Define a string file_source with a long base64 encoded string (part of the content is omitted here).
Base64 decode the string to obtain the original binary data.
Open a file named 'File Reference/index_1.png' and write it in binary mode.
Write the decoded binary data to a file.
Main program entry
if __name__ == '__main__': # encode() decode() # file_encode() file_decode()
The main program entry part comments on the encode() and file_encode() functions, and only the decode() and file_decode() functions are executed. If you need to perform encoding operations, you can uncomment the corresponding function.
Summary: This code mainly demonstrates how to use Python's base64 library to encode and decode strings and files.
AES encryption and decryption-source code
from import AES from binascii import b2a_hex from binascii import a2b_hex # AES Encryptionsource = 'kfc-v50' # The first step is to make up for 16# If the source is less than 16 digits, use spaces to make up for 16 digitsif len(('utf-8')) % 16: add = 16 - (len(('utf-8')) % 16) else: add = 0 source = source + ('\0' * add) print(source) # Step 2: Define the key# Define the offset, must be 16, 24, 32 bitskey = 'today-is-thursday-kfc-permit-v50'.encode() mode = AES.MODE_CBC iv = b'1234567890ABCDEF' cryptos = (key, mode, iv) cipher = b2a_hex((())) print(()) #AES Decryption# cipher = 'encrypted ciphertext' key = 'today-is-thursday-kfc-permit-v50'.encode() mode = AES.MODE_CBC iv = b'1234567890ABCDEF' cryptos = (key, mode, iv) dest = (a2b_hex(cipher)) print(().rstrip('\0'))
AES encryption and decryption-source code analysis
This code uses Python's pycryptodome library to implement AES encryption and decryption. The following is a detailed analysis of the code:
Import module
from import AES from binascii import b2a_hex, a2b_hex
: Provides the implementation of the AES encryption algorithm.
binascii.b2a_hex and binascii.a2b_hex: Used to convert between binary data and hexadecimal strings.
AES encryption part
1. Data preprocessing (population)
source = 'kfc-v50' if len(('utf-8')) % 16: add = 16 - (len(('utf-8')) % 16) else: add = 0 source = source + ('\0' * add) print(source)
Purpose: Ensure that the length of the plaintext is a multiple of 16 bytes, because AES is a packet encryption algorithm, requiring that the data length must be a multiple of the block size (16 bytes).
step:
Calculate the byte length of the source string.
Determine whether filling is required (i.e. whether the length is a multiple of 16).
If necessary, calculate the number of bytes to be filled and fill it with \0 (null character).
Output: Filled string, for example 'kfc-v50\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0'.
2. Define the key and initialize vector (IV)
key = 'today-is-thursday-kfc-permit-v50'.encode() mode = AES.MODE_CBC iv = b'1234567890ABCDEF'
Key: Must be 16, 24 or 32 bytes long. Here is a 32-byte (256-bit) key.
Mode: Use CBC (Cipher Block Chaining) mode, which is one of the most common AES encryption modes.
Initialization vector (IV): 16 bytes long, used to increase encryption randomness in CBC mode. The IV should be randomly generated, but a fixed value is used in the example.
3. Encryption process
cryptos = (key, mode, iv) cipher = b2a_hex((())) print(())
Create an AES encryption object: Initialize the AES encryptor with the specified key, mode, and IV.
Encryption: Encode the filled plaintext string into bytes and encrypt it.
Convert: Convert encrypted binary data into hexadecimal strings for easy display and storage.
Output: Encrypted hexadecimal string, for example 'e3b0c44298fc1c14...'.
AES decryption part
1. Define keys and IVs
key = 'today-is-thursday-kfc-permit-v50'.encode() mode = AES.MODE_CBC iv = b'1234567890ABCDEF'
The key, mode, and IV used during decryption must be exactly the same as when encrypted.
2. Decryption process
cryptos = (key, mode, iv) dest = (a2b_hex(cipher)) print(().rstrip('\0'))
Create an AES decryption object: Also initialize the AES decryptor using the specified key, mode, and IV.
Decryption: Convert the hexadecimal string back to binary data and decrypt it.
Remove padding: The decrypted data may contain padding characters \0. Use rstrip('\0') to remove these characters to restore the original plaintext.
Output: Decrypted original string, such as 'kfc-v50'.
Things to note
Security:
Fixed IV: In practical applications, IVs should be randomly generated and are different every time they are encrypted. Using a fixed IV will reduce encryption security, especially when processing large amounts of data.
Key management: Ensure the secure storage and management of keys to avoid leakage.
Filling method:
In the example, \0 is used for filling, which is simple but not universal enough. Standard fill schemes such as PKCS7 fill are recommended for compatibility and security.
Exception handling:
The code does not include exception handling mechanism. In practical applications, appropriate error handling should be added to deal with possible exceptions (such as decryption failures, data format errors, etc.).
Dependency library:
Make sure that the pycryptodome library is installed, you can install it using the following command:
pip install pycryptodome
Summarize
This code shows how to use Python's pycryptodome library for AES encryption and decryption operations. The basic process of symmetric encryption is realized by filling plaintext, defining keys and IVs, and executing encryption and decryption steps. However, in practical applications, attention needs to be paid to improve safety and robustness, such as using random IVs, adopting standard fill schemes, and adding exception handling.
RSA encryption and decryption—source code
from binascii import b2a_hex from binascii import a2b_hex import rsa # Step 1: Generate RSA public and private keyspub, priv = (256) # print(pub, priv) # Step 2, public key encryptionencrypt = ('leyinsec'.encode(), pub) enstr = b2a_hex(encrypt).decode() # print(enstr) # Step 3: Decrypt the private key# decrypt = (encrypt, priv) decrypt = (a2b_hex(enstr), priv) print(())
RSA encryption and decryption—source code analysis
This code uses Python's rsa library and binascii library to implement the RSA public key encryption and private key decryption process
1. Import the library
from binascii import b2a_hex from binascii import a2b_hex import rsa
The binary library is used to convert data between binary and ASCII encoding.
The rsa library is used to implement RSA encryption and decryption.
2. Generate RSA public and private keys
pub, priv = (256)
Use the() function to generate a pair of RSA public and private keys.
Parameter 256 means that the length of the key is 256 bits. This is a relatively short key length that may not be secure enough for modern security standards. It is generally recommended to use a key length of at least 3072 bits.
3. Public key encryption
encrypt = ('leyinsec'.encode(), pub) enstr = b2a_hex(encrypt).decode()
Encrypt the string 'leyinsec' using the public key pub. Note that the () function requires input of byte type, so use .encode() to convert the string to bytes.
The encrypted data is in binary format. For easy display or storage, use the b2a_hex() function to convert it into a hex string.
4. Private key decryption
decrypt = (a2b_hex(enstr), priv) print(())
Use the private key priv to decrypt the encrypted data. Since the encrypted data is stored in hexadecimal strings, it is first converted back to binary format using the a2b_hex() function.
The decrypted data is byte type, and use .decode() to convert it back to a string and print it out.
Things to note
Key Length: As mentioned above, the 256-bit RSA key length is relatively short and may not be secure enough. It is recommended to use longer key lengths, such as 3072 bits or longer.
Fill scheme: RSA encryption usually uses some kind of fill scheme (such as PKCS#1 v1.5 or OAEP). In the above code, the fill scheme is not explicitly specified, so the rsa library may use the default fill scheme. In practical applications, it is recommended to specify a fill scheme to ensure security.
Error handling: The above code does not contain any error handling logic. In practical applications, appropriate error handling should be added to catch and handle possible exceptions, such as decryption failures, invalid inputs, etc.
Security: RSA encryption is powerful, but it also has its limitations. It is mainly used to encrypt small amounts of data or to securely exchange symmetric encryption keys. For encryption of large amounts of data, it is generally recommended to use symmetric encryption algorithms such as AES and use RSA to securely exchange symmetric keys.
The above is a detailed content of in-depth exploration of the design and implementation of Python custom encryption algorithms. For more information about Python custom encryption algorithms, please pay attention to my other related articles!