文章

代码中密码加密解密

代码中密码加密解密

本文档介绍 代码中密码加密解密 的相关内容。

基于Cryptodome 加密

# -*- coding: utf-8 -*- """'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' # 文件:encryption.py # 日期:2019-07-31 # 备注:多种加解密方法 # pip install pycryptodome(pip3 install pycryptodome) 用py Cryptodome 模块带的aes先将秘钥以及要加密的文本填充为16位 AES key must be either 16, 24, or 32 bytes long ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''""" import base64 from Crypto.Cipher import AES # bytes不是32的倍数那就补足为32的倍数 def add_to_32(value): while len(value) % 32 != 0: value += b'\x00' return value # 返回bytes # str转换为bytes超过32位时处理 def cut_value(org_str): org_bytes = str.encode(org_str) n = int(len(org_bytes) / 32) print('bytes长度:', len(org_bytes)) i = 0 new_bytes = b'' while n >= 1: i = i + 1 new_byte = org_bytes[(i - 1) * 32:32 * i - 1] new_bytes += new_byte n = n - 1 if len(org_bytes) % 32 == 0: # 如果是32的倍数,直接取值 all_bytes = org_bytes elif len(org_bytes) % 32 != 0 and n > 1: # 如果不是32的倍数,每次截取32位相加,最后再加剩下的并补齐32位 all_bytes = new_bytes + add_to_32(org_bytes[i * 32:]) else: all_bytes = add_to_32(org_bytes) # 如果不是32的倍数,并且小于32位直接补齐 print(all_bytes) return all_bytes def AES_encrypt(org_str, key): # 初始化加密器 aes = AES.new(cut_value(key), AES.MODE_ECB) # 先进行aes加密 encrypt_aes = aes.encrypt(cut_value(org_str)) # 用base64转成字符串形式 encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8') # 执行加密并转码返回bytes print(encrypted_text) return (encrypted_text) def AES_decrypt(secret_str, key): # 初始化加密器 aes = AES.new(cut_value(key), AES.MODE_ECB) # 优先逆向解密base64成bytes base64_decrypted = base64.decodebytes(secret_str.encode(encoding='utf-8')) # 执行解密密并转码返回str decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '') print(decrypted_text) if __name__ == '__main__': org_str = 'Wangke.0912' # 秘钥 key = '123acb' secret_str = AES_encrypt(org_str, key) AES_decrypt(secret_str, key)

自定义加密

# -*- coding: utf-8 -*- """'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 自定义加密解密 ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''""" def encrypt(key, s): b = bytearray(str(s).encode("utf-8")) n = len(b) # 求出 b 的字节数 c = bytearray(n * 2) j = 0 for i in range(0, n): b1 = b[i] b2 = b1 ^ key # b1 = b2^ key c1 = b2 % 16 c2 = b2 // 16 # b2 = c2*16 + c1 c1 = c1 + 65 c2 = c2 + 65 # c1,c2都是0~15之间的数,加上65就变成了A-P 的字符的编码 c[j] = c1 c[j + 1] = c2 j = j + 2 return c.decode("utf-8") def decrypt(key, s): c = bytearray(str(s).encode("utf-8")) n = len(c) # 计算 b 的字节数 if n % 2 != 0: return "" n = n // 2 b = bytearray(n) j = 0 for i in range(0, n): c1 = c[j] c2 = c[j + 1] j = j + 2 c1 = c1 - 65 c2 = c2 - 65 b2 = c2 * 16 + c1 b1 = b2 ^ key b[i] = b1 try: return b.decode("utf-8") except: return "failed" if __name__ == '__main__': password = 'YOUR_PASSWORD' a = encrypt(100, password) print(a) b = decrypt(100, a) print(b)
本文由作者按照 CC BY 4.0 进行授权