Theo tài liệu MySQL, thuật toán là hàm băm SHA1 kép. Khi kiểm tra mã nguồn MySQL, bạn tìm thấy một hàm gọi là make_scrambled_password() trong libmysql/password.c. Hàm được định nghĩa như sau:
/*
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);
}
Với phương pháp này, bạn có thể tạo đối tác .NET về cơ bản cũng làm như vậy. Đây là những gì tôi đã đưa ra. Khi tôi chạy SELECT PASSWORD ('test'); chống lại bản sao cục bộ của tôi về MySQL, giá trị trả về là:
*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29
Theo mã nguồn (một lần nữa trong password.c), dấu hoa thị bắt đầu chỉ ra rằng đây là phương pháp 4.1 hậu MySQL của mã hóa mật khẩu. Khi tôi mô phỏng các chức năng trong VB.Ví dụ: net, đây là những gì tôi đưa ra:
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
Hãy nhớ rằng SHA1Managed() nằm trong không gian tên System.Security.Cryptography. Phương thức này trả về kết quả đầu ra giống như lời gọi PASSWORD() trong MySQL. Tôi hy vọng điều này sẽ giúp ích cho bạn.
Edit: Đây là cùng mã trong 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();
}
Bạn đang sử dụng phiên bản MySQL nào? Có vẻ như điều này có thể xảy ra nếu bạn biết bạn đang sử dụng phiên bản nào. MySQL sử dụng thuật toán băm SHA1 kép để mã hóa mật khẩu. –
Sẽ kiểm tra điều này khi tôi có quyền truy cập vào DB mysql. Cảm ơn bạn đã đăng giải pháp! –