.NET to Java

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
Daniel SödlingAsked:
Who is Participating?
 
CEHJCommented:
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
 
CEHJCommented:
Please post what you attempted
0
 
Daniel SödlingAuthor Commented:
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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
CEHJCommented:
I can only repeat my last comment at this point
0
 
Daniel SödlingAuthor Commented:
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
 
CEHJCommented:
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
 
Daniel SödlingAuthor Commented:
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
 
CEHJCommented:
>>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
 
Daniel SödlingAuthor Commented:
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
 
Daniel SödlingAuthor Commented:
ehh, sorry about the embedded code. You can ignore that.
0
 
CEHJCommented:
>>
This is what you get on the .NET side:
Archive_FSE_117302500.zip  ->  12C51406
>>

You absolutely sure it's not 1051406 ?
0
 
Daniel SödlingAuthor Commented:
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
 
CEHJCommented:
That's rather a pity - since that's what i get ;)
0
 
Daniel SödlingAuthor Commented:
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
 
Daniel SödlingAuthor Commented:
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
 
Daniel SödlingAuthor Commented:
Got me out the of the hole I was digging for my self.
I'm very grateful!
0
 
CEHJCommented:
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
 
Daniel SödlingAuthor Commented:
Well, it produced 1C37E715.
What was the potential issue?
 
0
 
CEHJCommented:
>>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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.