1. 程式人生 > >php-AES/CBC/PKCS7Padding加密的實現

php-AES/CBC/PKCS7Padding加密的實現

wan adding 註意 size 字節 openssl -a generic ase

php5模式

https://github.com/gunnzhao/AES-CBC-PKCS7Padding-/blob/master/AesCrypter.php

public function encrypt($orig_data) {
        $encrypter = mcrypt_module_open($this->algorithm, ‘‘,
            $this->mode, ‘‘);
        $orig_data = $this->pkcs7padding(
            $orig_data, mcrypt_enc_get_block_size($encrypter)
        );
        mcrypt_generic_init($encrypter, $this->key, substr($this->key, 0, 16));
        $ciphertext = mcrypt_generic($encrypter, $orig_data);
        mcrypt_generic_deinit($encrypter);
        mcrypt_module_close($encrypter);
        return base64_encode($ciphertext);
    }

  

php7模式:

$cipher = "aes-256-cbc";
        $key = hash(‘sha256‘,   ‘@parkingwang.com‘ , true);
        $encrypted = openssl_encrypt(json_encode($data), ‘AES-256-CBC‘, $key, 1, substr($key, 0, 16));
        $encrypt_msg = base64_encode($encrypted);

  

註意:加密後的字節碼使用Base64轉換成字符串

  • 加密模式: CBC
  • 填充模式: PKCS7Padding
  • 加密密鑰: 用戶密鑰 SHA256 的32 bytes
  • AES IV : 加密密鑰的前 16 bytes
  • Base 64: Base64.DEFAULT

加密過程:

加密:padding->CBC加密->base64編碼

解密:base64解碼->CBC解密->unpadding

AES加密結果基準測試:

用戶密鑰:

909ed2d5fcf907c79fb9aa341a98febb65291c39

明文:

AABBCC測試數據

密文:

noMrTUS2A0YTcYaaPQSy9peqF6Mv/faMkI4yYHDvKjw=

php-AES/CBC/PKCS7Padding加密的實現