Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Mar 2005
    Location
    Brighton, UK
    Posts
    117
    Thanks
    0
    Thanked 0 Times in 0 Posts

    mcrypt encrypt/decrypt functions

    Hi, I have written these two functions to encrypt and then decrypt data on my site, and I was hoping someone could let me know if they are OK? I'm just not sure about the way I'm handling the IV value. Because its random, but is also required to decrypt, I'm just adding it to the encrypted string, and then splitting that in the decrypt function. Is this what most people do?

    PHP Code:
    public function encrypt($string$key) {
        
    $mcrypt    mcrypt_module_open('rijndael-256''''ofb''');
        
    $iv        mcrypt_create_iv(mcrypt_enc_get_iv_size($mcrypt), MCRYPT_RAND);
        
    $size    mcrypt_enc_get_key_size($mcrypt);
        
    $key    substr(hash('sha256'$key), 0$size);
        
    mcrypt_generic_init($mcrypt$key$iv);
        
    $encrypted mcrypt_generic($mcrypt$string);
        
    mcrypt_generic_deinit($mcrypt);
        
    mcrypt_module_close($mcrypt);
        return 
    $iv.$encrypted;
    }

    public function 
    decrypt($string$key) {
        
    $mcrypt    mcrypt_module_open('rijndael-256''''ofb''');
        
    $iv        substr($string0mcrypt_enc_get_iv_size($mcrypt));
        
    $string    substr($stringmcrypt_enc_get_iv_size($mcrypt));
        
    $size    mcrypt_enc_get_key_size($mcrypt);
        
    $key    substr(hash('sha256'$key), 0$size);
        
    mcrypt_generic_init($mcrypt$key$iv);
        
    $decrypted mdecrypt_generic($mcrypt$string);
        
    mcrypt_generic_deinit($mcrypt);
        
    mcrypt_module_close($mcrypt);
        return 
    $decrypted;

    Thanks, Jack

  • #2
    New to the CF scene
    Join Date
    Feb 2007
    Location
    Utah
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts
    The Initialization Vector (IV) doesn't need to be private. In fact, as you are doing here, it can be attached to the cipher-text. Careful with those keys though.

  • #3
    Regular Coder
    Join Date
    Mar 2005
    Location
    Brighton, UK
    Posts
    117
    Thanks
    0
    Thanked 0 Times in 0 Posts
    OK great, and the way I'm attaching it and then detaching it is OK? I thought I might need to use mb_substr instead of substr, but it seems to work, is this reliable enough?

    Careful with those keys though.
    Why? Is there a problem?


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •