I have this block of code in a .asp file that I am struggling to convert to c#... can anyone help me?
Function EncodeCPT(ByVal sPinCode, ByVal iOfferCode, ByVal sShortKey, ByVal sLongKey)
Dim vob(2), encodeModulo(256), decodeX, ocode
decodeX = " abcdefghijklmnopqrstuvwxyz0123456789!$%()*+,-.#;<=>?[]^_{|}~"
if len(iOfferCode) = 5 then
ocode = iOfferCode Mod 10000
else
ocode = iOfferCode
end if
vob(1) = ocode Mod 100
vob(0) = Int((ocode-vob(1)) / 100)
For i = 1 To 256
encodeModulo(i) = 0
Next
For i = 0 To 60
encodeModulo(asc(mid(decodeX, i + 1, 1))) = i
Next
'append offer code to key
sPinCode = lcase(sPinCode) & iOfferCode
If Len(sPinCode) < 20 Then
sPinCode = Left(sPinCode & " couponsincproduction", 20)
End If
'encode
Dim i, q, j, k, sCPT, s1, s2, s3
i = 0
q = 0
j = Len(sPinCode)
k = Len(sShortKey)
sCPT = ""
For i = 1 To j
s1 = encodeModulo(asc( mid(sPinCode, i, 1)) )
s2 = 2 * encodeModulo( asc( mid(sShortKey, 1 + ((i - 1) Mod k), 1) ) )
s3 = vob(i Mod 2)
q = (q + s1 + s2 + s3) Mod 61
sCPT = sCPT & mid(sLongKey, q + 1, 1)
Next
EncodeCPT = sCPT
End Function
What you have here seems to be pretty standard VBScript code.
Perhaps you could look at some C# tutorial to get the basics or maybe go for VB.NET instead of C#.
The syntax is pretty much the same as VBScript, but remember, the .NET framework is object oriented so some feature or functions are not implemented the same way.
For example, if you want to get the length of a string, you would be using myString.Length instead of Len(myString).
Here are a few C# and VB.NET tutorials for you to look at.
http://www.csharp-station.com/Tutorial.aspx
http://www.csharpkey.com/csharp/Lesson01.htm
http://www.programmersheaven.com/2/VB-NET-School
http://www.homeandlearn.co.uk/net/vbnet.html
Related
I try to convert the awesome script jquery.md5.js to C# for my own purpose.
But I can't figure it out these two methods:
function rstr2binl(input) {
var i,
output = [];
output[(input.length >> 2) - 1] = undefined;
for (i = 0; i < output.length; i += 1) {
output[i] = 0;
}
for (i = 0; i < input.length * 8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
}
return output;
}
I don't understand very well what is he doing with "output"...
function rstr_hmac_md5(key, data) {
var i,
bkey = rstr2binl(key),
ipad = [],
opad = [],
hash;
ipad[15] = opad[15] = undefined;
if (bkey.length > 16) {
bkey = binl_md5(bkey, key.length * 8);
}
for (i = 0; i < 16; i += 1) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
}
"ipad[15] = opad[15] = undefined;"
I can't do that in C#...
Thanks beforehand!
P.S.: Strange behavior, I can't say Hello, its always deleted...
I won't translate all code to C#, but explain a few points:
var output = [];
output[(input.length >> 2) - 1] = undefined;
This is one way to set the array length in javascript. Basically you say thet elements [0 ... (input.length >> 2) - 1] are undefined - which can be compared to null in C#. As you are calculating some values I would avoid nullable types and simply initialize the array to 0 - So the C# equivalent would be:
int[] output = new int[(input.Length >> 2)];
The next thing is that instead of normal division right bit shifts are used. If you compare the C# and JavaScript descriptions of the operators, you'll see they're doing the same thing. Therefore, no conversion is required but you could simply write new int[input.Length / 4].
Please note that in the current version of the script the array initialization is done like this:
var output = Array(input.length >> 2);
And as a final note: unless you are doing this for self-education, take an existing C# MD5 implementation, there should be plenty avaliable. This will help you to avoid errors and performance issues.
I am trying to create a small software that does the Affine Cipher, which means that K1 and the amount of letters in the alphabet (using m for this number) must be coprime, that is gcd(k1, m) == 1.
Basically it's like this:
I have a plaintext: hey
I have K1: 7
I have K2: 5
Plaintext in numerical format is:
8 5 25
8 - from h (the position in the alphabet) and **
5 25** goes the same for e and y
Encrypted: 7 13 18
Which is the formula:
k1 * 8 + k2 mod 27 = 7
k1 * 5 + k2 mod 27 = 13
k1 * 25 + k2 mod 27 = 18
I have a function that crypts this but I don't know how to decrypt.
For example I have 7 for h. I want to get the number 8 back again, knowing 7, k1 and k2.
Do you guys have any ideas ?
Some function where you input k1, k2, result (7 for example, for h), and it gives me back 8, but I really don't know how to reverse this.
The function for encryption is this:
public List<int> get_crypted_char(string[] strr)
{
List<int> l = new List<int>();
int i;
for (i = 0; i < strr.Length; i++)
{
int ch = int.Parse(strr[i]);
int numberback = k1 * ch + 5;
numberback = (numberback % 27);
l.Add(numberback);
}
return l;
}
Where: string[] strr is a string that contains the plaintext.
Function example:
get_crypted_char({"e","c","b"})
The result would be a list like this {"5","3","2"}
UPDATE:
Here is a link from wikipedia about this encryption, and also decryption, but ... I don't really understand "how to"
http://en.wikipedia.org/wiki/Affine_cipher
It is not possible (in general case, for affine cipher, see update below). That's why module operation is so frequently used in security algorithms - it is not reversible. But, why don't we try?
result = (k1 * input + k2) % 27 (*1)
Let's take the first letter:
result = (7 * 8 + 5) % 27 = 7
That's cool. Now, because we said, that:
result = (k1 * input + k2) % 27
the following is also true:
k1 * input + k2 = 27 * div + result (*2)
where
div = (k1 * input + k2) / 27 (integral division)
It is quite obvious (if a % b = c, then a = b*n + c, where n is the result of integer division a/b).
You know the values of k1 (which is 7), k2 (5) and result (7). So, when we put these values to (*2), we get the following:
7 * input + 5 = 27 * div + 7 //You need to solve this
As you can see, it is impossible to solve this, because you would need to know also the result of the integral division - translating this to your function's language, you would need the value of
numberback / 27
which is unknown. So answer is: you cannot reverse your function's results, using only output it returns.
** UPDATE **
I focused too much on the question's title, so the answer above is not fully correct. I decided not to remove it, however, but write an update.
So, the answer for your particular case (affine cipher) is: YES, you can reverse it.
As you can see on the wiki, decryption function for affine cipher for the following encrytption function:
E(input) = a*input + b mod m
is defined as:
D(enc) = a^-1 * (enc - b) mod m
The only possible problem here can be computation of a^-1, which is modular multiplicative inverse.
Read about it on wiki, I will provide only example.
In your case a = k1 = 7 and m = 27. So:
7^-1 = p mod 27
7p = 1 mod 27
In other words, you need to find p, which satisfies the following: 7p % 27 = 1.
p can be computed using extended euclidean algorithm and I computed it to be 4 (4 * 7 = 28, 28 % 27 = 1).
Check, if can decipher your output now:
E(8) = 7*8 + 5 mod 27 = 7
D(7) = 4 * (7 - 5) mod 27 = 8
Hope that helps :)
Please note that the other answers do not take into account the the algorithm at hand is the Affine Cipher, ie there are some conditions at hand, the most important one the coprime status of k1 and m.
In your case it would be:
m = 27; // letters in your alphabet
k1 = 7; // coprime with m
k2 = 5; // no reqs here, just that a value above 27 is the same as mod 27 of that value
int Encrypt(int letter) {
return ((letter * k1) + k2) % m;
}
int Decrypt(int letter) {
return ((letter - k2) * modInverse(k1, m)) % m;
}
Tuple<int, Tuple<int, int>> extendedEuclid(int a, int b)
{
int x = 1, y = 0;
int xLast = 0, yLast = 1;
int q, r, m, n;
while (a != 0)
{
q = b / a;
r = b % a;
m = xLast - q * x;
n = yLast - q * y;
xLast = x; yLast = y;
x = m; y = n;
b = a; a = r;
}
return new Tuple<int, Tuple<int, int>>(b, new Tuple<int, int>(xLast, yLast));
}
int modInverse(int a, int m)
{
return (extendedEuclid(a, m).Item2.Item1 + m) % m;
}
ModInverse implementation taken from http://comeoncodeon.wordpress.com/2011/10/09/modular-multiplicative-inverse/.
I have created a program that will tell the modular inverse of something. I will let you use it. It is posted below.
# Cryptomath Module
def gcf(a, b):
# Return the GCD of a & b using Euclid's Algorithm
while a != 0:
a, b = b % a, a
return b
def findModInverse(a, m):
# Return the modular inverse of a % m, which is
# the number x such that a*x % m = 1
if gcf(a, m) != 1:
return None # No mode inverese if a & m aren't relatively prime
# Calculate using the Extended Euclidean Algorithm:
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3 # // is the integer division operator
v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q *
v3), v1, v2, v3
return u1 % m
Note: The modular inverse is found using the extended euclidean algorithm. Here is the Wikipedia entry for it: http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
Note: This needs to be imported as a module to be used. Hope it helps.
I'm trying to convert some complex C# bitshifting code into javascript (node), but I'm having issues with this kind of conversion as an example:
var d = false;
var k = 61;
var dd = 103;
uint r = 2924539136;
r |= unchecked((byte)(d ? (k + dd) : (k - dd)));
Console.WriteLine("result: " + r); // 2924539350
Is there some way to replicate the (byte) casting in javascript to where it computes the value I'm looking for, I have this so far, but it just results in -42.
r |= (d ? (k + dd): (k - dd));
var d = false;
var k = 61;
var dd = 103;
r = 2924539136;
b = (d ? (k + dd) : (k - dd))
x = (r | (b & 0xFF)) >>> 0
returns
x = 2924539350
The trick is to use &0xFF to mask all but lower 8 bits in b and >>>0 to convert a signed 32-bit number to unsigned.
How to convert a "big" Hex number (in string format):
EC851A69B8ACD843164E10CFF70CF9E86DC2FEE3CF6F374B43C854E3342A2F1AC3E30C741CC41E679DF6D07CE6FA3A66083EC9B8C8BF3AF05D8BDBB0AA6CB3EF8C5BAA2A5E531BA9E28592F99E0FE4F95169A6C63F635D0197E325C5EC76219B907E4EBDCD401FB1986E4E3CA661FF73E7E2B8FD9988E753B7042B2BBCA76679
to a decimal number (in string format):
166089946137986168535368849184301740204613753693156360462575217560130904921953976324839782808018277000296027060873747803291797869684516494894741699267674246881622658654267131250470956587908385447044319923040838072975636163137212887824248575510341104029461758594855159174329892125993844566497176102668262139513
without using BigInteger Class (as my application should support machines without .NET Framework 4)?
Here's a quick-and-dirty implementation that can work with arbitrarily-large numbers. The aim of this implementation is simplicity, not performance; thus, it should be optimized drastically if it's to be used in a production scenario.
Edit: Simplified further per Dan Byström's implementation of the inverse decimal-to-hex conversion:
static string HexToDecimal(string hex)
{
List<int> dec = new List<int> { 0 }; // decimal result
foreach (char c in hex)
{
int carry = Convert.ToInt32(c.ToString(), 16);
// initially holds decimal value of current hex digit;
// subsequently holds carry-over for multiplication
for (int i = 0; i < dec.Count; ++i)
{
int val = dec[i] * 16 + carry;
dec[i] = val % 10;
carry = val / 10;
}
while (carry > 0)
{
dec.Add(carry % 10);
carry /= 10;
}
}
var chars = dec.Select(d => (char)('0' + d));
var cArr = chars.Reverse().ToArray();
return new string(cArr);
}
I just translated Douglas' code into VBA
Function HexToDecimal(ByVal sHex As String) As String
Dim dec() As Long
ReDim dec(0 To 0) As Long
Dim lCharLoop As Long
For lCharLoop = 1 To Len(sHex)
Dim char As String * 1
char = Mid$(sHex, lCharLoop, 1)
Dim carry As Long
carry = Val("&h" & char)
Dim i As Long
For i = 0 To UBound(dec)
Dim lVal As Long
lVal = dec(i) * 16 + carry
dec(i) = lVal Mod 10
carry = lVal \ 10
Next i
While (carry > 0)
ReDim Preserve dec(0 To UBound(dec) + 1) As Long
dec(UBound(dec)) = carry Mod 10
carry = carry \ 10
Wend
Next
For lCharLoop = UBound(dec) To LBound(dec) Step -1
Dim sDecimal As String
sDecimal = sDecimal & Chr$(48 + dec(lCharLoop))
Next
HexToDecimal = sDecimal
End Function
Private Sub TestHexToDecimal()
Debug.Assert HexToDecimal("F") = "15"
Debug.Assert HexToDecimal("4") = CStr(Val("&H4"))
Debug.Assert HexToDecimal("10") = CStr(Val("&H10"))
Debug.Assert HexToDecimal("20") = CStr(Val("&H20"))
Debug.Assert HexToDecimal("30") = CStr(Val("&H30"))
Debug.Assert HexToDecimal("40") = CStr(Val("&H40"))
Debug.Assert HexToDecimal("44") = CStr(Val("&H44"))
Debug.Assert HexToDecimal("FF") = "255"
Debug.Assert HexToDecimal("FFF") = "4095"
Debug.Assert HexToDecimal("443") = CStr(Val("&H443"))
Debug.Assert HexToDecimal("443C1") = "279489"
Debug.Assert HexToDecimal("443C1CE20DFD592FB374D829B894BBE5") = "90699627342249584016268008583970733029"
Debug.Assert HexToDecimal("EC851A69B8ACD843164E10CFF70CF9E86DC2FEE3CF6F374B43C854E3342A2F1AC3E30" & _
"C741CC41E679DF6D07CE6FA3A66083EC9B8C8BF3AF05D8BDBB0AA6CB3EF8C5BAA2A5" & _
"E531BA9E28592F99E0FE4F95169A6C63F635D0197E325C5EC76219B907E4EBDCD401FB1" & _
"986E4E3CA661FF73E7E2B8FD9988E753B7042B2BBCA76679") = _
"1660899461379861685353688491843017402046137536931563604625752175601309049219" & _
"5397632483978280801827700029602706087374780329179786968451649489474169926767" & _
"4246881622658654267131250470956587908385447044319923040838072975636163137212" & _
"8878242485755103411040294617585948551591743298921259938445664971761026682621" & _
"39513"
End Sub
Also a benchmark at statman.info Hexadecimal Conversion for large numbers
You can use the IntX library as it should work with .Net 2.0 and up. From the description on the page in regards to BigInteger:
So internally System.Numerics.BigInteger seems to use standard
arbitrary arithmetic algorithms and I am not worrying about IntX
library since, due to its use of FHT, it can be times faster for
really big integers.
The license is pretty liberal but worth reading first just to make sure it's okay.
I've not used this library but from a cursory glance at the source code this should be all you need to do
string dec = new IntX(myHex, 16).ToString();
If you don't want to compile the code yourself, you can install it via Nuget.
An easy way would be to use a big number library that supports your version of .NET. I'd recommend GnuMpDotNet, which uses the excellent GMP library. By default it targets .NET 3.5, but you can change that to .NET 2.0 without breaking anything (just remove the references and using statement that refer to new things), as it doesn't use anything from .NET 3.5. Here is an example using GnuMpDotNet:
BigInt e = new BigInt(hexString, 16);
string decimalStr = e.ToString();
Look at my answer here: https://stackoverflow.com/a/18231860/2521214
worth looking
string based conversions (limited by free memory only)
dec->hex and hex<-dec included
no bigint/bigreal lib used
supporting fixed point string formats (no exponents)
I just translated Douglas code to PHP:
function BigNumberHexToDecimal($hex)
{
$dec = array(0);
$hexLen = strlen($hex);
for($h=0;$h<$hexLen;++$h)
{
$carry = hexdec($hex[$h]);
for ($i = 0; $i < count($dec); ++$i)
{
$val = $dec[$i] * 16 + $carry;
$dec[$i] = $val % 10;
$carry = (int)($val / 10);
}
while ($carry > 0)
{
$dec[] = $carry % 10;
$carry = (int)($carry / 10);
}
}
return join("", array_reverse($dec));
}
I just translated Douglas code to JAVA:
public static String HexToDec(String hex) {
List<Integer> dec = new ArrayList<Integer>();
for (int k = 0; k < hex.length(); k++) {
String c = hex.charAt(k) + "";
int carry = Integer.parseInt(c, 16);
for (int i = 0; i < dec.size(); ++i) {
int val = dec.get(i) * 16 + carry;
dec.set(i, val % 10);
carry = val / 10;
}
while (carry > 0) {
dec.add(carry % 10);
carry /= 10;
}
}
int[] out = new int[dec.size()];
for (int i = 0; i < dec.size(); i++) {
out[i] = dec.get(i).intValue();
}
return arrayToDecString(reverseArray(out));
}
public static String arrayToDecString(int[] data) {
String str = "";
for (int i = 0; i < data.length; i++) {
str += data[i] + "";
}
return str;
}
public static int[] reverseArray(int[] data) {
for (int i = 0; i < data.length / 2; i++) {
int temp = data[i];
data[i] = data[data.length - i - 1];
data[data.length - i - 1] = temp;
}
return data;
}
I just translated Douglas code to Delphi/Pascal:
function HexToDecimal(const Hex: string): string;
var
dec: TList;
I: Integer;
carry: Cardinal;
c: Char;
val: Integer;
begin
Result := '';
dec := TList.Create;
try
dec.Add(Pointer(0)); // decimal result
for c in Hex do begin
carry := StrToInt('$' + c); // initially holds decimal value of current hex digit;
// subsequently holds carry-over for multiplication
for I := 0 to dec.Count -1 do begin
val := Integer(dec[I]) * 16 + carry;
dec[I] := Pointer(Integer(val mod 10));
carry := val div 10;
end;
while carry > 0 do begin
dec.Add(Pointer(Integer(carry mod 10)));
carry := carry div 10;
end;
end;
for I := 0 to dec.Count -1 do begin
val := Integer(dec[I]);
Result := IntToStr(val) + Result;
end;
finally
dec.Free;
end;
end;
procedure Test;
var
S: string;
begin
S := HexToDecimal('FF'); // 255
S := HexToDecimal('FFF'); // 4095
S := HexToDecimal('443C1'); // 279489
S := HexToDecimal('443C1CE20DFD592FB374D829B894BBE5'); // "90699627342249584016268008583970733029"
S := 'EC851A69B8ACD843164E10CFF70CF9E86DC2FEE3CF6F374B43C854E3342A2F1AC3E30' +
'C741CC41E679DF6D07CE6FA3A66083EC9B8C8BF3AF05D8BDBB0AA6CB3EF8C5BAA2A5' +
'E531BA9E28592F99E0FE4F95169A6C63F635D0197E325C5EC76219B907E4EBDCD401FB1' +
'986E4E3CA661FF73E7E2B8FD9988E753B7042B2BBCA76679';
S := HexToDecimal(S); // "166089946137986168535368849184301740204613753693156360462575217560130904921953976324839782808018277000296027060873747803291797869684516494894741699267674246881622658654267131250470956587908385447044319923040838072975636163137212887824248575510341104029461758594855159174329892125993844566497176102668262139513"
end;
Translated Douglas code to Qt:
QByteArray convertHexToDecimal(const QByteArray &hex)
{
QList<int> dec;
for (int i = 0; i < hex.count(); i++) {
int carry = hex.mid(i, 1).toInt(nullptr, 16);
for (int j = 0; j < dec.count(); ++j) {
int val = dec[j] * 16 + carry;
dec[j] = val % 10;
carry = val / 10;
}
while (carry > 0) {
dec.append(carry % 10);
carry /= 10;
}
}
QByteArray chars;
foreach (int d, dec) {
chars.prepend((char)('0' + d));
}
return chars;
}
I need to encrypt authentication information (strings) in VBA and then decrypt them correctly in C# (a WCF service).
We're not overly concerned about the type or strength of encryption used, just that the decryption must correctly produce the original text.
Can anyone advise me how to go about this, or point me at blocks of code to implement both in VBA & in C# to achieve what I need to do?
Many Thanks in advance
Ok, I am positive you can use this.
I am using it for VBA, however, it is simple enough to use in vb.net as is, and one step away from being converting to C#.
I got the code and explanation here:
link to who built the function
I just use it for VBA. I'v used tons of VBA functions in vb.net and I've converted enough vb.net to c# to know this could be used in c#.
Function RunRC4(sMessage, strKey)
Dim kLen, x, y, i, j, temp
Dim s(256), k(256)
'Init keystream'
klen = Len(strKey)
For i = 0 To 255
s(i) = i
k(i) = Asc(Mid(strKey, (i Mod klen) + 1, 1))
Next
j = 0
For i = 0 To 255
j = (j + k(i) + s(i)) Mod 255
temp = s(i)
s(i) = s(j)
s(j) = temp
Next
'Drop n bytes from keystream'
x = 0
y = 0
For i = 1 To 3072
x = (x + 1) Mod 255
y = (y + s(x)) Mod 255
temp = s(x)
s(x) = s(y)
s(y) = temp
Next
'Encode/Decode'
For i = 1 To Len(sMessage)
x = (x + 1) Mod 255
y = (y + s(x)) Mod 255
temp = s(x)
s(x) = s(y)
s(y) = temp
RunRC4 = RunRC4 & Chr(s((s(x) + s(y)) Mod 255) Xor Asc(Mid(sMessage, i, 1)))
Next
End Function