Blowfish encryption and decryption in C

4.6k Views Asked by At

So here is my C program, I can't figure out why I can't decrypt the encrypted string. I wanted to write a small C program which takes a string, encrypts, then takes the encrypted string and with the supplied key, decrypts. Two questions: A)What am I doing wrong here? B)How is the key stored, that is, if I am now working on a new encryption and the user wants to decrypt the previous text, when he supplies the password, would blowfish then know how to decrypt it?

Here is documentation for blowfish: http://www.openssl.org/docs/crypto/blowfish.html and now my program:

#include <string.h>
#include "blowfish.h"
#include "bf_pi.h"
#include "bf_locl.h"
#include <stdio.h>
#include <stdlib.h>

int main()
 {
    char from[128], to[128];
    int len = 128;
    BF_KEY key;
    char temp_buf[16];
    int n = 0;          /* internal blowfish variables */
    unsigned char iv[8];        /* Initialization Vector */
    /* fill the IV with zeros (or any other fixed data) */
    memset(iv, 0, 8);


    printf("input password: ");
    scanf("%s", &temp_buf);

    strcpy(from, "ABCDEFGHTHISISTHEDATA"); //ENCRYPT THIS

    BF_set_key(&key, 16, temp_buf);

    BF_cfb64_encrypt(from, to, len, &key, iv, &n, BF_ENCRYPT);
    printf("encrypted to -->  %s\n", to); //SUCCESSFULY ENCRYPTED


    BF_cfb64_encrypt(from, to, len, &key, iv, &n, BF_DECRYPT);
    printf("File %s has been decrypted to --> %s \n",from,  to); //FAILS DOES NOT DECRYPT
}
1

There are 1 best solutions below

6
On

I think you're supposed to switch the from and to variables:

//as WhozCraig mentioned, fill in n and iv again before decryption
n = 0;          /* internal blowfish variables */
/* fill the IV with zeros (or any other fixed data) */
memset(iv, 0, 8);

BF_cfb64_encrypt(to, from, len, &key, iv, &n, BF_DECRYPT);
printf("File %s has been decrypted to --> %s \n",to,  from); //FAILS DOES NOT DECRYPT

Retaining the original IV (which isn't hard; it was all zeros) and resetting n to zero before the decryption will get what the OP wants - WhozCraig