Encrypt string in VBA, decrypt in C# - c#

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

Related

The name 'Fix' does not exist in the current context

In my project I am converting some vb.net to c# and I came to this line:
int thisdigit = Fix(countervalue / (Math.Pow(10, (numdigits - j - 1)))) - Fix(countervalue / (Math.Pow(10, (numdigits - j)))) * 10;
But I get the error:
The name 'Fix' does not exist in the current context
How do I fix this? I can't understand why Fix() wouldn't exist.
But if I used Math.Truncate() instead, well, that doesn't work because thisdigit is an int.
How could I change that?
Here is my original vb.net code:
dim dg as int
dg = Fix(value / (10 ^ (digits - j - 1))) - Fix(value / (10 ^ (digits - j))) * 10
Here is a link to what I'm trying to convert:
https://www.developerfusion.com/code/3734/aspnet-graphical-page-hit-counter/
The code works in my vb.net projects. I've run my converted code through the debugger, and the only place I can see any problem is with this line.
I came up with this, too:
double thisdigit = Math.Truncate((double)(countervalue / (10 ^ (numdigits - j - 1)))) - Math.Truncate(((double)(countervalue / (10 ^ (numdigits - j))) * 10));
I don't really understand why this is so convoluted..
The original code seems to draw a counter, one digit at a time:
dim j as Integer, dg as Integer
for j = 0 to (digits-1)
' Extract digit from value
dg = fix(value / (10^(digits - j - 1))) - fix(value / (10^(digits - j)))*10
' Add digit to the output graphic
g.drawimage(i, New rectangle(j*dgwidth, 0, dgwidth, dgheight), New rectangle(dg*dgwidth, 0, dgwidth, dgheight), GraphicsUnit.Pixel)
next j
But surely it would just be easier to do something like:
int pageCounter = 7234283;
string toDraw = pageCounter.ToString();
for(int i = 0; i < toDraw.Length; i++)
someGraphics.DrawString(toDraw.Substring(i, 1), someFont, someBrush, new PointF(i * 10.0f, 0));
Or perhaps:
int pageCounter = 7234283;
string toDraw = pageCounter.ToString();
PointF p = new PointF(0.0f, 0.0f);
foreach(char c in toDraw){
someGraphics.DrawString(c.ToString(), someFont, someBrush, p);
p.X += 10.0f;
}
With some help from Aidy in the C# Discord, I ended up with this. Very simple and clean.
//Get the number of digits to display in the output graphic
//If the countervalue is 16 then "16".ToString("D5") converts it to "00016".
//ToCharArray() turns that into an array of characters ['0', '0', '0', '1', '6'].
//We loop through that list and convert the char back to int and we get 0, 0, 0, 1 and 6.
//Thanks to #Aidy in the C# Discord for help on this
int numdigits = Convert.ToInt32(Request.QueryString["digits"]);
var digits = countervalue.ToString("D" + numdigits.ToString()).ToCharArray();
//Create an output object
Bitmap imageoutput = new Bitmap(digitwidth * digits.Length, digitheight, PixelFormat.Format24bppRgb); //should be 5*15 = 75 for digits.gif
Graphics graphic = Graphics.FromImage(imageoutput); //here is our black box
//digits.gif is 150 x 20px;
//So, if our countervalue = 16, and numdigits = 5, we want to display 00016.
for(int j = 0; j < digits.Length; j++) {
//We loop through that digits and convert the char back to int and we get 0, 0, 0, 1 and 6.
int thisdigitX = int.Parse(digits[j].ToString());
//add the digit to the output graphic
graphic.DrawImage(digitpix, new Rectangle(j * digitwidth, 0, digitwidth, digitheight), new Rectangle(thisdigitX * digitwidth, 0, digitwidth, digitheight), GraphicsUnit.Pixel);
}
However, I was also able to get the original code to work with the conversion of int and double and importing the Visual Basic assembly.
using Microsoft.VisualBasic;
int thisdigitX = Conversion.Fix(countervalue / ((int)Math.Pow(10, (double)(numdigits - j - 1)))) - ( Conversion.Fix(countervalue / ((int)Math.Pow(10,(double)(numdigits - j)))) * 10);
Here is a link to my github page where I've posted the entire working project if anyone is really interested. (not self-promoting here - just sharing; I don't care if anyone uses it or not).

C# Changing Least Significant Bit Image Algorithm

I am trying to hide a string of text into a bitmap using the LSB algorithm, which is replacing the least significant bit of the RGB Values for each pixel. So far I have loped through the pixels of the image and cleared the LSB value for each pixel. The part that I am struggling with is inserting the new LSB values that come from a string.
This is what I have done so far any pointers of where to go next would be helpful
string text = txtEncrypt.Text;
//Gets the ascii value of each character from the string
var n = ASCIIEncoding.ASCII.GetBytes(text);
Bitmap myBitmap = new Bitmap(myPictureBox.Image);
byte[] rgbBytes = new byte[0];
int R=0, G=0, B=0;
for (int i = 0; i < myBitmap.Width; i++)
{
for (int j = 0; j < myBitmap.Height; j++)
{
Color pixel = myBitmap.GetPixel(i, j);
// now, clear the least significant bit (LSB) from each pixel element
//Therefore Three bits in each pixel spare
R = pixel.R - pixel.R % 2;
G = pixel.G - pixel.G % 2;
B = pixel.B - pixel.B % 2;
// Need to insert new values
}
}
Although you can do bit manipulation using "regular" arithmetics (the kind they teach in the first grade) it is more common to use bit manipulation operators to achieve the same goal.
For example, writing R = pixel.R & ~1 is a lot more common than subtracting pixel.R % 2.
You don't need to clear the bit before setting it. To force a bit into 1 use R = pixel.R | 1. To force it into zero use the R = pixel.R & ~1 mentioned above.
To iterate bits of the "messagestored as a sequence ofN` bytes use this check:
if (message[pos / 8] & (1 << pos % 8) != 0) {
// bit at position pos is 1
} else {
// bit at position pos is 0
}
Bitwise operators make this easy to do:
set last bit to 1:
var newR = pixel.R | 0b00000001
set last bit to 0
var newR = pixel.R & 0b11111110
how this works: | merges bits like an or operator would per byte. and & merges bits like an and operator would (psuedocode):
10101000 | 0000001 = 10101001
10101001 & 1111110 = 10101000

C# version of jquery.md5.js

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.

Help converting some classic asp code to c# (.net 3.5)

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

Calculating RMS with overlapping windows

I have a 1-dimensional float array of root mean square values, each calculated with the same window length. Let's say
RMS = {0, 0.01, 0.4, ... }
Now the RMS for a larger window, which can be represented as a range of the original windows, can be calculated as the RMS of the "participating" RMS values from RMS[i] to RMS[i + len]. Here len is the length of the larger window divided by the lenght of the original windows.
I'd like to create a rolling window. I want
rollingRMS[0] = RMS from 0 to len
...
rollingRMS[n] = RMS from n to len+n
calculated as efficiently as possible. I know this isn't very hard to crack, but does anyone have ready code for this?
EDIT: I asked for sample code, so I guess it would be decent to provide some. The following is based on pierr's answer and is written in C#. It's a bit different from my original question as I realized it would be nice to have the resulting array to have the same size as the original and to have the windows end at each element.
// The RMS data to be analysed
float[] RMS = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// The resulting rolling RMS values
float[] rollingRMS = new float[RMS.Length];
// Window lenght
int len = 3;
// Calculate: rollingRMS will hold root mean square from windows which end at
// each respective sample in the RMS array. For the first len samples the input
// will be treated as zero-padded
for (int i = 0; i < RMS.Length; i++)
{
if (i == 0)
rollingRMS[i] = (float)Math.Sqrt((RMS[i] * RMS[i] / len));
else if (i < len)
rollingRMS[i] = (float)Math.Sqrt(
( RMS[i] * RMS[i] +
len * (rollingRMS[i - 1] * rollingRMS[i - 1])
) / len);
else
rollingRMS[i] = (float)Math.Sqrt(
( len * (rollingRMS[i - 1] * rollingRMS[i - 1]) +
RMS[i] * RMS[i] -
RMS[i - len] * RMS[i - len]
) / len);
}
I am not sure that I have understood your problem correctly. But let me have a try.
a=[1,2,3,4,5,6,7,8,9,10]
LEN = 3
SquareOfRollingRMS[0] = (a[0]^2 + a[1]^2 + a[2]^2 ) / LEN
SquareOfRollingRMS[1] = ( a[1]^2 + a[2]^2 + a[3]^2 ) / LEN
It's not difficult to notice that:
SquareOfRollingRMS[i] = RollingRMS[i-1] * LEN - a[i-1]^2 + a[i+LEN-1]^2
RollingRMS[i] = SqurefOfRollingRMS[i]^(1/2)
Doing it this way ,you are avoiding recaculating the overlap windows.
EDIT:
You can save some divide and multiply operation by moving LEN to the left side of the equations. This might speed up a lot as dividing is usually relatively slow.
LEN_by_SquareOfRollingRMS[0] = (a[0]^2 + a[1]^2 + a[2]^2)
LEN_by_SquareOfRollingRMS[i] = LEN_by_RollingRMS[i-1] - a[i-1]^2 + a[i+LEN-1]^2

Categories

Resources