简体   繁体   中英

VB.NET and sizeof

I'm converting some code from C# to VB.NET. I have the following line in C#

var bytes = new byte[password.Length * sizeof(char)];

Looking on MSDN it appears that VB.NET does not seem to have the sizeof operator. I understand there is a Marshal.SizeOf but further MSDN documentation states that the value returned can be different to that of sizeof .

Can anybody help? Is there an equivalent statement in VB.NET?

Additional Information

My aim is to convert a password into an array of bytes which I can then hash and then either store in a database or compare to a previously stored hash. But I don't necessarily want an answer relating to my particular situation.

Dim bytes(password.Length * xxx) As Byte
System.Buffer.BlockCopy(password.ToCharArray(), 0, bytes, 0, bytes.Length)
Dim sha512 = System.Security.Cryptography.SHA512.Create()
Dim hash = sha512.ComputeHash(bytes)

' compare hash or stroe in database

VB中的'Len'操作符将执行此操作(但它适用于实例,因此您需要相应地调整):

Dim bytes = New Byte((someString.Length * Len(New Char)) - 1){}

VB.NET's Char maps to .NET's System.Char , which is defined in ECMA 335 to be a 16-bit Unicode character. Meaning, Char has a fixed size (no matter on which platform you compile or run your code), you don't actually need sizeof .

Therefore, just multiply by 2 .

I'm hashing a password and was following stackoverflow.com/a/10380166/1113475

The top answer there is wrong, in spite of high vote count. The code for that answer still uses an encoding (Unicode), because that's how all strings are encoded internally in .Net. Even if it didn't, the encoding still matters, because you need to be able to decrypt the string on a different system than the one that encrypted it and have meaningful results. Even with the same system doing the encryping/decrypting, soemthing as simple as a Windows Update patch to the .Net framework could break this. Pick an encoding (like Unicode or UTF-8), and just call it's GetBytes() method:

Dim bytes = Encoding.Unicode.GetBytes(password)

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.

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