main body (of a book)
Needless to say a hot moment, the whole network hot Web3.0 blockchain technology, do not have to say such as WeChat Pay, Alipay Payments and other people almost every day to use the online payment business, a simple registration/login function, and cryptography can not be dissociated from this time we rake comb a variety of classic cryptographic algorithms, trying to portray the use of cryptographic algorithms in the development of scenarios using the skills.
Reversible encryption algorithm (symmetric encryption)
An encryption algorithm is a method of converting original data into encrypted data. Based on the different characteristics of encryption algorithms, they can be categorized as reversible encryption algorithms and irreversible encryption algorithms.
Reversible encryption algorithms are also known as symmetric encryption algorithms, which use the same key for encryption and decryption processes. In this algorithm, the encrypted data can be restored to the original data by the decryption algorithm. This algorithm is commonly used to protect the confidentiality of data, such as protecting files stored on a computer's hard disk or data transmitted over a network.
To put it bluntly, it's encrypting the data in transit, and when it's actually used in business, it's still in plaintext.
For example, files are encrypted using the AES encryption algorithm:
from import AES import os # Generate a 16-byte key key = (16) # Initialize encryption algorithm cipher = (key, AES.MODE_EAX) # Read the file to be encrypted with open('', 'rb') as f: plaintext = () # Encrypting files ciphertext, tag = cipher.encrypt_and_digest(plaintext) # Save encrypted files to disk with open('', 'wb') as f: () (tag) (ciphertext)
Or use the DES algorithm:
from import DES # Generate an 8-byte key key = b'secretke' # Initialize encryption algorithm cipher = (key, DES.MODE_ECB) # String to be encrypted plaintext = b'Hello, World!' # Encrypting strings ciphertext = (plaintext) # Convert the encrypted string to hexadecimal format and output it print(())
In the field of network transmission, symmetric encryption is generally used in the Token token encryption session of JWT:
class MyJwt: def __init__(self): # Key = "1234" # Encryption methods (add to life cycle) def encode_time(self,userinfo,lifetime=300): # Separate declaration of load playload playload = { 'exp':(()+(seconds=lifetime)).timestamp(), 'data':userinfo } res = (playload,,algorithm='HS256') return res # Encryption methods async def encode(self,userinfo): res = (userinfo,,algorithm='HS256') return res # Decryption algorithms async def decode(self,jwt_str): res = (jwt_str,,algorithms=['HS256']) return res
In practical applications, it is necessary to choose encryption algorithms and key lengths suitable for specific scenarios, and take appropriate security measures to protect the key, because for reversible encryption algorithms, once the secret key is leaked, the consequences will be disastrous.
Irreversible encryption algorithm (hash)
Irreversible encryption (also known as hash algorithm) is usually used to encrypt or verify passwords or data to ensure the security of passwords or data. Compared to symmetric encryption or asymmetric encryption, hash algorithms do not require a key to encrypt or decrypt, so they are more convenient and efficient, but it does not support decryption, and once the encrypted result is generated, the original data cannot be recovered. The most common application scenario for irreversible encryption algorithms is encrypting the user's plaintext password into a ciphertext.
For example, data is encrypted using the SHA-256 hash algorithm:
import hashlib # Encrypted data message = b'hello world' hash_object = hashlib.sha256(message) encrypted_data = hash_object.hexdigest() print(encrypted_data)
Or encrypt the password using the bcrypt algorithm:
import bcrypt # Encrypted passwords password = b'mysecretpassword' salt = () hashed_password = (password, salt) # Verify password password_to_check = b'mysecretpassword' if (password_to_check, hashed_password): print("Password is valid!") else: print("Invalid password.")
Or perhaps the password is encrypted using the scrypt algorithm:
import scrypt # Encrypted passwords password = b'mysecretpassword' salt = b'saltsaltsalt' encrypted_password = (password, salt, N=16384, r=8, p=1) # Verify password password_to_check = b'mysecretpassword' if (password_to_check, salt, N=16384, r=8, p=1) == encrypted_password: print("Password is valid!") else: print("Invalid password.")
The principle is similar, are based on the hash (hash) algorithm to map the original data to a fixed length of the ciphertext, due to the irreversible encryption (hash algorithm) is a one-way encryption, can not be decrypted to recover the original data, so the hash algorithm of the violent cracking is usually through a large number of possibilities of the exhaustion of the original data to try to match:
import hashlib # Load a file containing a list of passwords with open('', 'r') as f: passwords = ().splitlines() # Load hash hash_value = '5d41402abc4b2a76b9719d911017c592' # Try to match the password for password in passwords: if hashlib.md5(()).hexdigest() == hash_value: print(f"Password found: {password}") break else: print("Password not found.")
The so-called database on the network was "stripped", in fact, the leak is the ciphertext, and then the hacker used the MD5 hash algorithm to try to match the password. If the password match is successful, then output the matching password, otherwise output the password is not found. Of course, like CSDN, this kind of strange behavioral art of saving passwords in plaintext, can not be considered as a common phenomenon.
But in fact, the so-called "exhaustive" is not really exhaustive, because human beings set up passwords on those laws, date of birth, cell phone number and so on, if it is a familiar, irreversible encryption is easy to be tried out, so in order to avoid being hacked "try out" passwords! The first thing you need to do is to have a long password that contains numbers, upper and lower case letters, and symbols so that you can maximize the likelihood of the password. There are 10 possibilities for numbers, 26 possibilities for lowercase letters, 26 possibilities for uppercase letters, 34 possibilities for symbols, and if the length is 16 digits and randomized, then the possible passwords could be 96 to the 16th power, with 6 trillion possibilities, which would be a monkey's age if you try it out:
Finally, irreversible encryption algorithms can also improve the security of the ciphertext by increasing the salt value, increasing the number of iterations, and other measures.
asymmetric encryption
Asymmetric encryption is also an encryption algorithm, however unlike the symmetric encryption algorithm described above, it uses a pair of public and private keys (public and private) to encrypt and decrypt data. In asymmetric encryption, the public key is public and can be used by anyone to encrypt data, but only the person holding the private key can decrypt the data.
Asymmetric encryption algorithms are widely used in the following scenarios:
Secure communication: Asymmetric encryption protects data during transmission over the network, such as the HTTPS protocol which uses asymmetric encryption algorithms to protect data transmission between websites and users.
Digital Signature: Asymmetric encryption can be used to sign documents or data using a private key to verify the integrity and authenticity of the document or data, such as digital certificates in the use of asymmetric encryption algorithms to protect the security of digital signatures.
Authentication: Asymmetric encryption allows you to use a private key for authentication, such as SSH login or remote desktop, and a public key for authentication and encrypted communication.
In Python 3.10, you can use the cryptography module from the standard library to implement asymmetric encryption. The following is an example of using the cryptography module to generate a pair of public and private keys:
from import rsa, padding from import serialization # Generate public and private keys private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) public_key = private_key.public_key() # Save public and private keys to file with open('private_key.pem', 'wb') as f: (private_key.private_bytes( encoding=, format=.PKCS8, encryption_algorithm=())) with open('public_key.pem', 'wb') as f: (public_key.public_bytes( encoding=, format=))
Here we use the rsa module to generate a pair of public and private keys and use the serialization module to save the public and private keys to a file. In practice, the public key can be used publicly, while the private key should be kept in a safe place to ensure data security.
In the payment system, asymmetric encryption is widely used, mainly using this set of encryption algorithms to generate signatures and signature verification operations, which are used to ensure the security of the payment process, taking Alipay payment as an example:
def sign(self, unsigned_string): # Start counting signatures key = self.app_private_key signer = PKCS1_v1_5.new(key) signature = ((unsigned_string)) # base64 encoding, convert to unicode and remove carriage return sign = encodebytes(signature).decode("utf8").replace("\n", "") return sign def _verify(self, raw_content, signature): # Start counting signatures key = self.alipay_public_key signer = PKCS1_v1_5.new(key) digest = () (raw_content.encode("utf8")) if (digest, decodebytes(("utf8"))): return True return False
The public key is used to generate the signature and the private key is used to verify the signature.
Blockchain and asymmetric encryption
Asymmetric encryption is widely used in the field of blockchain. Blockchain is a decentralized distributed ledger system and due to its decentralized nature, anyone can join the network and participate in transactions, hence the need to use asymmetric encryption to protect the privacy and security of data.
Here are some of the applications of asymmetric encryption in the blockchain space:
Digital Signature: In blockchain, digital signature is used to verify the authenticity and integrity of the transaction. The process of digital signing involves signing the transaction data using a private key and then including the signature and public key in the transaction, which can be used by others to verify the authenticity and integrity of the transaction.
Consensus algorithms: consensus algorithms in blockchains are used to determine which transactions should be added to a block. Consensus algorithms typically require participants to provide a certain amount of cryptographic evidence, such as hashes or digital signatures, to prove that they are entitled to participate in the consensus.
Blockchain Wallet: a blockchain wallet is a medium used to store and manage digital currency. Wallets typically use asymmetric encryption to protect the user's private key and ensure that the user's digital currency is not stolen or tampered with.
Cryptocurrency Exchanges: Cryptocurrency exchanges are platforms used to buy and sell digital currencies. Exchanges typically use asymmetric encryption to secure users' identifying information and transaction data.
Digital signatures in the blockchain can be accomplished using Python 3.10, again using Python's cryptography library cryptography to generate public-private key pairs, signatures and verify signatures. Here is a simple example code:
from import ec from import serialization, hashes from import encode_dss_signature, decode_dss_signature # Generate elliptic curve public-private key pairs private_key = ec.generate_private_key(ec.SECP256K1()) public_key = private_key.public_key() # Signing of data data = b"hello, world" signature = private_key.sign(data, (hashes.SHA256())) # Transmit signatures with data signature_bytes = encode_dss_signature(*signature) data_with_signature = (data, signature_bytes) # Verify the signature data, signature_bytes = data_with_signature signature = decode_dss_signature(signature_bytes) public_key.verify(signature, data, (hashes.SHA256()))
First, we generate an elliptic curve private key using the ec.generate_private_key(ec.SECP256K1()) method. Then, we can obtain the corresponding public key using the private_key.public_key() method.
Next, we sign the data using the private key. Here we use the SHA256 hash algorithm to calculate the hash value of the data and sign the hash value using the ECDSA signature algorithm.
Subsequently, we transmit the signature along with the data. In practice, signatures and data are usually transmitted as binary data.
Finally, we can use the public key to verify the signature. First, we need to decode the signature from byte data to two integers. Then, we can use the public_key.verify() method to verify that the signature is correct. If the signature is correct, this method will not throw an exception; otherwise, an InvalidSignature exception will be thrown.
concluding remarks
Encryption techniques come under the umbrella of applied cryptography and are designed to protect the confidentiality and integrity of information to ensure that only authorized people can access and use that information. Cryptography mainly involves two types of algorithms which are mentioned in this article: symmetric encryption and asymmetric encryption.
Cryptography has a wide range of applications in modern society, including the Internet, e-commerce, digital payments, e-mail, social networks, and so on. It is an important tool for protecting personal privacy and business secrets. Also, cryptography is the basis for many advanced security protocols and systems, such as SSL/TLS (https/wss), SSH, PGP, IPSec, Kerberos, and so on.
The above is Python3.10 rake comb encryption algorithm Encryption types and development scenarios in detail, more information about Python rake comb encryption algorithm please pay attention to my other related articles!