Skip to content

Commit

Permalink
Merge pull request #9 from xiashaung/master
Browse files Browse the repository at this point in the history
支持AES解密
  • Loading branch information
wi1dcard authored Mar 4, 2019
2 parents 44ff6ef + af8af64 commit 499c3f0
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
34 changes: 34 additions & 0 deletions aop/AopClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Alipay;

use Alipay\Exception\AlipayInvalidSignException;
use Alipay\Exception\AlipayOpenSslException;
use Alipay\Key\AlipayKeyPair;
use Alipay\Request\AbstractAlipayRequest;
use Alipay\Signer\AlipayRSA2Signer;
Expand Down Expand Up @@ -256,6 +257,39 @@ public function verify($params = null)
return true;
}

/**
* 解密被支付宝加密的敏感数据
*
* @param string $encryptedData Base64 格式的已加密的数据,如手机号
* @param string $encodedKey Base64 编码后的密钥
* @param string $cipher 解密算法,保持默认值即可
*
* @throws AlipayOpenSslException
*
* @return string
*
* @see https://docs.alipay.com/mini/introduce/aes
* @see https://docs.alipay.com/mini/introduce/getphonenumber
*/
public static function decrypt($encryptedData, $encodedKey, $cipher = 'aes-128-cbc')
{
$key = base64_decode($encodedKey);
if ($key === false) {
throw new AlipayBase64Exception($encodedKey);
}

if (!in_array($cipher, openssl_get_cipher_methods(), true)) {
throw new AlipayOpenSslException("Cipher algorithm {$cipher} not available");
}

$result = openssl_decrypt($encryptedData, $cipher, $key);
if ($result === false) {
throw new AlipayOpenSslException();
}

return $result;
}

/**
* 获取应用 ID
*
Expand Down
27 changes: 27 additions & 0 deletions tests/client/ClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,33 @@ public function testVerify(AopClient $client, $sign)
$this->assertFalse($result);
}

/**
* @depends testCreate
*/
public function testDecrypt(AopClient $client)
{
$result = $client->decrypt(
'h6qnRCccN8vR/IPtKYuTMIZUoDE9ZKp6pB2rrh4BMu8C7rS51ZZFn3aTlPl4i/RxvdS7SkJ+i49uDYfV+u5CKA==',
'ZXdCNW9ta1FsRGlVbzQ0TVdXbzJKN001dA=='
);

$this->assertEquals('{"code":"1000","msg":"success","mobile":"12777207727"}', $result);
}

/**
* @depends testCreate
*/
public function testDecryptException(AopClient $client)
{
$this->expectException('Alipay\Exception\AlipayOpenSslException');

$client->decrypt(
'h6qnRCccN8vR/IPtKYuTMIZUoDE9ZKp6pB2rrh4BMu8C7rS51ZZFn3aTlPl4i/RxvdS7SkJ+i49uDYfV+u5CKA==',
'ZXdCNW9ta1FsRGlVbzQ0TVdXbzJKN001dA==',
'non-existed-cipher'
);
}

/**
* @depends testCreate
*/
Expand Down

0 comments on commit 499c3f0

Please sign in to comment.