Search code examples
perlencryptionblowfish

Blowfish Encrypt and Decrypt need to return an error


I'm using Blowfish to encrypt and Decrypt with the code below. I need to return an error if there is a problem with Decryption if say the encrypted line doesn't have the correct Salt. As it is, the script just dies. Thanks

sub decrypt { $cipher = new Crypt::CBC( $key, 'Blowfish' );  
defined $_[0] ? $cipher->decrypt_hex($_[0]) : '' 
#I NEED SOMETHING LIKE
#if ($cipher){ $return = $cypher; }
#else{ $return = "BadNumber"; }
return $return;
}

sub encrypt { $cipher = new Crypt::CBC( $key, 'Blowfish' );  
defined $_[0] ? $cipher->encrypt_hex($_[0]) : ''  }

Solution

  • Do not use Blowfish: yes it is a neat name but it is antiquated and superseded by AES. Use AES if security is what you want to achieve.

    There are plenty of answers on SO that provide example code.

    If you need to know if the decryption was successful, meaning the same as what was encrypted, use authenticated encryption. See this SO Answer for more details on authenticated encryption.

    By definition encryption is just a math function, it is always successful. It is like x = y * z, x will always equal something, it just may not be what you want if the incorrect values are provided for y & z. Encryption is similar, you need to provide the correct encrypted data and key in order to get the desired decrypted data. If you provide incorrect encrypted data and/or an incorrect key you will get a result but it will not be the desired decrypted data.

    If there is padding a padding error may be noticed on an invalid key but this must be ignored and not reported or a padding oracle attack is possible.