3DES, Encryption in C (Unsigned), Decryption in Java

Hi Guys,

I face 3DES decryption problem in Java where as encryption was done in C by using OpenSSL. Java 3DES method input is in byte[]. As we known, Java didn抰 support for unsigned data type. That抯 why my decryption result is different with the original value.

Below is my Java code:

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");

DESedeKeySpeckeySpec =newDESedeKeySpec(getTripleDesMD5Value("abcde"));

SecretKey key = keyFactory.generateSecret(keySpec);

Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");

cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] finalBytes=newbyte[16];

byte[] bytesToEncrypt ="1234".getBytes();

if (bytesToEncrypt.length<16){

int i=0;

for (i=0;i<16;i++){

if (i<bytesToEncrypt.length){

finalBytes[i]=bytesToEncrypt[i];

}else{

finalBytes[i]='\0';

}

}

}

String encryptedBytesAsString="";

byte[] oBytes = finalBytes;

byte[] otBytes =newbyte[8];

for (int i=0;i<8;i++){

otBytes[i]=oBytes[i];

}

byte[] encryptedBytes = cipher.doFinal(otBytes);

getTripleDesMD5Value("abcde") = in signed byte.

In other words, encryption/decryption in Java will use signed byte object as an input.

Anyone face this problem before and get solution?

Thank you very much.

Regards,

Sapiduta>

[2415 byte] By [sapidutaa] at [2007-11-26 12:21:59]
# 1

> getTripleDesMD5Value("abcde") = in signed byte.

> In other words, encryption/decryption in Java will

> use signed byte object as an input.

> Anyone face this problem before and get solution?

It makes no difference at all since you are only concerned with the bit pattern in the byte and not it's numerical value. You have something else wrong but without seeing your 'C' code it is difficult to say what.

I can make a few comments on the Java code.

1) In Java, when one create a byte array all the bytes are initialised to zero so the 'else' part of your padding " finalBytes[i]='\0'" is not required.

2) Having padded your data to 16 bytes you then truncate to just 8 bytes. This seems silly!

3) You seem to be creating a Tripple DES key from an MD5 hash (16 bytes only) but since we don't have access to your getTripleDesMD5Value() method we can't be sure that it generates a valid 24 byte Tripple DES key.

4) You have a reference named 'encryptedBytesAsString' but you don't show how this String is generated from your encrypted bytes. This operation is critical to the correct working of the encryption.

sabre150a at 2007-7-7 15:14:32 > top of Java-index,Archived Forums,Socket Programming...