繁体   English   中英

Python 八进制转义字符串

[英]Python Octal Escape String

我正在执行 web 应用程序登录自动化。 web app前缀和后缀几个八进制转义字符加密码,在客户端将密码md5 hash发送给服务器。

因此,当我使用 Java 脚本对字符串进行 Md5 加密时,得到以下结果。

webapp 使用https://ideone.com/2C1b5 JS 库进行客户端 MD5 转换。 hexMD5()属于该库。

在此处输入图像描述

但是当我尝试使用 python 做同样的事情时,我得到了不同的结果。

import hashlib
def getMd5(string):
    m = hashlib.md5()
    m.update(string)
    return m.hexdigest()
prefix = "\051"
suffix  = "\341\303\026\153\155\271\161\166\030\054\324\011\046\035\344\274"

prefix = unicode(prefix,'unicode-escape')
suffix = unicode(suffix,'unicode-escape')
salted = prefix+"HELLO"+suffix
print getMd5(salted.encode('utf8'))

结果

c7862e873e9bc54a93aec58c199cda37

谁能解释一下我在这里做错了什么?

import hashlib
def getMd5(string):
    m = hashlib.md5()
    m.update(string)
    return m.hexdigest()
prefix = "\051"
suffix  ="\341\303\026\153\155\271\161\166\030\054\324\011\046\035\344\274"


salted = prefix+"HELLO"+suffix
print getMd5(salted)

37a0c199850b36090b439c3ac152fd70

不使用 unicode 会得到与 Javascript 相同的 output。

如果我正确理解您的评论:

len(r"\051" == 4 # use raw string r
len("\051") == 1 

这个问题很老,但我前几天遇到了这个问题,上面的答案无法解决,所以我用这种方式解决了。

1-首先将所有字符转换为八进制相等格式

HELLO => \110\105\114\114\117

通过这个函数stringToOctal

def dectoOct(decimal):
    octal = 0
    ctr = 0
    temp = decimal
    while (temp > 0):
        octal += ((temp % 8) * (10 ** ctr))
        temp = int(temp / 8)
        ctr += 1
    return octal

def stringToOctal(string):
    result = ""
    for character in list(string):
        result += "\\"+ str(dectoOct(ord(character)))
    return result

那么结果应该是这样的

\051\110\105\114\114\117\341\303\026\153\155\271\161\166\030\054\324\011\046\035\344\274

2- 将八进制数转换为字节

最终代码是这样的:

import hashlib

def dectoOct(decimal):
    octal = 0
    ctr = 0
    temp = decimal
    while (temp > 0):
        octal += ((temp % 8) * (10 ** ctr))
        temp = int(temp / 8)
        ctr += 1
    return octal

def stringToOctal(string):
    result = ""
    for character in list(string):
        result += "\\"+ str(dectoOct(ord(character)))
    return result

prefix = r"\051"
suffix  =r"\341\303\026\153\155\271\161\166\030\054\324\011\046\035\344\274"
word = "HELLO"


octalCharacters = prefix + stringToOctal(word) + suffix

hashed = hashlib.md5(bytes([int(i, 8) for i in octalCharacters.split("\\")[1:]]))

result = hashed.hexdigest()

结果:

37a0c199850b36090b439c3ac152fd70

暂无
暂无

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

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