How to encrypt and decrypt data

Some methods of the Key class in the Defuse\Crypto namespace

Method Description
createNewRandomKey() A static method that generates a new Key object.
saveToAsciiSafeString() A regular method that converts the Key object to an ASCII string.
loadFromAsciiSafeString($keyAscii) A static method that converts the ASCII string to a Key object.

Some methods of the Crypto class in the Defuse\Crypto namespace

Method Description
encrypt($data, $key) A static method that uses the specified Key object to encrypt the specified data.
decrypt($data, $key) A static method that uses the specified Key object to decrypt the specified data.
      require_once('/xampp/ph
      p/lib/defuse-crypto.phar'); 
      use Defuse\Crypto\Key;
      $key = Key::createNewRandomKey(); 
      $keyAscii = $key->saveToAsciiSafeString(); 
      file_put_contents('/xampp/php/defuse-key.txt', $keyAscii);
      

Code that encrypts and decrypts data

      require_once('/xampp/php/lib/defuse-crypto.phar'); 
      use Defuse\Crypto\Key; 
      use Defuse\Crypto\Crypto; 
      use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException; 
      
      // set up credit card variable 
      $credit_card_no = '4111111111111111'; 
      
      // get encryption key 
      $keyAscii = file_get_contents('/xampp/php/defuse-key.txt'); 
      $key = Key::loadFromAsciiSafeString($keyAscii); 
      
      // encrypt data 
      $encrypted_data = Crypto::encrypt($credit_card_no, $key); 
      echo("Encrypted data: $encrypted_data<br />>");

      // decrypt data 
      try {
        $decrypted_data = Crypto::decrypt($encrypted_data, $key); 
        echo("Decrypted data: $decrypted_data<br />>");
      } catch (WrongKeyOrModifiedCiphertextException $ex) { 
        echo("Exception: : . $ex->getMessage() . "<br />>'");
      }        
      

Back