mysql password 函数,使用.NET或MS SQL模拟MySql的password()加密

小编典典

根据MySQL文档,该算法是双SHA1哈希。在检查MySQL源代码时,您会在libmysql /

password.c中找到一个名为make_scrambled_pa​​ssword()的函数。该函数定义如下:

/*

MySQL 4.1.1 password hashing: SHA conversion (see RFC 2289, 3174) twice

applied to the password string, and then produced octet sequence is

converted to hex string.

The result of this function is used as return value from PASSWORD() and

is stored in the database.

SYNOPSIS

make_scrambled_password()

buf OUT buffer of size 2*SHA1_HASH_SIZE + 2 to store hex string

password IN NULL-terminated password string

*/

void

make_scrambled_password(char *to, const char *password)

{

SHA1_CONTEXT sha1_context;

uint8 hash_stage2[SHA1_HASH_SIZE];

mysql_sha1_reset(&sha1_context);

/* stage 1: hash password */

mysql_sha1_input(&sha1_context, (uint8 *) password, (uint) strlen(password));

mysql_sha1_result(&sha1_context, (uint8 *) to);

/* stage 2: hash stage1 output */

mysql_sha1_reset(&sha1_context);

mysql_sha1_input(&sha1_context, (uint8 *) to, SHA1_HASH_SIZE);

/* separate buffer is used to pass 'to' in octet2hex */

mysql_sha1_result(&sha1_context, hash_stage2);

/* convert hash_stage2 to hex string */

*to++= PVERSION41_CHAR;

octet2hex(to, (const char*) hash_stage2, SHA1_HASH_SIZE);

}

使用此方法,您可以创建一个基本上执行相同操作的.NET副本。这是我想出的。当我运行SELECT PASSWORD(’test’);

针对我的MySQL本地副本,返回的值是:

*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29

根据源代码(再次在password.c中),星号开头表示这是MySQL 4.1之后的加密密码方法。例如,当我在VB.Net中模拟功能时,这就是我想出的:

Public Function GenerateMySQLHash(ByVal strKey As String) As String

Dim keyArray As Byte() = Encoding.UTF8.GetBytes(strKey)

Dim enc = New SHA1Managed()

Dim encodedKey = enc.ComputeHash(enc.ComputeHash(keyArray))

Dim myBuilder As New StringBuilder(encodedKey.Length)

For Each b As Byte In encodedKey

myBuilder.Append(b.ToString("X2"))

Next

Return "*" & myBuilder.ToString()

End Function

请记住,SHA1Managed()在System.Security.Cryptography命名空间中。此方法返回的输出与MySQL中的PASSWORD()调用相同。希望对您有帮助。

编辑:这是C#中的相同代码

public string GenerateMySQLHash(string key)

{

byte[] keyArray = Encoding.UTF8.GetBytes(key);

SHA1Managed enc = new SHA1Managed();

byte[] encodedKey = enc.ComputeHash(enc.ComputeHash(keyArray));

StringBuilder myBuilder = new StringBuilder(encodedKey.Length);

foreach (byte b in encodedKey)

myBuilder.Append(b.ToString("X2"));

return "*" + myBuilder.ToString();

}

2021-03-10

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值