加密解密

Testing Is Documentation

tests/Encryption/EncryptionTest.php加密解密 - 图1

字符串加密解密支持。

Uses

  1. <?php
  2. use Leevel\Encryption\Encryption;
  3. use Leevel\Encryption\IEncryption;

加密解密基本功能

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