Python Base64补全= 代码

Python Base64补全= 代码


学会如何补全Base64


补全原理

base64编码后的字符串,每4字节一组。


例子:(下面的base64编码后的字符串都没有 = 符号)

编码后len补全几个 = 符号补全后解码后
aGVsbA64 - (6 % 4) = 2aGVsbA==hell
aGVsbG874 - (7 % 4) = 1aGVsbG8=hello
aGVsbG9388 % 4 == 0,所以不需要补aGVsbG93hellow

代码逻辑:

  • 1.先用 len % 4 如果等于0,就说明不需要补=
  • 2.len % 4 不等于0,就说明需要补=,末尾补全 4 - (len % 4)=

Python代码如下:

wf = open("base64_str补全=后.txt", "w")

with open("base64_str.txt", "r") as f:
    data = f.read()
    data = data.splitlines()

for line in data:
    missing_padding = len(line) % 4
    if missing_padding != 0:
        line += "=" * (4 - missing_padding)
    wf.write(line + "\n")
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用Python实现AES和DES的示例代码: AES加密解密示例代码: ```python from Crypto.Cipher import AES import base64 # 加密函数 def aes_encrypt(key, data): cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB) data = data.encode('utf-8') # 补全16位 length = 16 - (len(data) % 16) data += bytes([length]) * length ciphertext = cipher.encrypt(data) # 转换为base64编码 return base64.b64encode(ciphertext).decode('utf-8') # 解密函数 def aes_decrypt(key, ciphertext): cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB) # 解码base64 ciphertext = base64.b64decode(ciphertext) data = cipher.decrypt(ciphertext) # 去除补位 length = data[-1] data = data[:-length] return data.decode('utf-8') # 测试 key = '0123456789abcdef' data = 'hello world' ciphertext = aes_encrypt(key, data) print(ciphertext) plaintext = aes_decrypt(key, ciphertext) print(plaintext) ``` DES加密解密示例代码: ```python from Crypto.Cipher import DES import base64 # 加密函数 def des_encrypt(key, data): cipher = DES.new(key.encode('utf-8'), DES.MODE_ECB) data = data.encode('utf-8') # 补全8位 length = 8 - (len(data) % 8) data += bytes([length]) * length ciphertext = cipher.encrypt(data) # 转换为base64编码 return base64.b64encode(ciphertext).decode('utf-8') # 解密函数 def des_decrypt(key, ciphertext): cipher = DES.new(key.encode('utf-8'), DES.MODE_ECB) # 解码base64 ciphertext = base64.b64decode(ciphertext) data = cipher.decrypt(ciphertext) # 去除补位 length = data[-1] data = data[:-length] return data.decode('utf-8') # 测试 key = '01234567' data = 'hello world' ciphertext = des_encrypt(key, data) print(ciphertext) plaintext = des_decrypt(key, ciphertext) print(plaintext) ``` 注意:这里仅提供示例代码,实际使用需要根据具体情况进行调整和优化。同时,使用对称密码算法时,需要注意密钥的安全性和保密性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值