I have a problem with the password encryption. I would like to have the password encrypted like those not highlighted in the picture.
I wrote the following c# code:
SHA1CryptoServiceProvider x = new SHA1CryptoServiceProvider();
//byte[] bs = System.Text.Encoding.Unicode.GetBytes(password);
//byte[] bs = System.Text.Encoding.UTF32.GetBytes(password);
byte[] bs = System.Text.Encoding.UTF8.GetBytes(password);
bs = x.ComputeHash(bs);
var s = new StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
new UserService().ChangeUserPassword(username, s.ToString());
to encrypt the password in the correct way I using the following SQL code that I want remove:
CAST(hashbytes('SHA1',@newuserpassword) as nvarchar)
this is the result:
Looking at the docs for CONVERT
, I suspect you just want:
CONVERT(nvarchar, hashbytes('SHA1',@newuserpassword), 2)
Where 2 is the style which converts to hex without a leading 0x. I suggest you specify the length of the nvarchar
though, which should be 40 (20 bytes, 2 characters per byte).
I strongly advise you to abandon storing binary data in characters. Still, if you need to keep it for legacy reasons, here is the translation of the SQL statement:
byte[] bytes = ...; //your binary data here
var nastilyBrokenChars =
Enumerable.Range(0, bytes.Length / 2)
.Select(i => (char)BitConverter.GetInt16(bytes, i * 2))
.ToArray();
string nastilyBrokenString = new string(nastilyBrokenChars);
As you can, I'm stuffing two bytes
into each char
. This by itself is a lossless conversion. But I wouldn't trust that storing this data into SQL Server (and comparing it later) is loss-less.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.