为了防止提交到接口的明文泄密,可以对提交到接口的数据加密,可以用AES加密算法。微信公众平台官方API接口就是采用此算法。
加密方法:
所有提交过来的数据都使用AES加密算法+Base64(base64UrlEncode)算法加密:
1.AES加密参数:
加密模式:AES-128-ECB (可用更安全的aes-128-cbc-微信公众平台在用))
向量iv:空 (aes-128-cbc时需要)
密钥Key:“123456789”(请勿外泄)
填充:PKCS7(PKCS7与PKCS5结果一样)(微信公众平台用的是PKCS7填充)
- 加密步骤:
- 对数据进行AES加密。
- 对AES加密后的数据进行Base64(base64UrlEncode)加密。
3.加密示例:
1)原始数据:“hello world”
2)AES加密后数据:“bH� �G:9�i_x0005_��”
3)base64UrlEncode加密后数据:“ducL9jnRX1De2o15_xw6xg”
代码:
<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$key='123456789';
/**
* base64UrlEncode https://jwt.io/ 中base64UrlEncode编码实现
* @param string $input 需要编码的字符串
* @return string
*/
function base64UrlEncode($input)
{
return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
}
/**
* base64UrlEncode https://jwt.io/ 中base64UrlEncode解码实现
* @param string $input 需要解码的字符串
* @return bool|string
*/
function base64UrlDecode($input)
{
$remainder = strlen($input) % 4;
if ($remainder) {
$addlen = 4 - $remainder;
$input .= str_repeat('=', $addlen);
}
return base64_decode(strtr($input, '-_', '+/'));
}
$plaintext="hello world";
//$cipher = "aes-128-cbc";
$cipher = "aes-128-ecb";
if (in_array($cipher, openssl_get_cipher_methods()))
{
// $iv='1111111111111111';
$iv='';
$ciphertext = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_RAW_DATA, $iv);//如果去掉OPENSSL_RAW_DATA参数,则直接输出base64编码的,不用再base64编码
$ciphertext =base64UrlEncode($ciphertext);
//store $cipher, $iv, and $tag for decryption later
$original_plaintext = openssl_decrypt(base64UrlDecode($ciphertext), $cipher, $key, OPENSSL_RAW_DATA, $iv);
var_dump( $original_plaintext);
var_dump( $ciphertext);
}
另可见 http://blog.p2hp.com/archives/5446
https://github.com/w3yyb/API_Doc_Standard
原创文章,转载请注明,来自Lenix的博客,地址 http://blog.p2hp.com/archives/5459
最后更新于 2022年2月1日
相关博文
API接口加密方法


