简体   繁体   中英

AES encryption using phpseclib

Can someone help me with AES? I've used phpseclib in encrypting and decrypting the data, however, it seems that it couldn't decrypt the data. see my code below. I wanted to decrypt the data on other pages. Thanks in advance!

$base64 = "AAA";

$cipher = new Crypt_AES(); 
$cipher->setKey('QrzMwvH7zmVn5Kzu%ks8GSTWzyLJu#Ck!^f%-UpXefuYBhv^%qLwYsuPx0d&zmNo');
$cipher->setIV(crypt_random_string($cipher->getBlockLength() >> 3));
echo $encrypted = $cipher->encrypt($base64); 


$cipher = new Crypt_AES(); 
$cipher->setKey('QrzMwvH7zmVn5Kzu%ks8GSTWzyLJu#Ck!^f%-UpXefuYBhv^%qLwYsuPx0d&zmNo');
$cipher->setIV(crypt_random_string($cipher->getBlockLength() >> 3));
echo 'decrypted:'.  $cipher->decrypt($encrypted);

Result

% NK y 0 k :decrypted:

Update:

Does this mean that It's necessary to keep a list of Initialization Vector in order to decrypt the data?

Update:

I've decided to use Lumen Framework. Lumen has a built-in encrpytion feature that handles IV and other encyrption technical stuff. Thanks for your help!

You're using a different IV in both cases - you need to be using the same IV. Try this:

$base64 = "AAA";
$iv = crypt_random_string($cipher->getBlockLength() >> 3);

$cipher = new Crypt_AES(); 
$cipher->setKey('QrzMwvH7zmVn5Kzu%ks8GSTWzyLJu#Ck!^f%-UpXefuYBhv^%qLwYsuPx0d&zmNo');
$cipher->setIV($iv);
echo $encrypted = $cipher->encrypt($base64); 


$cipher = new Crypt_AES(); 
$cipher->setKey('QrzMwvH7zmVn5Kzu%ks8GSTWzyLJu#Ck!^f%-UpXefuYBhv^%qLwYsuPx0d&zmNo');
$cipher->setIV($iv);
echo 'decrypted:'.  $cipher->decrypt($encrypted);

Use a randomly generated IV for encryption. The IV does not need to be secret so just prefix the encrypted data with the IV. Then the IV is available for decryption.

The encryption key 'QrzMwvH7zmVn5Kzu%ks8GSTWzyLJu#Ck!^f%-UpXefuYBhv^%qLwYsuPx0d&zmNo' is 512-bits (64-bytes) but there are only three AES key sizes: 128, 192 and 256 bits.

You are using a library. Why don't you use openssl_encrypt() ?

For Encrypting:

openssl_encrypt($text, $method, $key);

Parameters:

  1. $text : The Text You Want To Encrypt.
  2. $method : The method you will use for encrypting. I use AES-256-ECB mostly.
  3. $key : The key you use for encrypting.

Example:

$data = openssl_encrypt('Hello', 'AES-256-ECB' 'test');

Decrypting:

openssl_decrypt($encrypted_text, $method, $key);

Parameters:

  1. $encrypted_text : The Text Encrypted.
  2. $method : The method you will use for decrypting.
  3. $key : The key to decrypt the text.

Example:

openssl_decrypt($data, 'AES-256-ECB', 'test');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM