?
Solved

.NET to Java

Posted on 2011-10-25
19
Medium Priority
?
361 Views
Last Modified: 2012-06-27
All,

could someone please help me translate the following code into Java? I thought I hade figured out what the code did but apparently I was wrong.

 
private String Encrypt_Decrypt_Code(String key)
{
   Int64 p = 17;
   Int64 CodeNo = 0;
   for (Int32 i = 0; i < key.Length; i++)
   {
       p = p & Convert.ToInt64("3FFFFF", 16);
       String s = key.Substring(i, 1);
       CodeNo = (CodeNo & Convert.ToInt64("3FFFFFFF", 16))    + p * Asc(new Char[] { Convert.ToChar(key.Substring(i, 1)) });
        p = p * 11;
    }
    return String.Format("{0:X}", CodeNo);
}

private Int32 Asc(Char[] ch)
{
    Byte[] b = Encoding.GetEncoding(1252).GetBytes(ch);
    return (Int32)b[0];
}

Open in new window


Thank you
Daniel Martinsson
0
Comment
Question by:Daniel Södling
  • 10
  • 9
19 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 37030116
Please post what you attempted
0
 

Author Comment

by:Daniel Södling
ID: 37030210
Well, the idea is to create a password based on the name of a file. I cannot say why things are done this way, it is a customer of mine who are moving a legacy application to a Java based version of it. So, from the given filename a hexadecimal password is to be created using the algorithm posted. I tried to convert it to Java but Iäm guessing that my lack of C# knowledge lead me down the wrong path because the output I get does not match the given test values.

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37030221
I can only repeat my last comment at this point
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:Daniel Södling
ID: 37030239
Oh, sorry.... I missread your question!
My apologies.

 
public String Encrypt_Decrypt_Code(String key) {

        long p = 17;
        long code = 0;

        for (char c : key.toCharArray()) {

            p = p & Long.decode("0x3FFFFF");
            code = (code & Long.decode("0x3FFFFFFF")) + p * asc(new char[]{c});
            p = p * 11;
        }


        return Long.toHexString(p);

    }

    private int asc(char[] ch) {

        byte[] bytes = String.valueOf(ch).getBytes(Charset.forName("windows-1252"));
        return (int) bytes[0];

    }

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37030270
OK. The best way to proceed now is to let us have

a. correct input value
b. correct output value

(from the .NET side)
0
 

Author Comment

by:Daniel Södling
ID: 37030285
input: 117302500
output: 12C51406

One additional thing: the given input is what the user puts into a dialog box. I do have a small code snipet t
Encrypt_Decrypt_Code("Archive_FSE_" & txtFileName.Text & ".zip")

Open in new window


That shows that there are some text added to the user input.
So my guess is that the actual input to try with is: Archive_FSE_117302500.zip
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37030311
>>So my guess is that the actual input to try with is

We don't want any guesswork ;) Let's have the actual input and the actual correct output
0
 

Author Comment

by:Daniel Södling
ID: 37030336
I agree and I double checked.
This is what you get on the .NET side:
Archive_FSE_117302500.zip  ->  12C51406
VERSION 5.00
Begin VB.Form frmEncryptDecryptCode 
   Caption         =   "EncryptCode"
   ClientHeight    =   1320
   ClientLeft      =   60
   ClientTop       =   450
   ClientWidth     =   2610
   LinkTopic       =   "Form1"
   ScaleHeight     =   1320
   ScaleWidth      =   2610
   StartUpPosition =   3  'Windows Default
   Begin VB.TextBox txtFileName 
      Height          =   285
      Left            =   150
      TabIndex        =   0
      Top             =   300
      Width           =   2325
   End
   Begin VB.Label lblHeaderEncryptDecryptCode 
      Caption         =   "Encrypt/Decrypt Code"
      Height          =   195
      Left            =   150
      TabIndex        =   3
      Top             =   690
      Width           =   1755
   End
   Begin VB.Label lblHeaderFileNmae 
      Caption         =   "File Name"
      Height          =   225
      Left            =   150
      TabIndex        =   2
      Top             =   90
      Width           =   1095
   End
   Begin VB.Label lblEncryptDecryptCode 
      BorderStyle     =   1  'Fixed Single
      Height          =   285
      Left            =   150
      TabIndex        =   1
      Top             =   900
      Width           =   2325
   End
End
Attribute VB_Name = "frmEncryptDecryptCode"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit

'------------------------'
'   EncryptDecryptCode   '
'------------------------'
Public Function EncryptDecryptCode(strKey As String) As String

   Dim LngI As Long
   Dim lngP As Long
   Dim lngCodeNo As Long
    
   lngP = 17
   For LngI = 1 To Len(strKey)
      lngP = lngP And &H3FFFFF
      lngCodeNo = (lngCodeNo And &H3FFFFFFF) + lngP * Asc(Mid$(strKey, LngI, 1))
      lngP = lngP * 11
   Next LngI
   
   EncryptDecryptCode = Hex(lngCodeNo)
   
End Function
'---------------'
'   Form_Load   '
'---------------'
Private Sub Form_Load()

   txtFileName_Change
   
End Sub
'------------------------'
'   txtFileName_Change   '
'------------------------'
Private Sub txtFileName_Change()

   lblEncryptDecryptCode.Caption = EncryptDecryptCode("Archive_FSE_" & txtFileName.Text & ".zip")
   With Clipboard
      .Clear
      .SetText lblEncryptDecryptCode.Caption
   End With
   
End Sub

Open in new window

0
 

Author Comment

by:Daniel Södling
ID: 37030337
ehh, sorry about the embedded code. You can ignore that.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37030362
>>
This is what you get on the .NET side:
Archive_FSE_117302500.zip  ->  12C51406
>>

You absolutely sure it's not 1051406 ?
0
 

Author Comment

by:Daniel Södling
ID: 37030371
Yes, I have the value (12C51406) both in a screenshot from the customer and from the output of the .NET code on my own machine.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37030382
That's rather a pity - since that's what i get ;)
0
 

Author Comment

by:Daniel Södling
ID: 37030411
Here is the compiled code (and source) that I'm running to get the value.

 
using System;
using System.Text;
namespace SampleNamespace
{
    public class SampleClass
    {
        public static void Main()
        {
            // Write hello world to the console
            System.Console.WriteLine("Archive_FSE_117302500.zip -> " + Encrypt_Decrypt_Code("Archive_FSE_117302500.zip"));
            System.Console.WriteLine("117302500.zip -> " + Encrypt_Decrypt_Code("117302500.zip"));
            System.Console.WriteLine("Press any key to exit the application");
            System.Console.Read();
        } // End of Main function (program statup)
        
                
       public static String Encrypt_Decrypt_Code(String key)
       {
            Int64 p = 17;
            Int64 CodeNo = 0;
            for (Int32 i = 0; i < key.Length; i++)
            {
                p = p & Convert.ToInt64("3FFFFF", 16);
                String s = key.Substring(i, 1);
                CodeNo = (CodeNo & Convert.ToInt64("3FFFFFFF", 16)) + 
                p * Asc(new Char[] { Convert.ToChar(key.Substring(i, 1)) });
                p = p * 11;
            }
            return String.Format("{0:X}", CodeNo);
        }

        public static Int32 Asc(Char[] ch)

        {
            Byte[] b = Encoding.GetEncoding(1252).GetBytes(ch);
            return (Int32)b[0];
        }
        
    } // End of SampleClass
} // End of SampleNamespace

Open in new window


Change the extension to .exe and see what you get.
 
pwdTest.txt
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 2000 total points
ID: 37030436
Gotcha! I was reading the two hex magic numbers as the same ;) The original was quite inefficient, so have tried to iron those inefficiencies out:
private String Encrypt_Decrypt_Code(String key) {
        String result = null;
        long p = 17;
        long code = 0;
        long smallSalt = Long.decode("0x3FFFFF");
        long bigSalt = Long.decode("0x3FFFFFFF");

        try {
            byte[] tmp = key.getBytes("windows-1252");

            for (int i = 0; i < tmp.length; i++) {
                int asciiCode = tmp[i] & 0xFF;
		p &= smallSalt;
		code = (code & bigSalt) + (p * asciiCode);
		p *= 11;
            }
	    result = String.format("%x", code);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;
    }

Open in new window

0
 

Author Comment

by:Daniel Södling
ID: 37030458
Thank you so much!
I ran in in my NetBeans projext and got he most uplifting unit test result I've seen in a long time! :)

I'm almost afraid to ask but what did I get wrong in my code?
0
 

Author Closing Comment

by:Daniel Södling
ID: 37030476
Got me out the of the hole I was digging for my self.
I'm very grateful!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37030523
I think it might be a little early to be throwing hats in the air though. There's a potential problem (possibly)

Try it with this filename
£Archive_FSE_117302500.zip

Open in new window

0
 

Author Comment

by:Daniel Södling
ID: 37030553
Well, it produced 1C37E715.
What was the potential issue?
 
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37030641
>>I'm almost afraid to ask but what did I get wrong in my code?

The tiniest error:

>>  return Long.toHexString(p);

should have been the below. I think my concerns were unfounded btw, but it won't do any harm to test £Archive_FSE_117302500.zip as a name. Your (corrected) code will output something different to mine

return Long.toHexString(code);

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month14 days, 22 hours left to enroll

839 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