LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Blowfish encryption implementation

Solved!
Go to solution

Managed to encrypt/decrypt strings using the rather succint  blowfish algorythm but have an issue that for whatever reason cannot overcome and understand.

The encryption algorithm uses 64 bit blocks, in a way that two letters in the cleartext are assigned to subsequent unsigned long integer enc...

see below:

int blowfish_encrypt_buffer(blowfish_context_t *ctx,char *cleartext,unsigned int bufferlen,unsigned long *enc){
    unsigned int i;
       for(i = 0; i < bufferlen; i+=2){
        enc[i]   = cleartext[i];
        enc[i+1] = cleartext[i+1];
        blowfish_encryptblock(ctx, &enc[i], &enc[i+1]);
     }

 return i;  
}

the output is the enc array that is i element long.

So far so good. If I use enc to decrypt, it works just fine:

 

int blowfish_decrypt_buffer(blowfish_context_t *ctx,unsigned long *cryptext,unsigned int bufferlen,char *cleartext){
  unsigned int i=0;
 
     for(i = 0; i < bufferlen; i+=2)    {
         blowfish_decryptblock(ctx, &cryptext[i], &cryptext[i+1]);
         cleartext[i] = cryptext[i];
         cleartext[i+1] = cryptext[i+1];
     }   
     cleartext[bufferlen] = '\0'; 
  return i;  
}

 

Now if I want to store the encrypted data -an array of unsigned longs, in a string, it looks handy to use hexadecimal string:

Running this loop and visualizing the string is nice:

for(int i=0;i<len;i++){
                sprintf(line,"%x",enc[i]);
                SetCtrlVal(bpanel,BPANEL_CRYPTEXT,line);
 }

it looks like this string here: 6441696d2d6e615073736f7764723231033...

 

The problem is that when I want to reveerse this, I cannot sscanf the the string into unsigned longs as it came from. Could not find the fortmatting parametes or other way to do it even if my life depends on it.  😞

L.

 

0 Kudos
Message 1 of 3
(4,575 Views)

You know the number of hexadecimal digits of a unsigned long ( 2* sizeof ( unsigned long) ) . So divide up the string in parts of that size and then scanf  these parts. 

In your print function is an error. You have to make sure that leading zeros aren't suppressed to be able to decrypt it again.

Message 2 of 3
(4,564 Views)
Solution
Accepted by topic author Layosh

Thank you! That seems to be the solution!

Layosh

0 Kudos
Message 3 of 3
(4,545 Views)