Solved

Convert Delphi to c#

Posted on 2011-03-23
10
1,077 Views
Last Modified: 2012-05-11
I am having problems converting the following from Delphi to C#:

const
  cKey1 = 57287;
  cKey2 = 34321;

    function Decrypt(CONST s:  STRING; Key:  WORD):  STRING;
    var
      b:   BYTE;
      i:   INTEGER;
    begin
        b := 0;
        RESULT := '';
        FOR i := 1 TO LENGTH(s) DIV 2 DO
        begin
          try
            b :=  StrToInt('$' + COPY(s, 2*i-1, 2));
          except
            ON EConvertError DO b := 0
          end;
          RESULT := RESULT + CHAR( b XOR (key SHR 8) );
          key := (b + key) * Ckey1 + Ckey2
        end
    end;
0
Comment
Question by:markusr13
  • 4
  • 3
  • 2
  • +1
10 Comments
 

Author Comment

by:markusr13
Comment Utility
use this as a test: "9DD6678ACD84FC0211DBCA543EE1F5"
0
 

Author Comment

by:markusr13
Comment Utility
probably should note that they key = 51474
0
 
LVL 33

Expert Comment

by:Todd Gerbert
Comment Utility
I get "TheSkyIs" in C# - conversion from one to the other doesn't seem terribly difficult, the Delphi syntax seems relatively obvious (I've never even seen Delphi before, and was able to make some sense out of it).

Did you give it a try?  Was there something in particular you were stuck at?
0
 
LVL 24

Accepted Solution

by:
jimyX earned 63 total points
Comment Utility
I am from Delphi zone and i do not know much about C#. The following is my trying:
public const int cKey1 = 57287;
public const int cKey2 = 34321;

public STRING Decrypt(string Name s, ushort Key)
{
    Byte b = 0;
    int i;
    string result = "";
    for (int i = 1; i <= s.Length / 2; i++)
    {
    try 
    {
      b = int.Parse(s.Substring(2*i-2, 2), NumberStyles.AllowHexSpecifier);
    }
    catch
    {
      b = 0;
    }
      result += (char)( b ^ (key >> 8) );
      key = (b + key) * Ckey1 + Ckey2;
    }
    return result;
}

Open in new window

0
 
LVL 33

Assisted Solution

by:Todd Gerbert
Todd Gerbert earned 62 total points
Comment Utility
Well, I had already done the work, I was just trying not to give it away for free, just in case this was a homework assignment or something. ;)

static string Decrypt(string encryptedString, ushort Key)
{
	ushort cKey1 = 57287, cKey2 = 34321;
	StringBuilder returnValue = new StringBuilder();

	for (int i = 0; i < encryptedString.Length / 2; i +=2)
	{
		byte b;
		try
		{
			b = Byte.Parse(encryptedString.Substring(i, 2), NumberStyles.HexNumber);
		}
		catch
		{
			b = 0;
		}

		returnValue.Append((char)(b ^ (Key >> 8)));

		Key = (ushort)((b + Key) * cKey1 + cKey2);
	}

	return returnValue.ToString();
}

Open in new window

0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 24

Expert Comment

by:jimyX
Comment Utility
@ tgerbert
Sorry mate, did not mean to spoil it.

Side comment ;-)
>   "Delphi syntax seems relatively obvious"
That's sure thing.

>   "I've never even seen Delphi before"
Oh man, Delphi is the best. Try using it, you will be amazed.

Cheers
0
 

Author Comment

by:markusr13
Comment Utility
Man, this looks pretty much looks like what I did...

What was getting me was "key := (b + key) * Ckey1 + Ckey2"

A word is only 65,535 but this calculation goes beyond that. I didn't dig into Delphi to see exactly how it was handling it. C# (ushort) doesn't handle it as gracefully....I thought.

I will test more tomorrow. jimyX version works on my test string tgerbert falls a little short (I will see why tgerbert's only returned me 8 characters).

Points come tomorrow.

(Delphi is great, c# is Delphi on steroids as it was written even better by the person (Anders) that wrote Delphi) but i still miss the bookmarks which must have been patented by Borland. VS has something similar but can't be numbered and they cross units.

-Markus

0
 

Author Comment

by:markusr13
Comment Utility
working solution (thanks to both of you). I don't know what I was smoking but I should have solved it myself. I had to have been doing something dumb on this line: Key = (ushort)((b + Key) * cKey1 + cKey2);

public string Decrypt(string s, ushort Key)
{
    Byte b = 0;

    string result = "";
    for (int i = 1; i <= s.Length / 2; i++)
    {
    try
    {
      b = (byte)int.Parse(s.Substring(2*i-2, 2), NumberStyles.AllowHexSpecifier);
    }
    catch
    {
      b = 0;
    }
    result += (char)(b ^ (Key >> 8));
    Key = (ushort)((b + Key) * cKey1 + cKey2);
    }
    return result;
}
0
 
LVL 33

Expert Comment

by:Todd Gerbert
Comment Utility
I made a typo (copied the "/ 2" from your Delphi code, realized I didn't need it, but forgot to take it out).
Couple notes...

1. Use meaningful variable names, particularly for method parameters, e.g. "encryptedString" instead of "s"

2. Instead of this goofy construct ".Substring(2*i-2, 2)", you can initialize the for loop's iterator, i, to 0, make it's condition that i is less than the string's length, and increment it by two each iteration, instead of 1, you can write ".Substring(i, 2)" - which changes the "for" loop from "for (int i = 1; i <= s.Length / 2; i++)" to "for (int i = 0; i < s.Length; i += 2)"

3. The byte "b" is of no use to me outside of the for loop, so I deliberately declared it inside the loop to limit it's scope.

4. Don't concatenate strings in loops like this using syntax such as "result += someOtherString" - since strings in .Net are immutable (meaning once created they can't be changed), you're actually creating new strings everytime you do that. That's what the StringBuilder is intended for.

static public string Decrypt(string encryptedString, ushort Key)
{
	ushort cKey1 = 57287, cKey2 = 34321;
	StringBuilder returnValue = new StringBuilder();

	for (int i = 0; i < encryptedString.Length; i += 2)
	{
		byte b;
		try
		{
			b = Byte.Parse(encryptedString.Substring(i, 2), NumberStyles.HexNumber);
		}
		catch
		{
			b = 0;
		}

		returnValue.Append((char)(b ^ (Key >> 8)));

		Key = (ushort)((b + Key) * cKey1 + cKey2);
	}

	return returnValue.ToString();
}

Open in new window


Funny how, even though I'd never seen Delphi code before, I could deduce that "key SHR 8" means shift-right by 8 bits - but if I had never seen C# before, the equivelant statement "key >> 8" would be almost meaningless. I still prefer C# though. ;)

Bookmarks (if they're what I think they are) would be a feature of the text editor Borland ships with their product, not the language.  There are a number of free text editors available that handle things like syntax highlighting for C# (and other languages) that might do what you want - there's nothing that says you have to use Visual Studio to write C#.
0
 
LVL 25

Expert Comment

by:epasquier
Comment Utility
@tgerbert :  the Delphi syntax seems relatively obvious

Indeed it is. And that sample was an easy one, you would be amazed how readable it is for complex things (objects). Compared to C syntax (and all derived Java, C++, C#) Delphi is just pure vanilla
And to say that the framework is also simple AND effective is an understatement. If you like .Net, you have to LOVE Delphi if you give it a try

I would like to know why you still prefer C#, as you said quite correctly that Delphi is so readable that any good programmer with no specific knowledge of it can understand it. Maybe we can convince you otherwise :o)

> c# is Delphi on steroids
I wouldn't say C# (.Net in fact) is better than Delphi. Let's say it is Java redesigned for MS world in Delphi spirit but keeping C-style syntax. a kind of hydra with multiple heads if you ask me, a powerful one for sure. But it couldn't be compared with any native language, as far as performance is concerned.

0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

771 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

10 Experts available now in Live!

Get 1:1 Help Now