RapidMod icon

PHP AES 256 CBC Secure Encryption / Decryption

RapidMod | PRO | 03/12/18 02:30:30 PM UTC | 0 ⭐ | 433 👁️ | Never ⏰ | []
PHP |

1.53 KB

|

None

|

0 👍

/

0 👎

<?php
/**
 *
 * Name AES Encryption
 * 
 *
 * @param $appKey random_bytes( 16 )
 * @param $secretKey random_bytes( 32 )
 *
 * @author RapidMod.com
 * @author 813.330.0522
 * 
 */
 
/**
 *
 * Name encryptData
 * @param $data
 *
 * @param $appKey
 * @param $secretKey
 *
 * @return string
 * 
 * @author RapidMod.com
 * @author 813.330.0522
 * 
 */
function encryptData($data,$appKey,$secretKey) {
    
 
    $method = "aes-256-cbc";
    $iv_length = openssl_cipher_iv_length($method);
    $iv = openssl_random_pseudo_bytes($iv_length);
 
    $first_encrypted = openssl_encrypt($data,$method,$appKey, OPENSSL_RAW_DATA ,$iv);
    $second_encrypted = hash_hmac('sha3-512', $first_encrypted, $secretKey, TRUE);
 
    $output = base64_encode($iv.$second_encrypted.$first_encrypted);
    return $output;
}
 
/**
 *
 * Name decryptData
 * @param $data
 *
 * @param $appKey
 * @param $secretKey
 *
 * @return bool|string
 *
 * @author RapidMod.com
 * @author 813.330.0522
 * 
 */
function decryptData($data,$appKey,$secretKey) {
    
    $method = "aes-256-cbc";
    $iv_length = openssl_cipher_iv_length($method);
    $data = base64_decode($data);
    $iv = substr($data,0,$iv_length);
 
    $second_encrypted = substr($data,$iv_length,64);
    $first_encrypted = substr($data,$iv_length+64);
 
    $data = openssl_decrypt($first_encrypted,$method,$appKey,OPENSSL_RAW_DATA,$iv);
    $second_encrypted_new = hash_hmac('sha3-512', $first_encrypted, $secretKey, TRUE);
    if (hash_equals($second_encrypted,$second_encrypted_new)){return $data;}
    return false;
}
?>

Comments