php openssl加密解密2

时间:2019-08-21 11:35:59 阅读:77次
php openssl加密解密2
//PRIVATE_KEY  PUBLIC_KEY  八位随机字符串

//加密
function encryptionEncode($content)
{
    if(PHP_VERSION<5.6 && extension_loaded('mcrypt')){
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES,PRIVATE_KEY,$content,MCRYPT_MODE_CBC,PUBLIC_KEY));
        return $encrypted;
    } elseif (extension_loaded('openssl')) {
        $len = strlen($content);
        if($len%8){
            $content= str_pad($content,$len+8-$len%8,"\0");
        }
        //使用空字符填充字符串的右侧,使字符串位数变为8的倍数
        $encrypted = base64_encode(openssl_encrypt($data,'DES-EDE3-CBC',PRIVATE_KEY,OPENSSL_RAW_DATA|OPENSSL_NO_PADDING,PUBLIC_KEY));
        return $encrypted;
    }
    return $content;
}


//解密方法
function decryptionEncode($content)
{
    try {
        if(PHP_VERSION<5.6 && extension_loaded('mcrypt')) {
            $result = rtrim(mcrypt_decrypt(MCRYPT_3DES, PRIVATE_KEY, base64_decode($content), MCRYPT_MODE_CBC, PUBLIC_KEY), '\0');
            $result = @json_decode(trim($result), true);
        } elseif(extension_loaded('openssl')) {
            $result = openssl_decrypt(base64_decode($content),'DES-EDE3-CBC',PRIVATE_KEY,OPENSSL_RAW_DATA|OPENSSL_NO_PADDING,PUBLIC_KEY);
            $result = @json_decode(trim($result), true);
        } else {
            $result = [];
        }
        return $result;
    } catch (\think\Exception $exception) {
        return [];
    }
}


//PRIVATE_KEY  PUBLIC_KEY  16位随机字符串 部分加密为空,暂时未查明原因

//加密
function encryptionEncode($content)
{
    if(PHP_VERSION<5.6 && extension_loaded('mcrypt')){
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,PRIVATE_KEY,$content,MCRYPT_MODE_CBC,PUBLIC_KEY));
        return $encrypted;
    } elseif (extension_loaded('openssl')) {
        $len = strlen($content);
        if($len%8){
            $content= str_pad($content,$len+8-$len%8,"\0");
        }
        //使用空字符填充字符串的右侧,使字符串位数变为8的倍数
        $encrypted = base64_encode(openssl_encrypt($data,'AES-128-CBC',PRIVATE_KEY,OPENSSL_RAW_DATA|OPENSSL_NO_PADDING,PUBLIC_KEY));
        return $encrypted;
    }
    return $content;
}


//解密方法
function decryptionEncode($content)
{
    try {
        if(PHP_VERSION<5.6 && extension_loaded('mcrypt')) {
            $result = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, PRIVATE_KEY, base64_decode($content), MCRYPT_MODE_CBC, PUBLIC_KEY), '\0');
            $result = @json_decode(trim($result), true);
        } elseif(extension_loaded('openssl')) {
            $result = openssl_decrypt(base64_decode($content),'AES-128-CBC',PRIVATE_KEY,OPENSSL_RAW_DATA|OPENSSL_NO_PADDING,PUBLIC_KEY);
            $result = @json_decode(trim($result), true);
        } else {
            $result = [];
        }
        return $result;
    } catch (\think\Exception $exception) {
        return [];
    }
}


扫描二维码关注程序员爱笔记,接收更多资讯

评论

快速评论