简体   繁体   English

如何从字符串内部安全地获取字节文字

[英]How to safely get byte literal from inside string

As a challenge to myself, I wanted to see how I could safely extract a byte literal from inside a regular string. 作为对自己的挑战,我想看看如何安全地从常规字符串中提取字节文字。 However, I'm not able to safely extract the byte literal out. 但是,我不能安全地提取出字节文字。

Example string: 示例字符串:

'b"\\xfeq\\xed\\xad7E\'\\x9a\\xb4_ p\\xdf\\x98\\tC\\xcb\\xe7\\xaa\\x80`\\x93\\x1a\\xf5?\\x03j\\xa4\\x93vT\\xd9"'

Goal: 目标:

b"\xfeq\xed\xad7E'\x9a\xb4_ p\xdf\x98\tC\xcb\xe7\xaa\x80`\x93\x1a\xf5?\x03j\xa4\x93vT\xd9"

After spending some time going through the documentation, this was the best solution that I could come up with. 在花了一些时间阅读文档之后,这是我能想到的最佳解决方案。 ast.literal_eval Is the best way to evaluate literal expressions from untrusted sources. ast.literal_eval是评估不受信任来源的文字表达式的最佳方法。 The except clause is left purposefully broad in order to accommodate for any possible errors. 故意将except子句保留得较宽,以适应任何可能的错误。

import ast

def extract_binary_literal(input: str):
    try:
        result = ast.literal_eval(input)
        if type(result) == bytes:
            return result
    except Exception:
        pass
    return None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM