Password encryption and decryption - Stack Overflow


  Due to the illegal copying of computer software, the leakage of communication and the security of data are threatened. Generally, for security, the database name, password and other information are required to be encrypted. Therefore, encryption is a technology often used in the development process, and it is applied in some important scenarios, such as: login, payment, oauth, etc. Different scenarios require different signature encryption algorithms to achieve business goals. The python side is used in the project, and python's encryption and decryption module for passwords is required.
  Encryption Algorithms Distributed hash algorithm, symmetric encryption, asymmetric encryption. Refer to the online information, and preliminarily sort out the logical thinking of password management.

1. Symmetric encryption

  It is the two parties using this encryption method to use the same key for encryption and decryption. Keys are instructions that control the encryption and decryption process. An algorithm is a set of rules that dictate how encryption and decryption should be done. Common symmetric algorithms include AES, DES, 3DES, etc.

1.1 Install third-party library - PyCrypto

  For symmetric encryption or asymmetric encryption, a third-party library needs to be installed. The cryptographic library in Python is PyCrypto, but it has stopped updating in 2012, and now PyCrytodome is used instead of PyCrypto.
  Install pycryptodemo under windows, install pycrypto under linux

pip install pycryptodome

Examples are as follows:
1

1.2 Encryption implementation

  AES algorithm is currently the most widely used encryption algorithm. AES has 5 encryption modes, namely ECB, CBC, CTR, CFB, OFB. Let’s take the ECB mode of AES as an example. AES also needs the encryption key aes_key. It should be noted that if the encrypted data is less than 16 or 32 bits, it needs to be a multiple of them. The multiple of 16 is used as an example below:

  1. Create the function first, and the incomplete data is less than 16 multiples
def addStrToSpecifyLen(s,specifyLen=0):
    """
    s不是specifyLen的倍数那就补足为specifyLen的倍数
    :param s: 需要加密的参数
    :param specifyLen: 指定参数的位数
    :return: 补足位数的参数
    """
    if specifyLen <= 0:
        specifyLen = 1;
    while len(s) % specifyLen != 0:
        s += '\0'
    return s.encode(encoding='utf-8')
  1. Encryption Algorithm - aes
def encrypt_aes(text='', key=''):
    """
    aes的ecb模式加密
    :param data: 加密数据
    :param aes_key: 加密的秘钥
    :return: 加密之后的密文
    """
    # 初始化加密器
    aes = AES.new(addStrToSpecifyLen(key,16), AES.MODE_ECB)
    # 先进行aes加密
    encrypt = aes.encrypt(addStrToSpecifyLen(text,16))
    # 用base64转成字符串形式
    encrypted_text = str(base64.encodebytes(encrypt), encoding='utf-8')  # 执行加密并转码返回bytes
    return encrypted_text
  1. decryption algorithm
def decrypt_aes(data, aes_key):
    """
    aes的ecb模式解密
    :param data: 待解密数据
    :param aes_key: 加密的秘钥
    :return: 解密之后的数据
    """
    # 初始化加密器
    aes = AES.new(addStrToSpecifyLen(aes_key,16), AES.MODE_ECB)
    #优先逆向解密base64成bytes
    base64_decrypted = base64.decodebytes(addStrToSpecifyLen(data,16))
    #执行解密密并转码返回str
    decrypted_text = str(aes.decrypt(base64_decrypted),encoding='utf-8').replace('\0','')
    return decrypted_text
  1. The test output is as follows:
if __name__ == '__main__':
    key = '12223'
    data = 'test12dcds'
    encrypt = encrypt_aes(data,key)
    print(encrypt)
    print(decrypt_aes(encrypt,key))

2

2. Asymmetric encryption

  Unlike symmetric encryption algorithms, asymmetric encryption algorithms require two keys: a public key (publickey) and a private key (privatekey). The public key and the private key are a pair. If the data is encrypted with the public key, only the corresponding private key can be used to decrypt it; if the data is encrypted with the private key, only the corresponding public key can be used to decrypt the data. decrypt. Because encryption and decryption use two different keys, this algorithm is called an asymmetric encryption algorithm. Common asymmetric algorithms include RSA, DSA, ECC, etc.

3. Summary Algorithm

  Python's hashlib provides common digest algorithms, such as MD5, SHA1, SHA224, SHA256, SHA384, SHA512 and other algorithms. Digest algorithm is also called hash algorithm or hash algorithm. It uses a function to convert data of any length into a fixed-length data string (usually represented by a hexadecimal string).
   It is generally used for message encryption in network communication. The premise is that the two parties must first agree on the key, just like the joint password, and then the message is sent to encrypt the message with the key, and the receiver uses the key + message plaintext to encrypt again, and the encrypted value is followed by Whether the relative ratio of the sender is equal, so that the authenticity of the message and the legitimacy of the sender can be verified.
   The reason why the digest algorithm can point out whether the data has been tampered with is because the digest function is a one-way function. It is easy to calculate f(data), but it is very difficult to reverse the data through digest. Moreover, making a bit modification to the original data will result in a completely different calculated summary. Hash algorithm encrypted data generally adopts base64 encoding format. Commonly used hash calculation examples are as follows:

3.1 md5 encryption

 It is the most common digest algorithm, which is very fast, and the generated result is a fixed 128-bit byte, usually represented by a 32-bit hexadecimal string.

import hashlib
hash = hashlib.md5()
hash.update("mayi".encode("utf-8"))
# 7d1080e20427559fcc0a647826741f66
print(hash.hexdigest())

3.2 sha1 encryption

 The result of SHA1 is 160 bit bytes, usually represented by a 40-bit hexadecimal string.

import hashlib
hash = hashlib.sha1()
hash.update("mayi".encode("utf-8"))
# c159ce3114fb4553683cf96d91db6d51080c02e8
print(hash.hexdigest())

3.3 sha256 encryption

Algorithms that are more secure than SHA1 are SHA256 and SHA512, but the more secure algorithms are slower and the digest length is longer.

import hashlib
hash = hashlib.sha256()
hash.update("mayi".encode("utf-8"))
# 5dfae51e782cce2f213ef6bc89f75c9ab6c3bd8a5d1299a73191677cd5aa1f93
print(hash.hexdigest())

3.4 sha384 encryption

import hashlib
hash = hashlib.sha384()
hash.update("mayi".encode("utf-8"))
# a1eb5c52e830d5ea4fdb0a3dc2241374f56426aebacd8890a69c7db57724788ec5047a005ecff4a23310b7f87035926f
print(hash.hexdigest())

3.5 sha512 encryption

import hashlib
hash = hashlib.sha512()
hash.update("mayi".encode("utf-8"))
# 93102ec5658f739c060e3d82096e538ec116d0c9d6925119b465f0823be99697056518465cc6fe75265deb26632c8ce62b3d63a8782c492
daac2b9c03a89defe
print(hash.hexdigest())

3.6 "Salt" encryption

  Although the above encryption algorithms are very powerful, there are still flaws, which can be reversed by credentialing. Therefore, it is necessary to add a custom key to the encryption algorithm (by adding a user name or random characters, etc.) and then encrypt it.

import hashlib
hash = hashlib.md5('python'.encode('utf-8'))
hash.update("mayi".encode("utf-8"))
# b0758ad1aad20530044668775f389922
print(hash.hexdigest())

Guess you like

Origin blog.csdn.net/weixin_44462773/article/details/128854517