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.
Related
I am trying to get this snippet to vb but keep getting errors in the ide
var header = new byte[8];
int index = 0;
var magic_signature = ((uint)header[index++] << 0) | ((uint)header[index++] << 8) | ((uint)header[index++] << 16) | ((uint)header[index++] << 24);
I tried an online coverter and got this (which produces errors)
Dim magic_signature = (CUInt(header(Math.Max(Threading.Interlocked.Increment(index), index - 1))) << 0) Or (CUInt(header(Math.Max(Threading.Interlocked.Increment(index), index - 1))) << 8) Or (CUInt(header(Math.Max(Threading.Interlocked.Increment(index), index - 1))) << 16) Or (CUInt(header(Math.Max(Threading.Interlocked.Increment(index), index - 1))) << 24)
The header variable is filled after declaration.
Could someone help me convert the above to vb.net?
EDIT:
Populating header via reading a stream
Dim header = New Byte(8) {}
If stream.Read(header, 0, 8) < 8 Then
Throw New ApplicationException("Incomplete data.")
End If
As Mike_OBrien has pointed out, VB doesn't have a built-in ++ - but we can fake one easily enough:
Function PostIncr(ByRef x As Integer) As Integer
' PostIncr(i) works like i++
Dim x0 As Integer = x : x += 1 : Return x0
End Function
After that, conversion is straightforward:
Dim header(7) As Byte
' Make believe this is a stream.Read
Array.Copy({CByte(1), CByte(2), CByte(3), CByte(4)},
header, 4)
Dim index As Integer = 0
Dim magic_signature = CUInt(header(PostIncr(index))) << 0 Or
CUInt(header(PostIncr(index))) << 8 Or
CUInt(header(PostIncr(index))) << 16 Or
CUInt(header(PostIncr(index))) << 24
And for fun:
Function PreIncr(ByRef x As Integer) As Integer
' PreIncr(i) works like ++i
x += 1 : Return x
End Function
I believe David Wilson is on the right path but as rskar pointed out the Index + 1 portion does not produce the same results as index++ would in c#. The easiest way to get the behavior from c# would be to break the single command into multiple commands and store the results in temp variables, incrementing Index between each step and then evaluating the temp variables at the end. This would result in a lot more code however.
Ex:
Dim temp1 = (CUInt(header(Index)) << 0)
Index += 1
Dim temp2 = (CUInt(header(Index)) << 8)
Index += 1
Dim temp3 = (CUInt(header(Index)) << 16)
Index += 1
Dim magic_signature As UInteger = temp1 Or temp2 Or temp3 Or (CUInt(header(Index)) << 24)
Unfortunately to my knowledge there isn't anything in vb.net that behaves the same as the ++ operator in c#.
I want to add a text box where a user can input a number. No matter how large or small the number, it needs to be stored as a double. Then with a click button, the hex equivalent will be displayed in a second text box. Bonus points if you can show me how to take the 16 byte hex and change it to 4 variables with 4 bytes each.
For example, user enters 1234.56 in textbox1. Clicks button 1, and textbox2 displays the hex equivilent "40934A3D70A3D70A" Then take that string, and extract to 4 different 4-byte strings so str1=1093, str2=4A3D, str3=70a3, str4=d70A.
Are you looking for BitConverter? C# implementation:
double source = 1234.56;
// 40934A3D70A3D70A
string result = string.Concat(BitConverter
.GetBytes(source)
.Reverse()
.Select(b => b.ToString("X2")));
Having got result, extract its parts with Substring:
string str1 = result.Substring(0, 4);
string str2 = result.Substring(4, 4);
string str3 = result.Substring(8, 4);
string str4 = result.Substring(12, 4);
If you are looking for a C# implementation, try this:
static void Main(string[] args)
{
var number = 1234.56;
string hex = DoubleToHex(number);
string part1 = hex.Substring(0, 4);
string part2 = hex.Substring(4, 4);
string part3 = hex.Substring(8, 4);
string part4 = hex.Substring(12, 4);
}
internal static string DoubleToHex(double value)
{
var b = BitConverter.GetBytes(value).Reverse();
string result = string.Join(string.Empty, b.Select(i => i.ToString("X2")).ToArray());
return result;
}
This is the most efficient answer you're going to get:
unsafe static void Main()
{
var value = 1234.56;
var pLong = (long*)&value;
var fullString = (*pLong).ToString("X");
var pShort = (short*)pLong;
short value0 = *pShort, value1 = *(pShort + 1), value2 = *(pShort + 2),
value3 = *(pShort + 3);
string s0 = value0.ToString("X"), s1 = value1.ToString("X"), s2 = value2.ToString("X"),
s3 = value3.ToString("X");
Debug.Print(fullString);
Debug.Print(s0);
Debug.Print(s1);
Debug.Print(s2);
Debug.Print(s3);
}
Output:
40934A3D70A3D70A
D70A
70A3
4A3D
4093
Translation of Dmitry Bychenko answer to VB.NET:
Imports SplitValue = System.Tuple(Of String, String, String, String)
Module Module1
Function DoubleToByteArray(ByVal AValue As Double) As Byte()
Return BitConverter.GetBytes(AValue).Reverse().ToArray()
End Function
Function SplitByteArray(ByRef AValue As Byte()) As SplitValue
Dim StringValue As String = String.Join("", From AByte In AValue Select AByte.ToString("X2"))
Return New SplitValue(StringValue.Substring(0, 4), StringValue.Substring(4, 4), StringValue.Substring(8, 4), StringValue.Substring(12, 4))
End Function
Sub Main()
Dim Result As SplitValue
Result = SplitByteArray(DoubleToByteArray(1234.56))
Console.WriteLine(Result)
Console.ReadLine()
End Sub
End Module
Output:
(4093, 4A3D, 70A3, D70A)
try it: DoubleToHex
//dashseparator 0 /2/4
public string DoubleToHex(double d, bool reverse = false, int dashSeparator = 0)
{
byte[] bytes = BitConverter.GetBytes(d);
if (reverse) bytes = bytes.Reverse().ToArray();
var hex = BitConverter.ToString(bytes);
var hex4 = "";
if (dashSeparator == 2) return hex;
if (dashSeparator == 4)
{
hex = hex.Replace("-", "");
hex = Regex.Replace(hex, ".{4}", "$0-").TrimEnd('-');
return hex;
}
return hex.Replace("-", "");
}
sample Output:
Double: 1234.56
Hex: 0AD7A3703D4A9340
Hex in Reverse order: 40934A3D70A3D70A
Hex in Reverse order separate by 2 digits: 40-93-4A-3D-70-A3-D7-0A
Hex in Reverse order separate by 4 digits: 4093-4A3D-70A3-D70A
you can :
-control the generated Hex to be displayed in order/ reverse order.
-Add dash separator by 0 (no separator) / 2 /4 digits
Edit:
Vb.Net Version
Converting Code to Vb.Net
'dashseparator 0 /2/4
Public Function DoubleToHex(d As Double, Optional reverse As Boolean = False, Optional dashseparator As Integer = 0) As String
Dim bytes As Byte() = BitConverter.GetBytes(d)
If reverse Then
Array.Reverse(bytes)
End If
Dim hex = BitConverter.ToString(bytes)
Dim hex4 = ""
If dashseparator = 2 Then
Return hex
End If
If dashseparator = 4 Then
hex = hex.Replace("-", "")
hex = Regex.Replace(hex, ".{4}", "$0-").TrimEnd("-"C)
Return hex
End If
Return hex.Replace("-", "")
End Function
I have read through the answers here https://stackoverflow.com/a/14332574/44080
I've also tried to produce equivalent VB.net code:
Option Strict ON
Public Function ParseHex(hexString As String) As Byte()
If (hexString.Length And 1) <> 0 Then
Throw New ArgumentException("Input must have even number of characters")
End If
Dim length As Integer = hexString.Length \ 2
Dim ret(length - 1) As Byte
Dim i As Integer = 0
Dim j As Integer = 0
Do While i < length
Dim high As Integer = ParseNybble(hexString.Chars(j))
j += 1
Dim low As Integer = ParseNybble(hexString.Chars(j))
j += 1
ret(i) = CByte((high << 4) Or low)
i += 1
Loop
Return ret
End Function
Private Function ParseNybble(c As Char) As Integer
If c >= "0"C AndAlso c <= "9"C Then
Return c - "0"C
End If
c = ChrW(c And Not &H20)
If c >= "A"C AndAlso c <= "F"C Then
Return c - ("A"C - 10)
End If
Throw New ArgumentException("Invalid nybble: " & c)
End Function
Can we remove the compile errors in ParseNybble without introducing data conversions?
Return c - "0"c Operator '-' is not defined for types 'Char' and 'Char'
c = ChrW(c And Not &H20) Operator 'And' is not defined for types 'Char' and 'Integer'
As it stands, no.
However, you could change ParseNybble to take an integer and pass AscW(hexString.Chars(j)) to it, so that the data conversion takes place outside of ParseNybble.
This solution is much much faster than all the alternative i have tried. And it avoids any ParseNybble lookup.
Function hex2byte(s As String) As Byte()
Dim l = s.Length \ 2
Dim hi, lo As Integer
Dim b(l - 1) As Byte
For i = 0 To l - 1
hi = AscW(s(i + i))
lo = AscW(s(i + i + 1))
hi = (hi And 15) + ((hi And 64) >> 6) * 9
lo = (lo And 15) + ((lo And 64) >> 6) * 9
b(i) = CByte((hi << 4) Or lo)
Next
Return b
End Function
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.
How would I go on splitting a string into pairs of letter in VB?
for example: abcdefgh
split into: ab cd ef gh
I'll throw my hat in the ring:
Dim test As String = "abcdefgh"
Dim results As New List(Of String)
For i As Integer = 0 To test.Length - 1 Step 2
If i + 1 < test.Length Then
results.Add(test.Substring(i, 2))
Else
results.Add(test.Substring(i))
End If
Next
MessageBox.Show(String.Join(" ", results.ToArray))
The following allows for odd length strings. If the string is zero-length, I'm not sure what you'd want to do, you'll want to address that case.
Dim src As String = "abcdef"
Dim size As Integer
If src.Length > 0 Then
If src.Length Mod 2 = 0 Then
size = (src.Length / 2) - 1
Else
size = ((src.Length + 1) / 2) - 1
End If
Dim result(size) As String
For i = 0 To src.Length - 1 Step 2
If i = src.Length - 1 Then
result(i / 2) = src.Substring(i, 1)
Else
result(i / 2) = src.Substring(i, 2)
End If
Next
End If
In C# you would do like this:
Dictionary<String, String> Split(String input)
{
if (input.Count % 2 == 0)
{
Dictionary<string, string> Pairs = new Dictionary( );
for (int L = 0, R = 1; L < input.Count && R <= input.Count; ++L, ++R)
{
Char
Left = input[L],
Right = input[R];
Pairs.Add(
Left.ToString(),
Right.ToString());
}
}
else
{
throw new NotEvenException( );
}
return Pairs( );
}
void Main()
{
var Pairs = Split("ABCDEFGH");
foreach(string Key in Split("ABCDEFGH"))
{
Console.Write("{0}{1}\n", Key, Pairs[Key]);
}
}
/*
Output:
AB
CD
EF
GH
*/
Now, I know what you think: This isn't what I want! But I say: It is actually, at least partly.
Since I presume you're working in VB.net, the basic structure of what you want performed is outlined in the short snippet above.
For example: The method Count (of the object String) exists in both C# and in VB.
Hope it helps a bit at least!