您的位置:首页 > 其它

Base64修改标准串编码

2020-06-07 04:33 183 查看

了解Base64

这部分网上很多具体就不介绍了,总之原有的Base64的标准串是
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
本偏博客的目的就是分享一个脚本,当标准串改变时能够根据所给的标准串进行编码和解码

话不多说直接上代码

#coding:utf-8
import re
import base64
import string
import random
def base64_encode(s, dictionary):
r = ""
p = ""
c = len(s) % 3

if (c > 0):
for i in range(c, 3):
p += '='
s += "\0"

for c in range(0, len(s), 3):
n = (ord(s[c]) << 16) + (ord(s[c+1]) << 8) + (ord(s[c+2]))
n = [(n >> 18) & 0x3F, (n >> 12) & 0x3F, (n >> 6) & 0x3F, n & 0x3F]
r += dictionary[n[0]] + dictionary[n[1]] + dictionary[n[2]] + dictionary[n[3]]
return r[0:len(r) - len(p)]  + p

def base64_decode(s, dictionary):
base64inv = {}
for i in range(len(dictionary)):
base64inv[dictionary[i]] = i

s = s.replace("\n", "")
if not re.match(r"^([{alphabet}]{{4}})*([{alphabet}]{{3}}=|[{alphabet}]{{2}}==)?$".format(alphabet = dictionary), s):
raise ValueError("Invalid input: {}".format(s))

if len(s) == 0:
return ""
p = "" if (s[-1] != "=") else "AA" if (len(s) > 1 and s[-2] == "=") else "A"
r = ""
s = s[0:len(s) - len(p)] + p
for c in range(0, len(s), 4):
n = (base64inv[s[c]] << 18) + (base64inv[s[c+1]] << 12) + (base64inv[s[c+2]] << 6) + base64inv[s[c+3]]
r += chr((n >> 16) & 255) + chr((n >> 8) & 255) + chr(n & 255)
return r[0:len(r) - len(p)]
def test_base64():
dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def random_string(length):
return ''.join(random.choice(string.ascii_letters) for m in range(length))
for i in range(100):
s = random_string(i)
encoded = base64_encode(s, dictionary)
assert(encoded == base64.b64encode(s))
assert(s == base64_decode(encoded, dictionary))
if __name__ == "__main__":
dictionary =  "/abcdefghIJKLMNOPQRSTUVWXYZABCDEFGijklmnopqrstuvwxyz0123456789+"#这里放修改的base64标准串,否则就是默认的base64标准串
print(base64_decode("YmxGY3s3MnMnYjd3Y2X5XWM5YfpoXWQkNSMlMzMnYjl9", dictionary))

案例

一道逆向题,用IDA分析得到如下

主函数
sub_400735
根据base64的原理可以知道这是一个base64的编码,看到最后一个步骤就是根据字典匹配进行编码

跟进查看该数组的值
知道这个编码顺序不一样了这个时候就上我们的脚本,修改标准串。跑脚本得到结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: