Solved

How do I convert old vb code to C# ?

Posted on 2009-07-07
11
388 Views
Last Modified: 2012-05-07
I've recently started a job where they use a simple VB encryption algorithm and I program in C# (something they wish to eventually switch everything to).  I'm having some trouble converting the VB code into useable c# code and was hoping you could help.  Thanks!
// The original code I'm trying to translate

  Public Function SimpleCrypt( _

           ByVal Text As String) As String

        ' Encrypts/decrypts the passed string using 

        ' a simple ASCII value-swapping algorithm

        Dim strTempChar As String, i As Integer

        For i = 1 To Len(Text)

            If Asc(Mid$(Text, i, 1)) < 128 Then

                strTempChar = _

          CType(Asc(Mid$(Text, i, 1)) + 128, String)

            ElseIf Asc(Mid$(Text, i, 1)) > 128 Then

                strTempChar = _

          CType(Asc(Mid$(Text, i, 1)) - 128, String)

            End If

            Mid$(Text, i, 1) = _

                Chr(CType(strTempChar, Integer))

        Next i

        Return Text

    End Function
 

//My failed attempt at translation

  public string SimpleCrypt(string Text)

  {

		// Encrypts/decrypts the passed string using 

		// a simple ASCII value-swapping algorithm

		string strTempChar = null;

		int i;

		for (i = 1; i <= Text.Length; i++)

		{
 

            if (Convert.ToInt16(Encoding.ASCII.GetBytes(Text.Substring(i,1))) < 128);

            if (Convert.ToInt16(Text.Substring(i - 1, 1)) < 128)

			{

                strTempChar = Convert.ToString(Convert.ToInt16(Text.Substring(i - 1, 1)) + 128);

			}

            else if (Convert.ToInt16(Text.Substring(i - 1, 1)) > 128)

			{

                strTempChar = Convert.ToString(Convert.ToInt16(Text.Substring(i - 1, 1)) - 128);

			}

			Text = Text.Remove(i - 1, 1).Insert(i - 1, ((char)(Convert.ToInt16(strTempChar))).ToString());

		}

		return Text;

	}

Open in new window

0
Comment
Question by:megatherian
  • 6
  • 4
11 Comments
 
LVL 21

Expert Comment

by:Tapan Pattanaik
ID: 24794596
hi megatherian,

                       Check these links, which able to solve your problem.

Convert VB.NET to C#:
(Simply paste in your VB.NET code below, and this free utility will automatically convert it to its equivalent in C#)

http://www.developerfusion.com/tools/convert/vb-to-csharp/

Code Translation for .NET (C#<->VB.NET):

http://www.carlosag.net/Tools/CodeTranslator/

http://vbconversions.net/
0
 

Author Comment

by:megatherian
ID: 24794664
I've tried those converters and that's partially how I came up with my non-working version.  None of them seem to be converting it correctly which is why I need a little more help.  Thanks though.
0
 
LVL 20

Expert Comment

by:alainbryden
ID: 24795010
The translation attempt looks pretty decent. Can you note where it's producing errors, or is it simply not giving the same results as the other algorithm?

--
Alain
0
 

Author Comment

by:megatherian
ID: 24795324
ok, the original VB both encrypts and decrypts text.  Using the following code I've gotten it to convert read:

test as ôåóô

but when I put in:
ôåóô it reads it as }}}}


in fact anything I put in that's not regular characters it reads them as }


So I'm halfway there.

    public string SimpleCrypt(string Text)

    {

        // Encrypts/decrypts the passed string using 

        // a simple ASCII value-swapping algorithm

        string strTempChar = null;

        int i = 0;

        for (i = 1; i <= Text.Length; i++)

        {

            if (Convert.ToInt32(Text[i - 1]) < 128)

            {

                strTempChar = Convert.ToString(Convert.ToInt32(Text[i - 1]) + 128);

            }

            else if (Convert.ToInt32(Text[i - 1]) > 128)

            {

                strTempChar = Convert.ToString(Convert.ToInt32(Text[i - 1]) - 128);

            }

            Text = Text.Remove(i - 1, 1).Insert(i - 1, ((char)(Convert.ToInt32(strTempChar))).ToString());

        }

        return Text;

    }

Open in new window

0
 
LVL 20

Expert Comment

by:alainbryden
ID: 24796471
So far as your code adjustments, 16 bit integers should suffice, but that's not an issue here.

Step through your code when decrypting and find out what the value of
Text[i - 1]
Convert.ToInt32(Text[i - 1])
and
Convert.ToString(Convert.ToInt32(Text[i - 1]) + 128)
are for each iteration. One of these functions may have a problem interpreting ascii values outside the normal range?

--
Alain
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 20

Expert Comment

by:alainbryden
ID: 24796674
strangely enough, the encryption isn't occurring as I expected it to given the code provided:

t      e      s      t
116 101 115 116

+128 =

244 229 243 244
      Ã       d      


The encryption you gave is
ô     å     ó     ô
147 134 162 147

Why do you think that is. It it not just adding 128 to the ascii value of the character or removing 128 if it is already over 128?

Note that this code completely fails with ascii characters greater than or equal to 256. If it's 256, it will be encrypted to 128, and then will never be decrypted (because there's no case dealing with 128 exactly, only greater or less than 128). If the character is greater than 256, it will get encrypted a second time instead of decrypted, because the encrypted value is still greater than 128.

Either way, here is the code, as is, properly translated for C#, but you should fix it to be more correct. You should probably have one "Encrypt" and one "Decrypt" function that do the ascii shift consistently.

 I would try using the following code:

--
Alain
    public string SimpleCrypt(string Text)

    {

        // Encrypts/decrypts the passed string using 

        // a simple ASCII value-swapping algorithm

        char newChar;

        int currCharAsc;

        for (i = 0; i < Text.Length; i++)

        {

            newChar = null

            currCharAsc = Convert.ToInt16(Text[i])

            if (currCharAsc < 128)

            {

                newChar = Convert.ToChar(currCharAsc + 128);

            }

            else if (currCharAsc > 128)

            {

                newChar = Convert.ToChar(currCharAsc - 128);

            }

            else

            Text[i] = newChar;

        }

        return Text;

    }

Open in new window

0
 

Author Comment

by:megatherian
ID: 24797618
Thanks Alain,
Unfortunately I wasn't able to get your code to work for either encryption or decryption.  The code I'm using now works in 1 direction, encryption.  That is, if I tell it to the word:

test

it returns:

ôåóô

but if I give it:

ôåóô

it doesn't understand those characters and returns:

ýýýý

which it then decrypts incorrectly (obviously)

I didn't write the original VB code but the best I could figure is that it should be a simple ad or subtract 128 from the character values.

I believe that the problem has something to do with ASCII and Unicode - though I'm a bit shaky on that stuff so maybe that's just silly talk.  The VB code I think assumes ASCII and .NET assumes Unicode.  So when I'm using the 26 letters the code works fine (because they are the same in ASCII and Unicode).  When I go the other direction things don't seem to match up as well.  So, I guess what I need to know now is how to make the encoding all mesh up.

Thanks again for your help!
0
 
LVL 20

Accepted Solution

by:
alainbryden earned 500 total points
ID: 24797828
Sorry, I had a bunch of syntax errors in my code and I didn't realize you couldn't assign to an indexed string. Please do try the following, I guarantee that it works:

--
Alain
static void Main(string[] args)

        {

            string text = "test";

            Console.WriteLine(text);

            text = SimpleCrypt(text);

            Console.WriteLine(text);

            text = SimpleCrypt(text);

            Console.WriteLine(text);

            Console.ReadKey();

        }
 

        public static string SimpleCrypt(string Text)

        {

            // Encrypts/decrypts the passed string using 

            // a simple ASCII value-swapping algorithm

            string result = "";

            char newChar;

            int currCharAsc;

            for (int i = 0; i < Text.Length; i++)

            {

                newChar = (char)0;

                currCharAsc = Convert.ToInt16(Text[i]);

                if (currCharAsc < 128)

                {

                    newChar = Convert.ToChar(currCharAsc + 128);

                }

                else if (currCharAsc > 128)

                {

                    newChar = Convert.ToChar(currCharAsc - 128);

                }

                result += newChar;

            }

            return result;

        }

Open in new window

0
 
LVL 20

Expert Comment

by:alainbryden
ID: 24797847
Here is the result, just to be sure, it is what you want.

--
Alain
result.JPG
0
 

Author Closing Comment

by:megatherian
ID: 31600598
Thanks, that works great!
0
 
LVL 20

Expert Comment

by:alainbryden
ID: 24798088
You're welcome, and thank you for the points making me a Master in Visual Basic Programming :)

--
Alain
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now