> * 现有的php项目要慢慢过渡到go,有些业务需要php和go互相调用。现在有个问题就是:php这边有个加密解密的方法加密解密数据后发送给go 然后在go这边加密解密操作。php代码如下,go该怎么写对应的加密解密方法?
### php加密解密方法
```c
/**
* 加密
* @param $key
* @param $data
* @return array
*/
function encrypt($key, $data)
{
$iv_len = openssl_cipher_iv_length($cipher = "AES-128-CBC");
$iv = openssl_random_pseudo_bytes($iv_len);
$raw = openssl_encrypt($data, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv);
$h_mac = hash_hmac('sha256', $raw, $key, $as_binary = true);
$data = bin2hex($iv . $h_mac . $raw);
return $data;
}
/**
* 解密
* @param $key
* @param $data
* @return array
*/
function decrypt($key, $data)
{
$c = hex2bin($data);
$iv_len = openssl_cipher_iv_length($cipher = "AES-128-CBC");
$iv = substr($c, 0, $iv_len);
$h_mac = substr($c, $iv_len, $sha2len = 32);
$raw = substr($c, $iv_len + $sha2len);
$result = openssl_decrypt($raw, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv);
$calc_mac = hash_hmac('sha256', $raw, $key, $as_binary = true);
//PHP 5.6+ timing attack safe comparison
if (!hash_equals($h_mac, $calc_mac)) {
$result = "";
}
return $result;
}
$key = 'K_Z(;l,8Zl-xNzwh|X3IJm{
$data = 'hello world';
echo $res = encrypt($key, $data), "\n";
echo decrypt($key, $res), "\n";
/**
输出
504d72428a9deb390b092f43b923034a790a8daf82a462042e2cc97fc94c94c767c7c63c85a970544780e29d2f3630f63e02b796c4f65d5fccdc0a1205cf7990
hello world
*/
```
感谢,感谢
有疑问加站长微信联系(非本文作者)