Converting C# to VB code - vb.net

I have this c# code that creates a CRC code. It works correctly in c#. I converted it to VB but it is not generating the correct CRC code. Could somebody please help me figure out what is wrong with the VB code.
you call GetMessageBytes with a string and get back a bytes array with the CRC added
static byte[] GetMessageBytes(string text)
{
//Get bytes for command
byte[] command = Encoding.ASCII.GetBytes(text);
//Get CRC for command bytes
ushort crc = CalculateCrc(command);
//Append CRC and CR to command
byte[] result = new byte[command.Length + 3];
command.CopyTo(result, 0);
result[result.Length - 3] = (byte)((crc >> 8) & 0xFF);
result[result.Length - 2] = (byte)((crc >> 0) & 0xFF);
result[result.Length - 1] = 0x0d;
return result;
}
static ushort CalculateCrc(byte[] pin)
{
ushort crc;
byte da;
byte ptr;
byte bCRCHign;
byte bCRCLow;
int len = pin.Length;
ushort[] crc_ta = new ushort[]
{
0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef
};
crc = 0;
for (int index = 0; index < len; index++)
{
ptr = pin[index];
da = (byte)(((byte)(crc >> 8)) >> 4);
crc <<= 4;
crc ^= crc_ta[da ^ (ptr >> 4)];
da = (byte)(((byte)(crc >> 8)) >> 4);
crc <<= 4;
crc ^= crc_ta[da ^ (ptr & 0x0f)];
}
//Escape CR,LF,'H' characters
bCRCLow = (byte)(crc & 0x00FF);
bCRCHign = (byte)(crc >> 8);
if (bCRCLow == 0x28 || bCRCLow == 0x0d || bCRCLow == 0x0a)
{
bCRCLow++;
}
if (bCRCHign == 0x28 || bCRCHign == 0x0d || bCRCHign == 0x0a)
{
bCRCHign++;
}
crc = (ushort)(((ushort)bCRCHign) << 8);
crc |= bCRCLow;
return crc;
}
Here is the VB code.
Private Function GetMessageBytes(text As String) As Byte()
'Get bytes for command
Dim command As Byte() = System.Text.Encoding.Unicode.GetBytes(text)
'Get CRC for command bytes
Dim crc As UShort = CalcCrcHalf(command)
'Append CRC and CR to command
Dim result As Byte() = New Byte(command.Length + 3) {}
command.CopyTo(result, 0)
result(result.Length - 3) = CByte((crc >> 8) And &HFF)
result(result.Length - 2) = CByte((crc >> 0) And &HFF)
result(result.Length - 1) = &HD
Return result
End Function
Private Function CalculateCRC(pin As Byte()) As UShort
Dim crc As UShort
Dim da As Byte
Dim ptr As Byte
Dim bCRCHign As Byte
Dim bCRCLow As Byte
Dim len As Integer = pin.Length
Dim crc_ta As UShort() = New UShort() {&H0, &H1021, &H2042, &H3063, &H4084, &H50A5, &H60C6, &H70E7, &H8108, &H9129, &HA14A, &HB16B, &HC18C, &HD1AD, &HE1CE, &HF1EF}
crc = 0
For index As Integer = 0 To len - 1
ptr = pin(index)
da = CByte(CByte(crc >> 8) >> 4)
crc <<= 4
crc = crc Xor crc_ta(da Xor (ptr >> 4))
da = CByte(CByte(crc >> 8) >> 4)
crc <<= 4
crc = crc Xor crc_ta(da Xor (ptr And &HF))
Next
'Escape CR,LF,'H' characters
bCRCLow = CByte(crc And &HFF)
bCRCHign = CByte(crc >> 8)
If bCRCLow = &H28 OrElse bCRCLow = &HD OrElse bCRCLow = &HA Then
bCRCLow += 1
End If
If bCRCHign = &H28 OrElse bCRCHign = &HD OrElse bCRCHign = &HA Then
bCRCHign += 1
End If
crc = CUShort(CUShort(bCRCHign) << 8)
crc = crc Or bCRCLow
Return crc
End Function

Thanks I got it working. It was the encoding.
This is the correct code.
retrun_string = System.Text.Encoding.GetEncoding(1252).GetString(result)

Dim hiByte as byte
Dim LoByter as byte
hiByte = crc \ &H100 And &HFF&
LoByte = crc And &HFF&
At least this worked for me.

Related

vb.net arithmetic operation resulted in an overflow in decryption

I am working on new decryption functions for password recovery tools. I tried code in c++ and worked:
void poco_pwd(u_char *pwd, int type) {
int len,
tmp;
u_char *out;
short azz;
if(type) azz = 0x2537; // encrypt message
else azz = 0x2a9a; // other passwords
len = strlen(pwd) >> 1;
out = pwd;
while(len--) {
sscanf(pwd, "%02X", &tmp);
pwd += 2;
*out++ = tmp ^ (azz >> 8);
azz = ((tmp + azz) * 0x8141) + 0x3171;
}
*out = 0;
}
I tried to convert this code to vb.net and c# but it throws arithmetic overflow operation. This functions new value is put to "azz" variable. "azz" is a short variable but this these values are very high. Strange is that it works in c++.
I converted this code to vb.net:
Dim encpass As String = "1EF66D8BD3C32476CEC8CF"
Dim encpassByte As Byte() = Encoding.UTF8.GetBytes(HexToString(encpass))
Dim azz As Integer = &H2A9A
Dim len As Integer = encpassByte.Length >> 1
Dim storage(len) As Char
For i = 0 To len
storage(i) = (ChrW(encpassByte(i) Xor (azz >> 8)))
azz = ((encpassByte(i) + azz) * &H8141) + &H3171 //Error: arithmetic operation resulted in an overflow.
Next
Console.WriteLine(storage.ToString)
Console.ReadKey()
Hex to string function:
Function HexToString(ByVal hex As String) As String
Dim text As New System.Text.StringBuilder(hex.Length \ 2)
For i As Integer = 0 To hex.Length - 2 Step 2
text.Append(Chr(Convert.ToByte(hex.Substring(i, 2), 16)))
Next
Return text.ToString
End Function
This code throws this error: arithmetic operation resulted in an overflow.

VB.net only 32 bytes and less to search

this is a function to search for a byte pattern (in process memory) in an array of bytes.
where SearchFor is the array of bytes to look for. and SearchInis the array of bytes dumped by the ReadProcessMemory external function. this is also done using Wildcard "?".
problem is if the byte pattern length is less or equal to 32 it will search. else return intptr.zero. and im not sure why.
Private Function WildCard(ByVal SearchIn As Byte(), ByVal SearchFor As Byte()) As IntPtr
Dim l As Integer = 0, m = 0
Dim iEnd As Integer = SearchFor.Length
Dim sBytes As Integer() = New Integer(&H100 - 1) {}
Dim i As Integer
For i = 0 To iEnd - 1
If (SearchFor(i) = &H3F) Then
l = (l Or (CInt(1) << ((iEnd - i) - 1)))
End If
Next i
If (l <> 0) Then
Dim j As Integer
For j = 0 To sBytes.Length - 1
sBytes(j) = l
Next j
End If
l = 1
Dim index As Integer = (iEnd - 1)
Do While (index >= 0)
sBytes(SearchFor(index)) = (sBytes(SearchFor(index)) Or l)
index -= 1
l = (l << 1)
Loop
Do While (m <= (SearchIn.Length - SearchFor.Length))
l = (SearchFor.Length - 1)
Dim length As Integer = SearchFor.Length
Dim k As Integer = -1
Do While (k <> 0)
k = (k And sBytes(SearchIn((m + l))))
If (k <> 0) Then
If (l = 0) Then
Return New IntPtr(m)
End If
length = l
End If
l -= 1
k = (k << 1)
Loop
m = (m + length)
Loop
Return IntPtr.Zero
End Function

Fibonacci shift register pseudo-random number generator

I am attempting to get the following code working for a Fibonacci shift register to generate pseudo-random numbers. Can't seem to get it working, so is(are) there any obvious issues(?)
Shared Function Main() As Integer
Dim start_state As UShort = &HACE1UI ' Any nonzero start state will work.
Dim lfsr As UShort = start_state
Dim bit As UInteger
Dim period As UInteger = 0
Do While lfsr <> start_state
' taps: 16 14 13 11; feedback polynomial: x^16 + x^14 + x^13 + x^11 + 1
bit = ((lfsr >> 0) Xor (lfsr >> 2) Xor (lfsr >> 3) Xor (lfsr >> 5)) And 1
lfsr = (lfsr >> 1) Or (bit << 15)
period += 1
Loop
Return 0
End Function
Last, does "period" need to be divided by a large integer to get U(0,1)'s?
Below is the original C++ code:
# include <stdint.h>
int main(void)
{
uint16_t start_state = 0xACE1u; /* Any nonzero start state will work. */
uint16_t lfsr = start_state;
uint16_t bit; /* Must be 16bit to allow bit<<15 later in the code */
unsigned period = 0;
do
{
/* taps: 16 14 13 11; feedback polynomial: x^16 + x^14 + x^13 + x^11 + 1 */
bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
lfsr = (lfsr >> 1) | (bit << 15);
++period;
} while (lfsr != start_state);
return 0;
}
As in #dummy's comment,
Do While lfsr <> start_state
...
Loop
doesn't run because lfsr = start_state at the beginning.
The code equivalent to C++
do {
...
} while (lfsr != start_state);
in VB.NET is
Do
...
Loop While lfsr <> start_state

How to implement murmurhash3 in VBNET

I'm trying to implement murmurhash3 in vb.net and trying to convert from this C# implementation
first part of the function in c#
public static SqlInt32 MurmurHash3(SqlBinary data)
{
const UInt32 c1 = 0xcc9e2d51;
const UInt32 c2 = 0x1b873593;
int curLength = data.Length; /* Current position in byte array */
int length = curLength; /* the const length we need to fix tail */
UInt32 h1 = seed;
UInt32 k1 = 0;
/* body, eat stream a 32-bit int at a time */
Int32 currentIndex = 0;
while (curLength >= 4)
{
/* Get four bytes from the input into an UInt32 */
k1 = (UInt32)(data[currentIndex++]
| data[currentIndex++] << 8
| data[currentIndex++] << 16
| data[currentIndex++] << 24);
/* bitmagic hash */
k1 *= c1;
k1 = rotl32(k1, 15);
k1 *= c2;
h1 ^= k1;
h1 = rotl32(h1, 13);
h1 = h1 * 5 + 0xe6546b64;
curLength -= 4;
}
And same in VB.net:
Public Shared Function MurmurHash3(data As Byte()) As Int32
Const c1 As UInt32 = &HCC9E2D51UI
Const c2 As UInt32 = &H1B873593
Dim curLength As Integer = data.Length
' Current position in byte array
Dim length As Integer = curLength
' the const length we need to fix tail
Dim h1 As UInt32 = seed
Dim k1 As UInt32 = 0
' body, eat stream a 32-bit int at a time
Dim dBytes As Byte()
Dim currentIndex As Int32 = 0
While curLength >= 4
' Get four bytes from the input into an UInt32
dBytes = New Byte() {data(currentIndex), data(currentIndex + 1), data(currentIndex + 2), data(currentIndex + 3)}
k1 = BitConverter.ToUInt32(dBytes, 0)
currentIndex += 4
' bitmagic hash
k1 *= c1
k1 = rotl32(k1, 15)
k1 *= c2
h1 = h1 Xor k1
h1 = rotl32(h1, 13)
h1 = h1 * 5 + &HE6546B64UI
curLength -= 4
End While
Private Shared Function rotl32(x As UInt32, r As Byte) As UInt32
Return (x << r) Or (x >> (32 - r))
End Function
k1 *= c1
Throws error Arithmetic operation resulted in an overflow.
Any suggestions how this should be implemented? I'm Not sure how to do the Get four bytes from the input into an UInt32 part if that is the problem or is it related to something else since there are some differences in bitwise operations between C# and VB.
For the reference Java implementation also exists
https://github.com/yonik/java_util/blob/master/src/util/hash/MurmurHash3.java
I'd first convert the 32-bit k1 to a 64-bit variant first, e.g:
k1_64 = CType(k1, UInt64)
for modulo-32bit calculation, do
k1_64 = (k1_64 * c1) And &HFFFFFFFFUI
finally, recast back to 32-bit
k1 = CType(k1_64 And $HFFFFFFFFUI, UInt32)
to add more performance, you might want to consider replacing the BitConverter.ToUInt call with something else.
EDIT : Here's a simpler version without additional variable (but with a 'helper constant')
Const LOW_32 as UInt32 = &HFFFFFFFFUI
' ... intervening code ...
k1 = (1L * k1 * c1) And LOW_32
' ... later on ...
h1 = (h1 * 5L + &HE6546B64UL) And LOW_32
the 1L forces the calculation within the parens to be performed as Long (Int64). The And LOW_32 pares down the number of non-zero bits to 32, and the overall result is then automatically casted to UInt32. Similar thing happens on the h1 line.
Reference: http://www.undermyhat.org/blog/2009/08/secrets-and-lies-of-type-suffixes-in-c-and-vb-net/ (scroll down to the section "Secrets of constants and type suffixes")
Unfortunately, it possible to do the equivalent of unchecked {} in VB.NET? You could use a try/catch blocked and do the shift manually if you overflow. Just be careful, putting an error handler in there will slow down the hash calculation.

VB.NET Bit manipulation: how to extract byte from short?

Given this Short (signed):
&Hxxxx
I want to:
Extract the most right &HxxFF as SByte (signed)
Extract the left &H7Fxx as Byte (unsigned)
Identify if the most left &H8xxx is positive or negative (bool result)
Extract the most right 0xxxff
myShort & 0x00FF
Extract the left 0xffxx
(myShort & 0xFF00) >> 8
Identify if the most left 0xfxxx is
positive or negative (it's a signed
short).
(myShort & 0xF000) >= 0;
Dim test As UInt16 = &HD 'a test value 1101
Dim rb As Byte 'lsb
Dim lb As Byte 'msb - 7 bits
Dim rm As UInt16 = &HFF 'lsb mask
Dim lm As UInt16 = &H7F00 'msb mask
Dim sgn As Byte = &H80 'sign mask
For x As Integer = 0 To 15 'shift the test value one bit at a time
rb = CByte(test And rm) 'get lsb
lb = CByte((test And lm) >> 8) 'get msb
Dim lbS, rbS As Boolean 'sign
'set signs
If (rb And sgn) = sgn Then rbS = True _
Else rbS = False
If (lb And sgn) = sgn Then lbS = True _
Else lbS = False 'should always be false based on mask
Console.WriteLine(String.Format("{0} {1} {2} {3} {4}",
x.ToString.PadLeft(2, " "c),
Convert.ToString(lb, 2).PadLeft(8, "0"c),
Convert.ToString(rb, 2).PadLeft(8, "0"c),
lbS.ToString, rbS.ToString))
test = test << 1
Next
inline char getLsb(short s)
{
return s & 0xff;
}
inline char getMsb(short s)
{
return (s & 0xff00) >> 8;
}
inline bool isBitSet(short s, unsigned pos)
{
return (s & (1 << pos)) > 0;
}
Uh...
value & 0x00ff
(value & 0xff00) >> 8
(value & 0xf000) >= 0
EDIT: I suppose you want the byte value and not just the upper 8 bits.
Extract the most right &HxxFF as SByte (signed)
CType(s AND &H00FF, SByte)
Extract the left &H7Fxx as Byte (unsigned)
CType((s AND &H7F00) >> 8, Byte)
Identify if the most left &H8xxx is positive or negative (bool result)
s AND &H8000 > 0
I think those work, been a while since I have worked in VB