I want to do an encryption / decryption program in C based on something I did in perl. The compiled perl program is 2MB so I figure if I write it in C it will be a smaller executable size.
My problem is, while I get it to encrypt, I can't get it to decrypt. It's been literally ages since I last used C so I forgot a lot of stuff. Someone please enlighten me to what I'm doing wrong here? Thanks.
/*
============================================================================
Name : test-c.c
Description : Testing Project
Trying to do a C version of this perl code:
my $cipher = Crypt::CBC->new( -key => $salt_key, -cipher => 'DES' -header => 'none');
my $enc_text = $cipher->encrypt_hex($text);
Requires : -lcrypt
References :
Function: cbc_crypt (char *key, char *blocks, unsigned len, unsigned mode, char *ivec)
GNU C Library: DES Encryption (http://www.gnu.org/software/libc/manual/html_node/DES-Encryption.html#DES-Encryption)
cbc_crypt (http://unix.derkeiler.com/Newsgroups/comp.unix.programmer/2012-10/msg00023.html)
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <rpc/des_crypt.h>
int main(void) {
char key[] = "aBcDeFg1";
char pass[] = "mypass1234test";
char encbuff[] = "87654321";
char decbuff[] = "87645321";
int buffsize;
int result;
des_setparity(key);
/* Encrypt pass, result is in encbuff */
buffsize = sizeof(pass);
/* Add to pass to ensure size is divisable by 8. */
while (buffsize % 8) {
pass[buffsize++] = '\0';
}
printf("Encrypted: ");
result = cbc_crypt(key, pass, buffsize, DES_ENCRYPT | DES_SW, encbuff);
if (DES_FAILED(result) || strcmp(encbuff, "") == 0) {
if(strcmp(encbuff, "") == 0) {
printf("*** Null Output ***\n");
} else {
printf("*** Encryption Error ***\n");
}
} else {
printf("%s\n", encbuff);
}
/* Decrypt encbuff, result is in decbuff */
/* FIXME: Decryption doesn't work:
Encrypted: ,�7&���8
Decrypted: *** Decryption Error ***
*/
buffsize = sizeof(encbuff);
/* Add to pass to ensure size is divisable by 8. */
while (buffsize % 8) {
encbuff[buffsize++] = '\0';
}
printf("Decrypted: ");
result = cbc_crypt(key, encbuff, buffsize, DES_DECRYPT | DES_SW, decbuff);
if(DES_FAILED(result) || strcmp(decbuff, "") == 0) {
if(strcmp(encbuff, "") == 0) {
printf("*** Null Output ***\n");
} else {
printf("*** Decryption Error ***\n");
}
} else {
printf("%s\n", decbuff);
}
return 0;
}