Skip to content

Instantly share code, notes, and snippets.

@tharsheblows
Last active June 30, 2020 14:51
Show Gist options
  • Save tharsheblows/d7c8152fd98af1391b3e65e72381b713 to your computer and use it in GitHub Desktop.
Save tharsheblows/d7c8152fd98af1391b3e65e72381b713 to your computer and use it in GitHub Desktop.
<?php
namespace Lalala\Src;
use \Defuse\Crypto\Crypto;
use \Defuse\Crypto\Key;
use Lalala\Src\Debug\Logging;
/**
* Wrapper class for encryption.
*
* To save a key: run vendor/bin/generate-defuse-key then save it to wp config using WP CLI.
*/
class Encryption {
/**
* The text to encrypt.
*
* @var string
*/
public $text;
/**
* Construct the function.
*
* @param string $text
*/
public function __construct( $text ) {
$this->text = $text; // The text to encrypt.
$this->logging = new Logging(); // Logging.
}
/**
* Makes the key used in encrypting and decrypting.
*
* @return object The Key object.
*/
private function make_key(){
if ( ! defined( 'LALALA_ENCRYPT_KEY' ) ) {
return false;
}
return Key::loadFromAsciiSafeString( LALALA_ENCRYPT_KEY );
}
/**
* Encrypts the text.
*
* @return string|false The encrypted string or false if something has failed.
*/
public function encrypt(){
try{
$encrypted = Crypto::encrypt( $this->text, $this->make_key() );
} catch( \TypeError $e ){
$this->logging->log( $e );
return false;
}
return $encrypted;
}
/**
* Decrypts the text.
*
* @return string|false The encrypted string or false if something has failed.
*/
public function decrypt(){
try{
$decrypted = Crypto::decrypt( $this->text, $this->make_key() );
} catch( \TypeError $e ){
$this->logging->log( $e );
return false;
}
return $decrypted;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment