PHP常见的加密方式

PHP常见的加密方式

<?php


/**
 * 对数据根据字符串进行asc加密
 * @param array   curlData     加密数组
 * @param string   rands     加密字符串
 * @return string  date   加密后的字符串
 * @author lyx     2019-06-19
 */
function ascEncrypt($curlData,$rands){
    $screct_key = $rands;
    $str = trim(json_encode($curlData));

    $str = addPKCS7Padding($str);

    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_ECB),MCRYPT_RAND);
    $encrypt_str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_ECB, $iv);
    $date = base64_encode($encrypt_str);

    return $date;
}




/**
 * 对数据根据字符串进行asc解密
 * @param array   curlData     加密数组
 * @param string   rands     加密字符串
 * @return string  date   加密后的字符串
 * @author lyx     2019-06-19
 */
function ascEC($date,$rands){
    $date = base64_decode($date);
    $screct_key = $rands;
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_ECB),MCRYPT_RAND);
    $encrypt_str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $screct_key, $date, MCRYPT_MODE_ECB, $iv);
    $encrypt_str = preg_replace('/[x00-x1F]/','', $encrypt_str);
    $encrypt_str = json_decode($encrypt_str,true);
    return $encrypt_str;
}





/**
 * 对加密字符串进行公钥加密
 * @param string   rands     加密字符串
 * @return string  encryptKey   加密后的字符串
 * @author lyx     2019-06-19
 */
function haveEncryptKey($rands)
{

    $encryptKey = file_get_contents('公钥文件地址');
    $pem = chunk_split(base64_encode($encryptKey), 64, "
");//转换为 pem 格式的公钥
    $public_key = "-----BEGIN CERTIFICATE-----
" . $pem . "-----END CERTIFICATE-----
";
    $pu_key = openssl_pkey_get_public($public_key);
    openssl_public_encrypt($rands, $encrypted, $pu_key);
    $encryptKey = base64_encode($encrypted);
    return $encryptKey;
}

/**
 * 对数据进行公钥验签
 * @param array   data     需要验证的数组
 * @param array   hmac     签名
 * @return result   空为错误,1为正确
 * @author lyx     2019-06-19
 */
function rsaPubilcSign($data,$hmac){
    $public_key=file_get_contents(‘公钥文件地址’);
    $pem1 = chunk_split(base64_encode($public_key),64,"
");
    $pem1 = "-----BEGIN CERTIFICATE-----
".$pem1."-----END CERTIFICATE-----
";
    $pi_key =  openssl_pkey_get_public($pem1);
    $result=openssl_verify($data,base64_decode($hmac),$pem1,OPENSSL_ALGO_MD5);
    return $result;

}



/**
 * 四要素验证  - 首信易
 * @param string bankcard 银行卡
 * @param array  idcard 身份证号
 * @param array  mobile 手机号
 * @param array  truename 真实姓名
 * @param array  errStr 错误信息
 * @return string
 */
function fourElementCheck($bankcard,$idcard,$mobile,$truename,&$errStr){


    //四要素验证
    $host = "https://bankcard4.shumaidata.com";
    $path = "/bank_card4/verify";
    $method = "POST";
    $appcode = "9517bdaef7cd4f578b8e90ea9a342c29";
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    //根据API的要求,定义相对应的Content-Type
    array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
    $querys = "";
    $bodys = "bankcard=".$bankcard."&idcard=".$idcard."&mobile=".$mobile."&name=".$truename;
    $url = $host . $path;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    if (1 == strpos("$".$host, "https://"))
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);

    $result = curl_exec($curl);
    $result = substr($result,strpos($result,"{"));
    $result = json_decode($result,true);

    if($result['code'] != 0 || $result['result']['description'] != '认证信息匹配'){
        $result['result']['description'] = isset($result['result']['description']) ? $result['result']['description'] : $result['message'];
        $errStr = $result['result']['description'];
        if($errStr == '无法验证'){
            return true;
        }
        return false;
    }else{
        return true;
    }
}



/**
 * discuz!金典的加密函数原版      需要URL转码   urlencode ( );
 * @param string $string 明文 或 密文
 * @param string $operation DECODE表示解密,其它表示加密
 * @param string $key 密匙
 * @param int $expiry 密文有效期
 */
function authcode($string, $operation = 'ENCODE', $key = '', $expiry = 0)
{
    // 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙
    if ($operation == 'DECODE') {
        $string = str_replace('[a]', '+', $string);
        $string = str_replace('[b]', '&', $string);
        $string = str_replace('[c]', '/', $string);
    }
    $ckey_length = 4;

    // 密匙
    $key = md5($key ? $key : 'unbhytvfrqazxswolmkiujnhybgtrvfedcxdewsxzaq'); // AUTH_KEY 项目配置的密钥 	hinkConfig::get('auth_key')

    // 密匙a会参与加解密
    $keya = md5(substr($key, 0, 16));
    // 密匙b会用来做数据完整性验证
    $keyb = md5(substr($key, 16, 16));
    // 密匙c用于变化生成的密文
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
    // 参与运算的密匙
    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);
    // 明文,前10位用来保存时间戳,解密时验证数据有效性,10到26位用来保存$keyb(密匙b),解密时会通过这个密匙验证数据完整性
    // 如果是解码的话,会从第$ckey_length位开始,因为密文前$ckey_length位保存 动态密匙,以保证解密正确
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    // 产生密匙簿
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    // 用固定的算法,打乱密匙簿,增加随机性,好像很复杂,实际上对并不会增加密文的强度
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    // 核心加解密部分
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        // 从密匙簿得出密匙进行异或,再转成字符
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if ($operation == 'DECODE') {
        // substr($result, 0, 10) == 0 验证数据有效性
        // substr($result, 0, 10) - time() > 0 验证数据有效性
        // substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16) 验证数据完整性
        // 验证数据有效性,请看未加密明文的格式
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        }   {
            return '';
        }
    }   {
        // 把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因
        // 因为加密后的密文可能是一些特殊字符,复制过程可能会丢失,所以用base64编码
        $ustr = $keyc . str_replace('=', '', base64_encode($result));
        $ustr = str_replace('+', '[a]', $ustr);
        $ustr = str_replace('&', '[b]', $ustr);
        $ustr = str_replace('/', '[c]', $ustr);
        return $ustr;
    }
}



/**
 * 保存二进制,base64图片
 * @param string $data 图片数据
 * @param string $type 图片类型
 * @param string $path 保存路径
 * @return string 图片保存路径
 */
function save_base64_image($data, $type = 'png', $path = 'upload')
{
    $dirname = $path . '/' . date('Ymd') . '/';
    if (preg_match('/^(data:s*image/(w+);base64,)/', $data, $result)) {
        $type = $result[2];
        $data = base64_decode(str_replace($result[1], '', $data));
    }   {

    }
    if (!file_exists($dirname)) {
        //检查是否有该文件夹,如果没有就创建,并给予最高权限
        mkdir($dirname, 0755);
    }
    $file = $dirname . md5(time() . rand(0, 99999)) . '.' . $type;
    if (file_put_contents($file, $data)) {
        return '/' . $file;
    }   {
        return false;
    }
}



/**
 * 图片转base64
 * @param $image_file
 * @return string
 */
function image_to_base64($image_file)
{
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}
原文地址:https://www.cnblogs.com/ccw869476711/p/12853577.html