AES 加解密

1 篇文章 / 0 new
author
AES 加解密
► 簡易方式, 固定iv(初始向量), 同樣資料每次產生的加密文均一樣
function aesEncrypt($key, $plaintext, $iv)
{
    $ciphertext_raw = openssl_encrypt($plaintext, 'AES-256-CBC', $key, $options=OPENSSL_RAW_DATA, $iv);
    return urlBase64Encode( $ciphertext_raw );
}
 
function aesDecrypt($key, $ciphertext, $iv)
{
    $c = urlBase64Decode($ciphertext);
    return openssl_decrypt($c, 'AES-256-CBC', $key, $options=OPENSSL_RAW_DATA, $iv);
}

► 組合方式, 動態iv(初始向量), 同樣資料每次產生的加密文不會一樣
資料組合為 iv + msha + ciphertext, msha 則是用來檢查祕文是否變動過
function aesEncrypt($key, $plaintext)
{
    $cipher="AES-256-CBC";
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = openssl_random_pseudo_bytes($ivlen);//產生 iv
    $ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
    $ciphertext = urlBase64Encode( $iv.$hmac.$ciphertext_raw );
    return $ciphertext;
}
 
function aesDecrypt($key, $ciphertext)
{
    $cipher="AES-256-CBC";
    $c = urlBase64Decode($ciphertext);
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = substr($c, 0, $ivlen);
    $hmac = substr($c, $ivlen, $sha2len=32);
    $ciphertext_raw = substr($c, $ivlen+$sha2len);
    $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
    $calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
    if (hash_equals($hmac, $calcmac))//PHP 5.6+ timing attack safe comparison
    {
        return $original_plaintext;
    } else {
        return false;
    }
}
Free Web Hosting