Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Decrypting DES encrypted text data from C/C++ using libcrypto (openssl)

843811Oct 14 2005 — edited Oct 16 2005
I have java cryptography initialised as follows, and have written the crude C/C++ test case attached below to try and decrypt a file I have written in Java.
The gives only garbage output when trying to decrypt the encrypted file my java code writes.
I read/write the file in java with CipherInputStream/CipherOutputStream.
I do not have much cryptography background. What am I missing here?
Any help with this appreciated.

private Cipher encCipher, decCipher;
private String keyText;

private void cryptoInit() throws Exception
{
DESKeySpec keySpec;
SecretKeyFactory keyFactory;
SecretKey key;
Security.addProvider(new com.sun.crypto.provider.SunJCE());
keySpec = new DESKeySpec(keyText.getBytes("UTF-8"));
keyFactory = SecretKeyFactory.getInstance("DES");
key = keyFactory.generateSecret(keySpec);
encCipher = Cipher.getInstance("DES/ECB/NoPadding"); //PKCS5Padding?
decCipher = Cipher.getInstance( "DES/ECB/NoPadding");
encCipher.init(Cipher.ENCRYPT_MODE, key);
decCipher.init(Cipher.DECRYPT_MODE, key);
}



#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <openssl/des.h>

using namespace std;

static void des_encrypt(const unsigned char in[8], DES_key_schedule *key,

int main(int argc, char **argv)
{
DES_cblock key;
DES_key_schedule schedule;

DES_string_to_key("12345678", &key);
DES_set_odd_parity(&key);
DES_set_key_unchecked(&key, &schedule);

FILE *f = fopen("encrypted.dat", "rb");

if (f == NULL) {
cout << "No input file" << endl;
return 1;
}

fseek(f, 0, SEEK_END);
size_t len = ftell(f);
fseek(f, 0, SEEK_SET);

unsigned char buf = (unsigned char )malloc(len);

fread(buf, len, 1, f);
fclose(f);

if (len % 8 != 0) {
cout << "FATAL: File length is not a multiple of block size" << endl;
return 1;
}

unsigned char *p1 = buf; // walk through buffer in block size increments

for (int i = 0; i < len; i += 8) {
DES_ecb_encrypt((DES_cblock *)p1, (DES_cblock *)p1, &schedule, DES_DECRYPT);
p1 += 8;
}

printf((const char *)buf);
printf("\n");

free(buf);

return 0;
}

Built with:
g++ -o destest -O2 -lcrypto main.cpp
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 13 2005
Added on Oct 14 2005
2 comments
2,036 views