加密解密

字符串加密解密支持。

引入相关类

  • use Leevel\Encryption\Encryption;
  • use Leevel\Encryption\IEncryption;

    加密解密基本功能

  1. public function testBaseUse()
  2. {
  3. $encryption = new Encryption('encode-key');
  4. $this->assertInstanceof(IEncryption::class, $encryption);
  5. $sourceMessage = '123456';
  6. $encodeMessage = $encryption->encrypt($sourceMessage);
  7. $this->assertFalse($sourceMessage === $encodeMessage);
  8. $this->assertSame(
  9. $encryption->decrypt($encodeMessage),
  10. $sourceMessage
  11. );
  12. $this->assertSame(
  13. $encryption->decrypt($encodeMessage.'foo'),
  14. ''
  15. );
  16. $this->assertSame(
  17. 'encode-key',
  18. $this->getTestProperty($encryption, 'key')
  19. );
  20. }

加密解密 AES-128-CBC

  1. public function testUse128()
  2. {
  3. $encryption = new Encryption('encode-key', 'AES-128-CBC');
  4. $this->assertInstanceof(IEncryption::class, $encryption);
  5. $sourceMessage = '123456';
  6. $encodeMessage = $encryption->encrypt($sourceMessage);
  7. $this->assertFalse($sourceMessage === $encodeMessage);
  8. $this->assertSame(
  9. $encryption->decrypt($encodeMessage),
  10. $sourceMessage
  11. );
  12. $this->assertSame(
  13. $encryption->decrypt($encodeMessage.'foo'),
  14. ''
  15. );
  16. $this->assertSame(
  17. 'encode-key',
  18. $this->getTestProperty($encryption, 'key')
  19. );
  20. }

加密解密支持过期时间

  1. public function testDecryptButExpired()
  2. {
  3. $encryption = new Encryption('encode-key');
  4. $this->assertInstanceof(IEncryption::class, $encryption);
  5. $data = $encryption->encrypt('123456', 1);
  6. $this->assertSame('123456', $encryption->decrypt($data));
  7. sleep(2);
  8. $this->assertSame('', $encryption->decrypt($data));
  9. }

加密解密支持 RSA 校验

  1. public function testWithPublicAndPrimaryKey()
  2. {
  3. $encryption = new Encryption(
  4. 'encode-key', 'AES-256-CBC',
  5. file_get_contents(__DIR__.'/assert/rsa_private_key.pem'),
  6. file_get_contents(__DIR__.'/assert/rsa_public_key.pem')
  7. );
  8. $this->assertInstanceof(IEncryption::class, $encryption);
  9. $sourceMessage = '123456';
  10. $encodeMessage = $encryption->encrypt($sourceMessage);
  11. $this->assertFalse($sourceMessage === $encodeMessage);
  12. $this->assertSame(
  13. $encryption->decrypt($encodeMessage),
  14. $sourceMessage
  15. );
  16. }