啥也不说,直接看代码

    1. <?php
    2. /**
    3. * 基于 AES-128-CBC PKCS7填充模式 的 加密解密类
    4. * @package aes
    5. */
    6. class MyCryptForAes128Cbc
    7. {
    8. private static $cipher = 'AES-128-CBC';
    9. private static $key = 'AES128CBC--PKCS7';
    10. private static $iv = 'AES128CBC--PKCS7';
    11. private static $options= OPENSSL_RAW_DATA;
    12. /**
    13. * 加密
    14. * @param $string
    15. * @return string
    16. */
    17. public static function encrypt($string){
    18. try {
    19. return bin2hex(base64_encode(openssl_encrypt($string, self::$cipher, self::$key, self::$options, self::$iv)));
    20. }catch (ErrorException $errorException){
    21. return '';
    22. }
    23. }
    24. /**
    25. * 解密
    26. * @param $string
    27. * @return string
    28. */
    29. public static function decrypt($string){
    30. try {
    31. $str = openssl_decrypt(base64_decode(pack('H*',$string)), self::$cipher, self::$key, self::$options, self::$iv);
    32. if ($str === false){
    33. //解密失败返回空
    34. $str = '';
    35. }
    36. if(self::encrypt($str) != $string){
    37. //经测试,通过上面加密函数加密后,在密文后面添加一些数据后也能解密出来
    38. //所以,解密出来的内容再进行加密,加密出的密文与参数的密文进行比较,不一致则返回空
    39. return '';
    40. }
    41. return $str;
    42. }catch (ErrorException $errorException){
    43. return '';
    44. }
    45. }
    46. }
    47. $d = '1234567890***...';
    48. echo $p = MyCryptForAes128Cbc::encrypt($d);
    49. echo PHP_EOL;
    50. echo $a = MyCryptForAes128Cbc::decrypt($p);

    测试一下:

    1. php index.php

    5943424f6a644e4a774b644761496a4b6f7534337142494f55527a324d7478392f5530634f6756414548383d
    1234567890*

    和Golang的互相转换可以参考:这里