How do you Encrypt and Decrypt a PHP String?

后端 未结 10 1496
梦毁少年i
梦毁少年i 2020-11-22 01:21

What I mean is:

Original String + Salt or Key --> Encrypted String
Encrypted String + Salt or Key --> Decrypted (Original String)

May

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 01:50

    If you don't want to use library (which you should) then use something like this (PHP 7):

    function sign($message, $key) {
        return hash_hmac('sha256', $message, $key) . $message;
    }
    
    function verify($bundle, $key) {
        return hash_equals(
          hash_hmac('sha256', mb_substr($bundle, 64, null, '8bit'), $key),
          mb_substr($bundle, 0, 64, '8bit')
        );
    }
    
    function getKey($password, $keysize = 16) {
        return hash_pbkdf2('sha256',$password,'some_token',100000,$keysize,true);
    }
    
    function encrypt($message, $password) {
        $iv = random_bytes(16);
        $key = getKey($password);
        $result = sign(openssl_encrypt($message,'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv), $key);
        return bin2hex($iv).bin2hex($result);
    }
    
    function decrypt($hash, $password) {
        $iv = hex2bin(substr($hash, 0, 32));
        $data = hex2bin(substr($hash, 32));
        $key = getKey($password);
        if (!verify($data, $key)) {
          return null;
        }
        return openssl_decrypt(mb_substr($data, 64, null, '8bit'),'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv);
    }
    
    $string_to_encrypt='John Smith';
    $password='password';
    $encrypted_string=encrypt($string_to_encrypt, $password);
    $decrypted_string=decrypt($encrypted_string, $password);
    

提交回复
热议问题