Python 求助!!!关于特殊字符 MD5,SHA256 加密处理

Yellow · November 15, 2019 · Last by Yellow replied at November 18, 2019 · 2156 hits

背景

因公司接口组装请求参数的方式为 XML,当拿到请求参数后需要把 XML 格式转换为 JSON,这里使用的是 xmltodict 第三方库,但是在转换的过程中,如果 XML 参数的值中存在特殊字符,则 xmltodict 库的 parse() 方法内部会把特殊字符转义,导致加密完成后的参数校验失败。

实例

目前碰到的存在转义问题的特殊字符为 & ,当 XML 参数的值中包含 & 字符时,经过 xmltodict.parse() 方法转化为 json 后,会自动转义为& 导致之后的加密参数和一开始传入到方法中的 XML 不匹配。

目前的解决方法

因为是 Python 第三方库导致的转义问题,所以暂时没有找到其他的办法,只能在加密之前,把转义之后的 amp;字符串替换为空,可以暂时解决 & 特殊字符转义的问题。

求助

目前只能解决 & 特殊字符的问题,如果下一次出现其他字符转义的问题,还需要重新修改代码,请教一下社区的各位,有没有治本的办法?

共收到 6 条回复 时间 点赞

包含转义部分的代码在 Source code: Lib/xml/sax/saxutils.py,特殊字符只有三个"&","<",">"。直接调 xml.sax.saxutils.unescape 方法就好了。或者自己替换回转义前的字符。

xml.sax.saxutils.escape(data, entities={})
  Escape '&', '<', and '>' in a string of data.
  You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. The characters '&', '<' and '>' are always escaped, even if entities is provided.

xml.sax.saxutils.unescape(data, entities={})
  Unescape '&amp;', '&lt;', and '&gt;' in a string of data.
  You can unescape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. '&amp', '&lt;', and '&gt;' are always unescaped, even if entities is provided.

好的,谢谢。


json 在哪里?

hellohell 回复

额,是我说的不对,是 xml 转成 dict。

不改源码就是导入一个模块,然后在本地复写一层啊,过滤条件还是得定制的,可以根据项目和规则做一个缓存字典啊
key 项目名称版本号,value 就是调转义过滤处理的一个参数,然后字典载入到本地复写的那层。
这个还好没转义字符,一样处理就好了。

陈子昂 回复

好的,感谢。

需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up