Encryption in C# gives different result from encryption in Java

G

Guest

Modification to my earlier post, in case anyone thinks I am trying to code in
Java what we did in C#. We are trying to code in C# what we coded in Java,
so I do need C#, not Java, help. :) Anyway, we have existing code in Java
that encrypts a string using DES. However, when we encrypt in C# the string
is encrypted differently.

The code in C# is:

DES desAlg = new DESCryptoServiceProvider();
InitKey(epsKey);
desAlg.Key = dec_Key;
desAlg.IV = dec_Key;
byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncrypt);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ICryptoTransform encrypto = desAlg.CreateEncryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
cs.Write(bytIn, 0, bytIn.Length);
cs.FlushFinalBlock();
ms.Close();
cs.Close();
byte[] resArray = ms.ToArray();
encryptedString = System.Convert.ToBase64String(resArray);

The code in Java is:

DESKeySpec desKeySpec = new DESKeySpec(epsKey.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ETYPE);
SecretKey key = keyFactory.generateSecret(desKeySpec);
ecipher = Cipher.getInstance(ETYPE);
ecipher.init(Cipher.ENCRYPT_MODE, key);
byte[] enc = ecipher.doFinal(str.getBytes("UTF8"));
encryptedString = new BASE64Encoder().encode(enc);

Any ideas?
 
C

Chris Dunaway

Carolyn said:
The code in C# is:

byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncrypt);

The code in Java is:

byte[] enc = ecipher.doFinal(str.getBytes("UTF8"));
Any ideas?

I'm not sure, but it looks like you are using different encodings for
your input strings. In the C# version you are encoding the string as
ASCII but in Java you are using UTF8
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top