2021-03-15 PHP使用openssl進行AES/CBC/PKCS5Padding加密

Java 算法需求

image.png

使用openssl進行AES/CBC/PKCS5Padding加密

問題解決了。

@openssl_encrypt($data, 'AES-128-CBC', $Key,OPENSSL_RAW_DATA);

iv不填寫直接加密,這樣子就行了
不過php會出現(xiàn)warning,在前面加一個@就可以了

php7 版 示例
ase.php

  <?php


namespace app\admin\model;


class Ase
{

    /**
     * [encrypt aes加密]
     * @param    [type]                   $input [要加密的數(shù)據(jù)]
     * @param    [type]                   $key   [加密key]
     * @return   [type]                          [加密后的數(shù)據(jù)]
     */
    public static function encrypt($input, $key)
    {
        $key = self::_sha1prng($key);
        $iv = '';
        $data = openssl_encrypt($input, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        $data = self::url_safe_b64encode($data);
        return $data;
    }

    /**
     * [decrypt aes解密]
     * @param    [type]                   $sStr [要解密的數(shù)據(jù)]
     * @param    [type]                   $sKey [加密key]
     * @return   [type]                         [解密后的數(shù)據(jù)]
     */
    public static function decrypt($sStr, $sKey)
    {
        $sKey = self::_sha1prng($sKey);
        $decrypted = openssl_decrypt(base64_decode($sStr), 'AES-128-ECB', $sKey, OPENSSL_RAW_DATA);
        return $decrypted;
    }

    /**
     * SHA1PRNG算法
     * @param  [type] $key [description]
     * @return [type]      [description]
     */
    private static function _sha1prng($key)
    {
        return substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
    }

    /**
     *url base64編碼
     * @param $string
     * @return string|string[]
     */
    private static  function url_safe_b64encode($string) {
        $data = base64_encode($string);
        $data = str_replace(array('+','/','='),array('-','_',''),$data);
        return $data;
    }

    /**
     * url base64解碼
     * @param $string
     * @return false|string
     */
    private static function url_safe_b64decode($string) {
        $data = str_replace(array('-','_'),array('+','/'),$string);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        return base64_decode($data);
    }
}

使用文件

        $jsonData = json_encode($data, JSON_UNESCAPED_UNICODE); //數(shù)組轉(zhuǎn)json Utf-8
        $appKeyHash = md5(self::$appKey);
        $checkCodeHash = md5($jsonData . self::$apiCode . self::$appKey);
        $jsonDataAES = Ase::encrypt(urlencode($jsonData), self::$appKey);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容