逆向常用python代码

字符串转数组列表

def strTolist(str):
    ans = list(str)
    for i in range(len(ans)):
        ans[i] = ord(ans[i])
    return ans

str='Hello'
print(strTolist(str))
#输出:[72, 101, 108, 108, 111]

16进制字符串转字符串

def hexstrTostr(hexstr):
    byte_str = bytes.fromhex(hexstr)
    return byte_str.decode("utf-8")

hexstr = "48656c6c6f"
print(hexstrTostr(hexstr))
# 输出:Hello
# 0x48->H 0x65->e 0x6c->l 0x6c->l 0x6f->0

16进制字符串转列表

def hexstrTolist(hexstr):
    ans = []
    if len(hexstr) % 2 == 1:
        print("两两分组要双数字符串")
    else:
        for i in range(0, len(hexstr), 2):
            ans.append(int(hexstr[i:i + 2], 16))
        print("分组后列表:", ans)

        # 使用列表推导式将列表中的数据转换为十六进制形式并打印
        hex_data_list = ["0x{:02x}".format(item) for item in ans]
        tmp = ",".join(hex_data_list)
        print('分组后列表16进制显示: [' + tmp + ']')
    return ans

hexstr = "48656c6c6f"
hexstrTolist(hexstr)
#输出:
#分组后列表: [72, 101, 108, 108, 111]
#分组后列表16进制显示: [0x48,0x65,0x6c,0x6c,0x6f]

字符串中大写转小写

strs.lower()

字符串中大写转小写

strs.upper()

字符串大小写置换

def ulsub(old_strs):
    new_strs = ''
    for str in old_strs:
        if str.isupper():
            new_strs += chr(ord(str) + 32)
        elif str.islower():
            new_strs += chr(ord(str) - 32)
        else:
            new_strs += str
    return new_strs

倒序输出

for i in range(10,1,-1):
	print(i)
#输出:
#10
#9
#8
#7
#6
#5
#4
#3
#2

列表反转

data_list[::-1]

数组列表通过ASCII码转为字符串

def listTostr(table):
    ans = ''
    for item in table:
        ans = ans + chr(item)
    return ans
lt = [0x48,0x65,0x6c,0x6c,0x6f]
print(listTostr(lt))
#输出:Hello

base64换表

def base64_encode(message,base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"):
    # 将字符串编码为字节串
    message_bytes = message.encode('utf-8')

    # 计算需要补齐的字节数
    padding = 3 - (len(message_bytes) % 3)
    if padding == 3:
        padding = 0

    # 补齐字节串
    message_bytes += b'\x00' * padding

    # 将每3个字节编码为4个Base64字符
    encoded_chars = []
    for i in range(0, len(message_bytes), 3):
        # 3个字节转换为一个24位整数
        value = (message_bytes[i] << 16) + (message_bytes[i + 1] << 8) + message_bytes[i + 2]
        # 拆分24位整数为4组6位
        for j in range(4):
            index = (value >> ((3 - j) * 6)) & 63
            encoded_chars.append(base64_chars[index])

    # 根据补齐数添加 '=' 字符
    for i in range(padding):
        encoded_chars[-(i + 1)] = '='

    # 将字符列表转换为字符串并返回
    return ''.join(encoded_chars)


def base64_decode(encoded_message,base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"):

    # 初始化解码字节串
    decoded_bytes = bytearray()

    # 解码每4个Base64字符为3个字节
    for i in range(0, len(encoded_message), 4):
        # 将4个Base64字符映射回6位整数
        value = 0
        for j in range(4):
            if encoded_message[i + j] == '=':
                value <<= 6
            else:
                value <<= 6
                value += base64_chars.index(encoded_message[i + j])

        # 将6位整数拆分为3个字节
        for j in range(2, -1, -1):
            decoded_bytes.append((value >> (j * 8)) & 255)

    # 去除补齐字节
    while decoded_bytes[-1] == 0:
        decoded_bytes.pop()

    # 将字节串解码为字符串并返回
    ans = None
    try:
        ans = decoded_bytes.decode('utf-8')
    except Exception as e:
        print("[*]解码失败")
    return ans

message = "Hello, World!"
encoded_message = base64_encode(message,base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
print("Encoded:", encoded_message)

decoded_message = base64_decode(encoded_message,base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
print("Decoded:", decoded_message)

16进制字符串转10进制整数

hexstr = "1A3F"  # 十六进制字符串
decimal_number = int(hexstr, 16)
print(decimal_number)
#输出: 6719
#0x1A3F == 6719

10进制整数转16进制字符串

hex_result = hex(6719)
print(hex_result)
#输出: 0x1a3f
#0x1A3F == 6719

字符串循环移位

def strloopmove(old_strs, n, direction=True):
    """
    字符串循环移动
    :param old_strs: 待移动字符串
    :param n: 移动距离
    :param direction: 方向,True表示左移,True表示右移
    :return: 循环移动后的字符串
    """
    new_strs = ''
    if direction == True:
        for str in old_strs:
            new_strs += old_strs[(old_strs.index(str) + n) % len(old_strs)]
    else:
        for str in old_strs:
            new_strs += old_strs[(old_strs.index(str) - n) % len(old_strs)]
    return new_strs

位置映射

def create_position_mapping(old_table, new_table):
    """
    创建位置映射字典,仅显示 old_table 和 new_table 中的位置关系。

    参数:
    old_table (str): 原始字符表。
    new_table (str): 新的字符表。

    返回:
    dict: 一个包含旧表位置到新表位置映射的字典。

    抛出:
    ValueError: 如果old_table和new_table不匹配,或包含重复字符。
    """
    # 检查是否有重复字符
    if len(set(old_table)) != len(old_table):
        raise ValueError("old_table contains duplicate characters")
    if len(set(new_table)) != len(new_table):
        raise ValueError("new_table contains duplicate characters")

    # 检查是否能够相互找到字符
    if set(old_table) != set(new_table):
        raise ValueError("old_table and new_table must contain the same characters")

    # 创建一个空字典来存储位置关系
    position_mapping = {}

    # 遍历old_table来填充字典
    for old_index, old_char in enumerate(old_table):
        new_index = new_table.index(old_char)  # 获取old_char在new_table中的位置
        position_mapping[old_index] = new_index

    return position_mapping

def map_string(table, mapping):
    """
    根据给定的映射关系对字符串进行重新排列。

    参数:
    table (str): 需要映射的原始字符串。
    mapping (dict): 位置关系的映射字典。

    返回:
    str: 映射后的字符串。

    抛出:
    ValueError: 如果table的长度和mapping的长度不同。
    """
    # 检查table的长度和mapping的长度是否相同
    if len(table) != len(mapping):
        raise ValueError("The length of the table and the length of the mapping must be the same")

    # 创建一个与原始字符串长度相同的列表,用于存放映射后的字符
    mapped = [''] * len(table)

    # 遍历原始字符串的每个字符和其对应的索引,按照映射关系将字符放到新的位置上
    for original_index, char in enumerate(table):
        new_index = mapping[original_index]
        mapped[new_index] = char

    # 将列表转换回字符串
    mapped_string = ''.join(mapped)

    return mapped_string


# 创建位置替换表
old_table = "ABCDEF"
new_table = "BACFED"
position_mapping = create_position_mapping(old_table, new_table)

//print(position_mapping)
//{0: 1, 1: 0, 2: 2, 3: 5, 4: 4, 5: 3}

# 位置替换
table = "GHILMO"
mapped_table = map_string(table, position_mapping)
//print(mapped_table)
//HGIOML

值映射

s="BFDD"
old_table = "ABCDEF"
new_table = "GHIJKL"

#生成替换表
trans_table = str.maketrans(old_table, new_table)
# print(trans_table)
# {65: 71, 66: 72, 67: 73, 68: 74, 69: 75, 70: 76}

#替换函数
def translate_string(s, trans_table):
    # 检查s中的字符是否都在trans_table的键中
    for char in s:
        if ord(char) not in trans_table:
            raise ValueError(f"Character {char} in string is not in the translation table")

    # 进行字符替换
    return s.translate(trans_table)

result = translate_string(s,trans_table)
# print(result)
# HLJJ
posted @ 2024-03-26 14:56  noahze  阅读(14)  评论(0编辑  收藏  举报