在Python中将UTF-8转换为UTF-7

问题描述 投票:0回答:1

我正在尝试找到一种在 python 中实现这一点的方法: CyberChef 示例

我想从 UTF-8 转换为 UTF-7。

例如,给定字符串

<root><test>aaa</test><hel>asd</hel></root>

编码输出应该是字节

+ADw-root+AD4-+ADw-test+AD4-aaa+ADw-/test+AD4-+ADw-hel+AD4-asd+ADw-/hel+AD4-+ADw-/root+AD4-

我尝试使用编解码器和解码('utf-7'),但这只是按原样返回字符串:

>>> "<root><test>aaa</test><hel>asd</hel></root>".encode("utf-7")
b'<root><test>aaa</test><hel>asd</hel></root>'
python encoding utf-8 utf-7
1个回答
0
投票

<
>
属于 UTF-7 (RFC 2152) 所谓的“可选直接字符”。这些字符可以直接编码为其 ASCII 等效项,也可以使用 Unicode 移位编码进行编码。

例如,当编码为 UTF-7 时,Python 选择对

<
使用直接编码:

>>> "<".encode("utf-7")
b'<'

从 UTF-7 解码字节时,Python 会很乐意处理直接编码或 Unicode 移位编码

<
:

>>> b"+ADw-".decode("utf-7")
'<'
>>> b"<".decode("utf-7")
'<'

如果您想获得

<
(或其他可选的直接字符)的 Unicode 移位编码,您需要手动将直接编码字符转换为其 Unicode 移位等效项,或使用提供更精细的不同 UTF-7 实现- 粒度编码控制。

要将

<
>
从直接编码手动转换为 Unicode 移位编码,您可以使用
bytes.replace
:

text = "<root><test>aaa</test><hel>asd</hel></root>"
payload = text.encode("utf-7")
payload = payload.replace(b"<", b"+ADw-")
payload = payload.replace(b">", b"+AD4-")

>>> print(payload)
b'+ADw-root+AD4-+ADw-test+AD4-aaa+ADw-/test+AD4-+ADw-hel+AD4-asd+ADw-/hel+AD4-+ADw-/root+AD4-'

>>> text == payload.decode("utf-7")
True
© www.soinside.com 2019 - 2024. All rights reserved.