Python是否可以对字符串进行编码以匹配ASP.NET成员资格提供程序的EncodePassword [英] Can Python encode a string to match ASP.NET membership provider's EncodePassword

查看:51
本文介绍了Python是否可以对字符串进行编码以匹配ASP.NET成员资格提供程序的EncodePassword的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python脚本从类似于ASP.NET的MembershipProvider的现有系统创建哈希字符串.使用Python,有一种方法可以获取十六进制字符串,然后将其转换回二进制,然后进行base64编码,以某种方式将原始字符串视为Unicode.让我们尝试一些代码.我正在寻找重新编码哈希密码的方法,以便在Python和ASP.NET/C#中哈希值相等:

I'm working on a Python script to create hashed strings from an existing system similar to that of ASP.NET's MembershipProvider. Using Python, is there a way to take a hexadecimal string and convert it back to a binary and then do a base64 encoding, somehow treating the original string as Unicode. Let's try some code. I'm looking to re-encode a hashed password so that the hashes would be equal in Python and ASP.NET/C#:

import base64
import sha
import binascii

def EncodePassword(password):
    # strings are currently stored as hex
    hex_hashed_password = sha.sha(password).hexdigest()

    # attempt to convert hex to base64
    bin_hashed_password = binascii.unhexlify(hex_hashed_password)
    return base64.standard_b64encode(bin_hashed_password)

print EncodePassword("password")
# W6ph5Mm5Pz8GgiULbPgzG37mj9g=

ASP.NET MembershipProvider使用此方法进行编码:

The ASP.NET MembershipProvider users this method to encode:

static string EncodePassword(string pass)
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    //bytes = Encoding.ASCII.GetBytes(pass);

    byte[] inArray = null;
    HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
    inArray = algorithm.ComputeHash(bytes);
    return Convert.ToBase64String(inArray);
}

string s = EncodePassword("password");
// 6Pl/upEE0epQR5SObftn+s2fW3M=

不匹配.但是,当我使用以ASCII编码的密码运行它时,它会匹配,因此.NET方法的Unicode部分有什么区别.

That doesn't match. But, when I run it with the password encoded with ASCII encoding, it matches, so the Unicode part of the .NET method is what's the difference.

W6ph5Mm5Pz8GgiULbPgzG37mj9g =

W6ph5Mm5Pz8GgiULbPgzG37mj9g=

python脚本中是否有一种方法来获取与默认.NET版本匹配的输出?

Is there a way in the python script to get an output to match the default .NET version?

推荐答案

这是窍门:

Encoding.Unicode

Encoding.Unicode

"Unicode"编码使Microsoft在使用UTF-16LE时感到困惑(特别是没有任何BOM).将字符串编码为哈希之前的字符串,您会得到正确的答案:

"Unicode" encoding is confusing Microsoft-speak for UTF-16LE (specifically, without any BOM). Encode the string to that before hashing and you get the right answer:

>>> import hashlib
>>> p= u'password'
>>> hashlib.sha1(p.encode('utf-16le')).digest().encode('base64')
'6Pl/upEE0epQR5SObftn+s2fW3M=\n'

这篇关于Python是否可以对字符串进行编码以匹配ASP.NET成员资格提供程序的EncodePassword的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆