Home  >  Article  >  Backend Development  >  Rake-comb encryption algorithm in Python: types and application scenarios

Rake-comb encryption algorithm in Python: types and application scenarios

WBOY
WBOYforward
2023-05-07 21:43:151112browse

Reversible encryption algorithm (symmetric encryption)

The encryption algorithm is a method of converting original data into encrypted data. According to the different characteristics of encryption algorithms, they can be divided into reversible encryption algorithms and irreversible encryption algorithms.

The reversible encryption algorithm is also called a symmetric encryption algorithm, and its encryption and decryption processes use the same key. In this algorithm, the encrypted data can be restored to the original data through the decryption algorithm. This algorithm is often used to protect the confidentiality of data, such as files stored on a computer's hard drive or data transmitted over a network.

To put it bluntly, it means encryption during data transmission. When it is actually used in business, plaintext is still used.

For example, use the AES encryption algorithm to encrypt files:

from Crypto.Cipher import AES  
import os  
# 生成一个16字节的密钥  
key = os.urandom(16)  
# 初始化加密算法  
cipher = AES.new(key, AES.MODE_EAX)  
# 读取要加密的文件  
with open('plaintext.txt', 'rb') as f:  
    plaintext = f.read()  
# 对文件进行加密  
ciphertext, tag = cipher.encrypt_and_digest(plaintext)  
# 将加密后的文件保存到磁盘上  
with open('ciphertext.txt', 'wb') as f:  
    f.write(cipher.nonce)  
    f.write(tag)  
    f.write(ciphertext)

Or use the DES algorithm:

from Crypto.Cipher import DES  
# 生成一个8字节的密钥  
key = b'secretke'  
# 初始化加密算法  
cipher = DES.new(key, DES.MODE_ECB)  
# 要加密的字符串  
plaintext = b'Hello, World!'  
# 对字符串进行加密  
ciphertext = cipher.encrypt(plaintext)  
# 将加密后的字符串转换为十六进制格式并输出  
print(ciphertext.hex())

In the field of network transmission, symmetric encryption is generally used in JWT Token Token encryption link uses:

class MyJwt:  
    def __init__(self):  
        # 密钥  
        self.secret = "1234"  
    # 加密方法(加入生命周期)  
    def encode_time(self,userinfo,lifetime=300):  
        # 单独声明载荷playload  
        playload = {  
            'exp':(datetime.datetime.now()+datetime.timedelta(seconds=lifetime)).timestamp(),  
            'data':userinfo  
        }  
        res = jwt.encode(playload,self.secret,algorithm='HS256')  
        return res  
    # 加密方法  
    async def encode(self,userinfo):  
        res = jwt.encode(userinfo,self.secret,algorithm='HS256')  
        return res  
    # 解密算法  
    async def decode(self,jwt_str):  
        res = jwt.decode(jwt_str,self.secret,algorithms=['HS256'])  
        return res

In actual applications, it is necessary to choose the encryption algorithm and key length suitable for the specific scenario, and take appropriate security measures to protect the key, because for reversible encryption algorithms, Once the secret key is leaked, the consequences will be catastrophic.

Irreversible encryption algorithm (hash)

Irreversible encryption (also called hash algorithm) is usually used to encrypt or verify passwords or data to ensure the security of passwords or data. Compared with symmetric encryption or asymmetric encryption, the hash algorithm does not require a key for encryption or decryption, so it is more convenient and efficient, but it does not support decryption. Once the encrypted result is generated, the original data cannot be recovered, and the irreversible encryption algorithm The most common application scenario is to encrypt the user's plaintext password into ciphertext.

For example, use the SHA-256 hash algorithm to encrypt data:

import hashlib  
# 加密数据  
message = b'hello world'  
hash_object = hashlib.sha256(message)  
encrypted_data = hash_object.hexdigest()  
print(encrypted_data)

Or use the bcrypt algorithm to encrypt the password:

import bcrypt  
# 加密密码  
password = b'mysecretpassword'  
salt = bcrypt.gensalt()  
hashed_password = bcrypt.hashpw(password, salt)  
# 验证密码  
password_to_check = b'mysecretpassword'  
if bcrypt.checkpw(password_to_check, hashed_password):  
    print("Password is valid!")  
else:  
    print("Invalid password.")

Or use the scrypt algorithm to encrypt the password Encryption:

import scrypt  
# 加密密码  
password = b'mysecretpassword'  
salt = b'saltsaltsalt'  
encrypted_password = scrypt.hash(password, salt, N=16384, r=8, p=1)  
# 验证密码  
password_to_check = b'mysecretpassword'  
if scrypt.hash(password_to_check, salt, N=16384, r=8, p=1) == encrypted_password:  
    print("Password is valid!")  
else:  
    print("Invalid password.")

The principles are similar. They are all based on the hash algorithm to map the original data to a fixed-length ciphertext. Since irreversible encryption (hash algorithm) is a one-way The original data cannot be recovered through decryption, so brute-force hashing algorithms usually try to match the original data by exhaustively exhausting a large number of possibilities:

import hashlib  
# 加载包含密码列表的文件  
with open('passwords.txt', 'r') as f:  
    passwords = f.read().splitlines()  
# 加载哈希值  
hash_value = '5d41402abc4b2a76b9719d911017c592'  
# 尝试匹配密码  
for password in passwords:  
    if hashlib.md5(password.encode()).hexdigest() == hash_value:  
        print(f"Password found: {password}")  
        break  
else:  
    print("Password not found.")

The so-called database on the Internet is "decrypted" Library", what was actually leaked was the ciphertext, and the hackers then used the MD5 hashing algorithm to try to match the password. If the password match is successful, the matching password is output, otherwise the password is not found. Of course, weird performance art like CSDN, which uses clear text to store passwords, cannot be considered a common phenomenon.

But in fact, the so-called "exhaustive" is not exhaustive in the true sense, because humans only set passwords based on those rules, such as birth date, mobile phone number, etc. If they are acquaintances, irreversible encryption can easily be tried. , so in order to avoid being "tried out" by hackers, the password must first be long and contain numbers, uppercase and lowercase letters, and symbols, so as to maximize the possibility of the password. There are 10 possibilities for numbers, 26 possibilities for lowercase letters, 26 possibilities for uppercase letters, and 34 possibilities for symbols. If the length is 16 digits and a bit random, the possible password may be 96 to the 16th power, which is 6 trillion possibilities. , if this were tried, it would be the year of the monkey:

Rake-comb encryption algorithm in Python: types and application scenarios

Finally, the irreversible encryption algorithm can also improve the ciphertext by increasing the salt value, increasing the number of iterations, etc. safety.

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 key and private key) to Encrypt and decrypt data. In asymmetric encryption, the public key is public and anyone can use it 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 can protect the security of data during network transmission, such as asymmetric encryption used in the HTTPS protocol Algorithms protect data transmission between the website and the user.

Digital signature: Asymmetric encryption can use private keys to sign files or data to verify the integrity and authenticity of files or data. For example, asymmetric encryption algorithms are used in digital certificates to protect the security of digital signatures. .

Authentication: Asymmetric encryption can use private keys for authentication, such as SSH login or remote desktop, etc., and use public keys for identity authentication and encrypted communication.

In Python3.10, you can use the cryptography module in 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 cryptography.hazmat.primitives.asymmetric import rsa, padding  
from cryptography.hazmat.primitives import serialization  
# 生成公私钥  
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)  
public_key = private_key.public_key()  
# 将公钥和私钥保存到文件  
with open('private_key.pem', 'wb') as f:  
    f.write(private_key.private_bytes(  
        encoding=serialization.Encoding.PEM,  
        format=serialization.PrivateFormat.PKCS8,  
        encryption_algorithm=serialization.NoEncryption()))  
with open('public_key.pem', 'wb') as f:  
    f.write(public_key.public_bytes(  
        encoding=serialization.Encoding.PEM,  
        format=serialization.PublicFormat.SubjectPublicKeyInfo))

The rsa module is used here A pair of public and private keys is generated and the serialization module is used to save the public and private keys to a file. In actual use, 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. This set of encryption algorithms is mainly used to generate signatures and signature verification operations to ensure the security of the payment process. Take Alipay payment as an example:

 def sign(self, unsigned_string):  
        # 开始计算签名  
        key = self.app_private_key  
        signer = PKCS1_v1_5.new(key)  
        signature = signer.sign(SHA256.new(unsigned_string))  
        # base64 编码,转换为unicode表示并移除回车  
        sign = encodebytes(signature).decode("utf8").replace("\n", "")  
        return sign  
    def _verify(self, raw_content, signature):  
        # 开始计算签名  
        key = self.alipay_public_key  
        signer = PKCS1_v1_5.new(key)  
        digest = SHA256.new()  
        digest.update(raw_content.encode("utf8"))  
        if signer.verify(digest, decodebytes(signature.encode("utf8"))):  
            return True  
        return False

The public key is used to generate the signature, and the private key is used to verify the signature.

区块链与非对称加密

非对称加密在区块链领域中的应用非常广泛。区块链是一个去中心化的分布式账本系统,由于其去中心化的特点,任何人都可以加入网络并参与交易,因此需要使用非对称加密来保护数据的隐私和安全性。

以下是一些非对称加密在区块链领域中的应用:

数字签名:在区块链中,数字签名用于验证交易的真实性和完整性。数字签名的过程是使用私钥对交易数据进行签名,然后在交易中包含签名和公钥,其他人可以使用公钥验证交易的真实性和完整性。
共识算法:区块链中的共识算法用于确定哪些交易应该被添加到区块中。共识算法通常需要参与者提供一定数量的加密学证据,如哈希值或数字签名,以证明他们有权参与共识。
区块链钱包:区块链钱包是用于存储和管理数字货币的介质。钱包通常使用非对称加密来保护用户的私钥,确保用户的数字货币不被盗窃或篡改。

加密货币交易所:加密货币交易所是用于买卖数字货币的平台。交易所通常使用非对称加密来保护用户的身份信息和交易数据的安全性。

可以使用Python3.10来完成区块链中的数字签名,同样使用Python的加密库 cryptography 来生成公私钥对、签名和验证签名。下面是一个简单的示例代码:

from cryptography.hazmat.primitives.asymmetric import ec  
from cryptography.hazmat.primitives import serialization, hashes  
from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature, decode_dss_signature  
# 生成椭圆曲线公私钥对  
private_key = ec.generate_private_key(ec.SECP256K1())  
public_key = private_key.public_key()  
# 对数据进行签名  
data = b"hello, world"  
signature = private_key.sign(data, ec.ECDSA(hashes.SHA256()))  
# 将签名和数据一起传输  
signature_bytes = encode_dss_signature(*signature)  
data_with_signature = (data, signature_bytes)  
# 验证签名  
data, signature_bytes = data_with_signature  
signature = decode_dss_signature(signature_bytes)  
public_key.verify(signature, data, ec.ECDSA(hashes.SHA256()))

首先,我们使用 ec.generate_private_key(ec.SECP256K1()) 方法生成一个椭圆曲线私钥。然后,我们可以通过 private_key.public_key() 方法获取对应的公钥。

接着,我们使用私钥对数据进行签名。这里使用 SHA256 哈希算法来计算数据的哈希值,并使用 ECDSA 签名算法对哈希值进行签名。
随后,我们将签名和数据一起传输。在实际应用中,签名和数据通常都是以二进制数据的形式进行传输。
最后,我们可以使用公钥来验证签名。首先,我们需要将签名从字节数据解码为两个整数。然后,我们可以使用 public_key.verify() 方法来验证签名是否正确。如果签名正确,这个方法将不会抛出异常;否则,将会抛出 InvalidSignature 异常。

The above is the detailed content of Rake-comb encryption algorithm in Python: types and application scenarios. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete