I am encrypting a string using following class (using inheritance)
class UnsafeCrypto {
const METHOD = 'aes-256-ctr';
/**
* Encrypts (but does not authenticate) a message
*
* #param string $message - plaintext message
* #param string $key - encryption key (raw binary expected)
* #param boolean $encode - set to TRUE to return a base64-encoded
* #return string (raw binary)
*/
public static function encrypt($message, $key, $encode = false)
{
$nonceSize = openssl_cipher_iv_length(self::METHOD);
$nonce = openssl_random_pseudo_bytes($nonceSize);
$ciphertext = openssl_encrypt(
$message,
self::METHOD,
$key,
OPENSSL_RAW_DATA,
$nonce
);
// Now let's pack the IV and the ciphertext together
// Naively, we can just concatenate
if ($encode) {
return base64_encode($nonce.$ciphertext);
}
return $nonce.$ciphertext;
}
/**
* Decrypts (but does not verify) a message
*
* #param string $message - ciphertext message
* #param string $key - encryption key (raw binary expected)
* #param boolean $encoded - are we expecting an encoded string?
* #return string
*/
public static function decrypt($message, $key, $encoded = false)
{
if ($encoded) {
$message = base64_decode($message, true);
if ($message === false) {
throw new Exception('Encryption failure');
}
}
$nonceSize = openssl_cipher_iv_length(self::METHOD);
$nonce = mb_substr($message, 0, $nonceSize, '8bit');
$ciphertext = mb_substr($message, $nonceSize, null, '8bit');
$plaintext = openssl_decrypt(
$ciphertext,
self::METHOD,
$key,
OPENSSL_RAW_DATA,
$nonce
);
return $plaintext;
}
}
Inheriting the class as below.
class SaferCrypto extends UnsafeCrypto {
const HASH_ALGO = 'sha256';
/**
* Encrypts then MACs a message
*
* #param string $message - plaintext message
* #param string $key - encryption key (raw binary expected)
* #param boolean $encode - set to TRUE to return a base64-encoded string
* #return string (raw binary)
*/
public static function encrypt($message, $key, $encode = false)
{
list($encKey, $authKey) = self::splitKeys($key);
// Pass to UnsafeCrypto::encrypt
$ciphertext = parent::encrypt($message, $encKey);
// Calculate a MAC of the IV and ciphertext
$mac = hash_hmac(self::HASH_ALGO, $ciphertext, $authKey, true);
if ($encode) {
return base64_encode($mac.$ciphertext);
}
// Prepend MAC to the ciphertext and return to caller
return $mac.$ciphertext;
}
/**
* Decrypts a message (after verifying integrity)
*
* #param string $message - ciphertext message
* #param string $key - encryption key (raw binary expected)
* #param boolean $encoded - are we expecting an encoded string?
* #return string (raw binary)
*/
public static function decrypt($message, $key, $encoded = false)
{
list($encKey, $authKey) = self::splitKeys($key);
if ($encoded) {
$message = base64_decode($message, true);
if ($message === false) {
throw new Exception('Encryption failure');
}
}
// Hash Size -- in case HASH_ALGO is changed
$hs = mb_strlen(hash(self::HASH_ALGO, '', true), '8bit');
$mac = mb_substr($message, 0, $hs, '8bit');
$ciphertext = mb_substr($message, $hs, null, '8bit');
$calculated = hash_hmac(
self::HASH_ALGO,
$ciphertext,
$authKey,
true
);
if (!self::hashEquals($mac, $calculated)) {
throw new Exception('Encryption failure');
}
// Pass to UnsafeCrypto::decrypt
$plaintext = parent::decrypt($ciphertext, $encKey);
return $plaintext;
}
/**
* Splits a key into two separate keys; one for encryption
* and the other for authenticaiton
*
* #param string $masterKey (raw binary)
* #return array (two raw binary strings)
*/
protected static function splitKeys($masterKey)
{
// You really want to implement HKDF here instead!
return [
hash_hmac(self::HASH_ALGO, 'ENCRYPTION', $masterKey, true),
hash_hmac(self::HASH_ALGO, 'AUTHENTICATION', $masterKey, true)
];
}
/**
* Compare two strings without leaking timing information
*
* #param string $a
* #param string $b
* #ref https://paragonie.com/b/WS1DLx6BnpsdaVQW
* #return boolean
*/
protected static function hashEquals($a, $b)
{
if (function_exists('hash_equals')) {
return hash_equals($a, $b);
}
$nonce = openssl_random_pseudo_bytes(32);
return hash_hmac(self::HASH_ALGO, $a, $nonce) === hash_hmac(self::HASH_ALGO, $b, $nonce);
}
}
Encrypting string as follow.
$email = 'myemail#domain.com';
$key = 'Some key';
$encrypted_email = $encrypted = SaferCrypto::encrypt($message, $key);
String is getting encrypted like this:
óÜCu!>Ò·<x0½“—J ‡l¿Ø ;ƒ;›OøVP#ï 1 Sjñ,(ñúrÛòv–~ºyÍg ÷–´´iƒû
If I pass this with urlencode($string) data is not getting decrypted because hash is not matching because hashEquals method is throwing exception.
What is the proper way to pass encrypted string in GET request?
It's not clear, what is the problem, but you can use base64_encode($encrypted_email) to pass your string as smth like HDo1FaXabDHjfxBkpx7YBHNGVeZ/G8FvI2BoxES2rUu3lvNWRo5G0PImiv9IhENv.
link
When receiving, decode it
$encrypted_email = base64_decode($_GET['enc']);
Related
Libraries code I get from https://github.com/b3457m0d3/JWT-CodeIgniter
and I have to create login API in that i want to generate token valid for certain time only.
**comtroller
<?php
require APPPATH.'libraries/REST_Controller.php';
class Comx extends REST_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('cookie');
$this->load->library('jwt');
}
public function generate_token($user_id)
{
//$this->load->library("jwt");
$CONSUMER_KEY = '124578';
$CONSUMER_SECRET = '456123';
$CONSUMER_TTL = 60;
var_dump( $this->jwt->encode(array(
'consumerKey'=>$CONSUMER_KEY,
'userId'=>$user_id,
'issuedAt'=>date(DATE_ISO8601, strtotime("now")),
'ttl'=>$CONSUMER_TTL
), $CONSUMER_SECRET));
}
**
// application/ libraries/jwt.php but this code give me error on line 89 of controller Undefined property: Comx::$JWT ?is it can not load library
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* JSON Web Token implementation
*
* Minimum implementation used by Realtime auth, based on this spec:
* http://self-issued.info/docs/draft-jones-json-web-token-01.html.
*
* #author Neuman Vong <neuman#twilio.com>
* #minor changes for codeigniter <b3457m0d3#interr0bang.net>
*/
class JWT
{
/**
* #param string $jwt The JWT
* #param string|null $key The secret key
* #param bool $verify Don't skip verification process
*
* #return object The JWT's payload as a PHP object
*/
public function decode($jwt, $key = null, $verify = true)
{
$tks = explode('.', $jwt);
if (count($tks) != 3) {
throw new UnexpectedValueException('Wrong number of segments');
}
list($headb64, $payloadb64, $cryptob64) = $tks;
if (null === ($header = $this->jsonDecode($this->urlsafeB64Decode($headb64)))
) {
throw new UnexpectedValueException('Invalid segment encoding');
}
if (null === $payload = $this->jsonDecode($this->urlsafeB64Decode($payloadb64))
) {
throw new UnexpectedValueException('Invalid segment encoding');
}
$sig = $this->urlsafeB64Decode($cryptob64);
if ($verify) {
if (empty($header->alg)) {
throw new DomainException('Empty algorithm');
}
if ($sig != $this->sign("$headb64.$payloadb64", $key, $header->alg)) {
throw new UnexpectedValueException('Signature verification failed');
}
}
return $payload;
}
/**
* #param object|array $payload PHP object or array
* #param string $key The secret key
* #param string $algo The signing algorithm
*
* #return string A JWT
*/
public function encode($payload, $key, $algo = 'HS256')
{
$header = array('typ' => 'jwt', 'alg' => $algo);
$segments = array();
$segments[] = $this->urlsafeB64Encode($this->jsonEncode($header));
$segments[] = $this->urlsafeB64Encode($this->jsonEncode($payload));
$signing_input = implode('.', $segments);
$signature = $this->sign($signing_input, $key, $algo);
$segments[] = $this->urlsafeB64Encode($signature);
return implode('.', $segments);
}
/**
* #param string $msg The message to sign
* #param string $key The secret key
* #param string $method The signing algorithm
*
* #return string An encrypted message
*/
public function sign($msg, $key, $method = 'HS256')
{
$methods = array(
'HS256' => 'sha256',
'HS384' => 'sha384',
'HS512' => 'sha512',
);
if (empty($methods[$method])) {
throw new DomainException('Algorithm not supported');
}
return hash_hmac($methods[$method], $msg, $key, true);
}
/**
* #param string $input JSON string
*
* #return object Object representation of JSON string
*/
public function jsonDecode($input)
{
$obj = json_decode($input);
if (function_exists('json_last_error') && $errno = json_last_error()) {
$this->handleJsonError($errno);
}
else if ($obj === null && $input !== 'null') {
throw new DomainException('Null result with non-null input');
}
return $obj;
}
/**
* #param object|array $input A PHP object or array
*
* #return string JSON representation of the PHP object or array
*/
public function jsonEncode($input)
{
$json = json_encode($input);
if (function_exists('json_last_error') && $errno = json_last_error()) {
$this->handleJsonError($errno);
}
else if ($json === 'null' && $input !== null) {
throw new DomainException('Null result with non-null input');
}
return $json;
}
/**
* #param string $input A base64 encoded string
*
* #return string A decoded string
*/
public function urlsafeB64Decode($input)
{
$remainder = strlen($input) % 4;
if ($remainder) {
$padlen = 4 - $remainder;
$input .= str_repeat('=', $padlen);
}
return base64_decode(strtr($input, '-_', '+/'));
}
/**
* #param string $input Anything really
*
* #return string The base64 encode of what you passed in
*/
public function urlsafeB64Encode($input)
{
return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
}
/**
* #param int $errno An error number from json_last_error()
*
* #return void
*/
private function handleJsonError($errno)
{
$messages = array(
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
);
throw new DomainException(isset($messages[$errno])
? $messages[$errno]
: 'Unknown JSON error: ' . $errno
);
}
}
This question already has answers here:
Where should I store an encryption key for php?
(5 answers)
Closed 6 years ago.
I'm using this php function to encrypt some strings.
openssl_encrypt();
To generate the encryption key I use
$encryption_key = openssl_random_pseudo_bytes(32);
I also know that this encryption key should be stored somewhere.
The problem is that I don't want to store it in my database, because it could be accessible for hackers.
Where could I also store my keys safely?
P.S. It makes any sense to store encrypted data and used keys in the same database
Here's an example encryption class I created in PHP. The encryption key is stored in this class, which can then be used to decrypt encrypted DB values. Hope this helps.
/**
* Provides basic encryption and decryption of strings and objects.
* Reasonable protection is provided, but you are still responsible
* for sanitizing the source strings or objects prior to use.
*/
class Encrypter {
/**
* This is the global encryption key for the site.
* The longer you make this key, the more secure the encryption
*/
const MASTER_KEY = 'my_amazing_key_of_death';
private $key;
private $cipher;
private $mode;
private $iv;
private $iv_size;
private $key_size;
private $block_size;
public function __construct() {
$this->key = self::MASTER_KEY
$this->cipher = MCRYPT_BLOWFISH;
$this->mode = MCRYPT_MODE_CBC;
$this->block_size = mcrypt_get_block_size($this->cipher);
$this->iv_size = mcrypt_get_iv_size($this->cipher, $this->mode);
$this->key_size = mcrypt_get_key_size($this->cipher, $this->mode);
$this->iv = mcrypt_create_iv($this->iv_size, MCRYPT_RAND);
/**
* if the calculated keysize is shorter than
* they key provided, trim the provided key
* to match its length
*/
if (strlen($this->key) > $this->key_size) {
$this->key = substr($this->key, 0, $this->key_size);
}
}
/**
* Static method alias for string encryption
* #param string $string The string to encrypt
* #return string The encrypted string
*/
public static function enc($string) {
$e = new self;
return $e->encrypt_string($string);
}
/**
* Static method alias for string decryption
* #param string $enc_string The previously encrypted string
* #return string The decrypted/original string
*/
public static function dec($enc_string) {
$e = new self;
return $e->decrypt_string($enc_string);
}
/**
* Encrypt a string
* #param string $string - string to encrypt
* #return string - encrypted string
*/
function encrypt_string($string) {
$enc = mcrypt_encrypt(
$this->cipher,
$this->key,
$string,
$this->mode,
$this->iv
);
$enc = base64_encode($this->iv . $enc);
/**
* replace potentially illegal chars
*/
$enc = strtr($enc, '+/=', '-_,');
/**
* remove unnecessary and ugly trailing commas
*/
$enc = strrev($enc);
if(substr($enc,0,1) == ',') $enc = substr($enc,1);
if(substr($enc,0,1) == ',') $enc = substr($enc,1);
$enc = strrev($enc);
return $enc;
}
/**
* Decrypt an encrypted string and return the original
* #param string $s The string previously encrypted with this class
* #return string The original unencrypted string
*/
function decrypt_string($s) {
$s = strtr($s, '-_,', '+/=');
$s = base64_decode($s);
$this->iv_size = mcrypt_get_iv_size($this->cipher, $this->mode);
$this->iv = substr($s, 0, $this->iv_size);
$data = substr($s, $this->iv_size);
/**
* supress warnings because they happen every time
* IV parameter must be as long as the block size
* yet this still works perfectly
*/
$decrypted = #mcrypt_decrypt($this->cipher, $this->key, $data, $this->mode, $this->iv);
return trim($decrypted);
}
/**
* Serialize an object into an encrypted string
* #throws Exception
* #param object $object
* #return string
*/
function encrypt_object($object) {
if(is_resource($object)) throw new Exception("Cannot encrypt objects of type 'resource'");
$ser = serialize($object);
$enc = base64_encode($ser);
return $this->encrypt_string($enc);
}
/**
* Unserialize an encrypted string back into an object
* #param string $enc
* #return object
*/
function decrypt_object($enc) {
$dec = $this->decrypt_string($enc);
$unenc = base64_decode($dec);
return unserialize($unenc);
}
}
Using this article as a guide I was able to successfully replicate MySQL's aes-128-ecb in PHP:
final class Encryption
{
// The key
const KEY = '36F3D40A7A41A827968BE75A87D60950';
/**
* Encrypt a string
*
* #access public
* #static
* #param string $string
* #return string
*/
public static function encrypt($string)
{
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, self::getMySQLKey(self::KEY), self::getPaddedString($string), MCRYPT_MODE_ECB);
}
/**
* Decrypt a string
*
* #access public
* #static
* #param string $string
* #return string
*/
public static function decrypt($string)
{
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, self::getMySQLKey(self::KEY), $string, MCRYPT_MODE_ECB), "\x00..\x10");
}
/**
* Get MySQL key
*
* #access public
* #static
* #param string $key
* #return string
*/
public static function getMySQLKey($key)
{
// The new key
$new_key = str_repeat(chr(0), 16);
// Iterate over the key and XOR
for ($i = 0, $l = strlen($key); $i < $l; ++$i)
{
$new_key[$i % 16] = $new_key[$i % 16] ^ $key[$i];
}
// Return the new key
return $new_key;
}
/**
* Get padded string
*
* #access public
* #static
* #param string $string
* #return string
*/
public static function getPaddedString($string)
{
return str_pad($string, (16 * (floor(strlen($string) / 16) + 1)), chr(16 - (strlen($string) % 16)));
}
}
As an example:
// PHP, gives CJI+zJyviQI7GgSCLGMNsqsXq2MDKC3a9FIG3wDrE8Y=
base64_encode(Encryption::encrypt('michael#example.com'))
// MySQL, gives CJI+zJyviQI7GgSCLGMNsqsXq2MDKC3a9FIG3wDrE8Y=
SELECT TO_BASE64(AES_ENCRYPT('michael#example.com', '36F3D40A7A41A827968BE75A87D60950'));
However, I want to update to using aes-256-cbc but am having difficulties. I started by replacing MCRYPT_RIJNDAEL_128 with MCRYPT_RIJNDAEL_256 and MCRYPT_MODE_ECB with MCRYPT_MODE_CBC and used the KEY constant as the initialization vector:
/**
* Encrypt a string
*
* #access public
* #static
* #param string $string
* #return string
*/
public static function encrypt($string)
{
return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, self::getMySQLKey(self::KEY), self::getPaddedString($string), MCRYPT_MODE_CBC, self::KEY);
}
/**
* Decrypt a string
*
* #access public
* #static
* #param string $string
* #return string
*/
public static function decrypt($string)
{
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, self::getMySQLKey(self::KEY), $string, MCRYPT_MODE_CBC, self::KEY), "\x00..\x10");
}
The problem is that I'm now getting different values from PHP and MySQL:
// PHP, gives XSRfnrl05CE7JIHCvfhq6D67O0mAW2ayrFv2YkjFVYI=
base64_encode(Encryption::encrypt('michael#example.com'))
// MySQL, gives lTLT4MRXcHnOAsYjlwUX4WVPHgYvyi6nKC4/3us/VF4=
SELECT TO_BASE64(AES_ENCRYPT('michael#example.com', '36F3D40A7A41A827968BE75A87D60950', '36F3D40A7A41A827968BE75A87D60950'));
I'm unsure where to proceed from here so any help would be appreciated.
And just to confirm that MySQL is indeed using the correct encryption method:
// aes-256-cbc
SELECT ##session.block_encryption_mode
AES is a subset of Rijndael so to use it for AES one must select a block size of 128-bits and a key size of 128, 192 or 256 bits.
MCRYPT_RIJNDAEL_256 specifies a block size of 256-bits, not the key size, similarly MCRYPT_RIJNDAEL_128 specifies a block size of 128-bits, not the key size. This is a common confusion.
This implementation of Rijndael auto selects a key size based on the passed key so it is important to use a key of exactly the correct desired size.
Also note that the iv length is the same as the block size so for AES it is 128-bits in length.
This is a good example of how poor naming can have unfortunate consequences.
As neither eggyal nor Artjom B. have chosen to provide an answer with their solution, I'll do so on their behalf.
The first issue is that AES-256 still uses MCRYPT_RIJNDAEL_128 rather than MCRYPT_RIJNDAEL_256, and the second is that AES-256 is used over AES-128 by providing a 32 byte key rather than a 16 byte key.
The below provides a correct implementation:
final class AESEncrypter
{
// The key
const KEY = 'F40E2A9E22150793C6D0CA9E316FEA42';
// The IV
const IV = '5C354934224F698E';
/**
* Encrypt a string
*
* #access public
* #static
* #param string $string
* #return string
*/
public static function encrypt($string)
{
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, self::getMySQLKey(self::KEY), self::getPaddedString($string), MCRYPT_MODE_CBC, self::IV);
}
/**
* Decrypt a string
*
* #access public
* #static
* #param string $string
* #return string
*/
public static function decrypt($string)
{
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, self::getMySQLKey(self::KEY), $string, MCRYPT_MODE_CBC, self::IV), "\x00..\x10");
}
/**
* Get MySQL key
*
* #access public
* #static
* #param string $key
* #return string
*/
public static function getMySQLKey($key)
{
// The new key
$new_key = str_repeat(chr(0), 32);
// Iterate over the key and XOR
for ($i = 0, $l = strlen($key); $i < $l; ++$i)
{
$new_key[$i % 32] = $new_key[$i % 32] ^ $key[$i];
}
// Return the new key
return $new_key;
}
/**
* Get padded string
*
* #access public
* #static
* #param string $string
* #return string
*/
public static function getPaddedString($string)
{
return str_pad($string, (16 * (floor(strlen($string) / 16) + 1)), chr(16 - (strlen($string) % 16)));
}
}
As an example:
// PHP, gives mwVraDh/7jG3BvPJyYqgxY6Ca8CTRN5JHvwPGeV8Vd0=
base64_encode(AESEncrypter::encrypt('michael#example.com'))
// MySQL, gives mwVraDh/7jG3BvPJyYqgxY6Ca8CTRN5JHvwPGeV8Vd0=
SELECT TO_BASE64(AES_ENCRYPT('michael#example.com', 'F40E2A9E22150793C6D0CA9E316FEA42', '5C354934224F698E'))
I've got the following class.
<?php
/**
* Cypher Class
*/
class Cipher
{
/**
* SHA256 Encrypted Key
* #var string
*/
private $encryptedKey;
/**
* Initial vector
*
* Used to seed the encryption string
*
* #var string
*/
private $initVector;
/**
* Constructor
* #param boolean|string $personalKey Holds the personal key to use in encryption
*/
public function __construct($personalKey = false)
{
// $config = configuration::getInstance();
if (false === $personalKey) {
return false;
} else {
$key = $personalKey;
}
$this->encryptionKey = hash('sha256', $key, TRUE);
$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CFB);
$this->initVector = mcrypt_create_iv($size, MCRYPT_DEV_URANDOM);
}
/**
* Encrypt a string
* #param mixed $input Data to encrypt
* #return string Encrypted data
*/
public function encrypt($input)
{
return array(
'salt' => base64_encode($this->initVector),
'encrypted_value' => base64_encode(mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
$this->encryptionKey,
$input,
MCRYPT_MODE_CFB,
$this->initVector
)));
}
/**
* Decrypt string
* #param string $input Encrypted string we are going to decrypt
* #param string $salt Encrypted salt used to decrypt
* #return string Decrypted output
*/
public function decrypt($input, $salt)
{
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->encryptionKey, base64_decode($input), MCRYPT_MODE_CFB, $salt));
}
}
Both my IV and encrypted string are 16 bytes but for some reason PHP gives me the following error:
Warning: mcrypt_encrypt(): The IV parameter must be as long as the blocksize in C:\xampp\htdocs\public\cipher\Cipher.php on line 58
I am not really a star in encryptions and so I was wondering if one of you good people could help me out.
The size of an IV is related to the block size of the cipher. So whatever you choose as the block size must be used as the length of the IV.
Rijndael supports block sizes of 128, 160, 192, 224, and 256 bits. If you use MCRYPT_RIJNDAEL_128 then you are using the 128-bit block size (which matches AES). If you use MCRYPT_RIJNDAEL_256 then your block-size is twice as large.
So, you must decide which block size you want to use and ensure your code consistently refers to the same MCRYPT_RIJNDAEL_* constant.
I assume the website is giving you an error because it's expecting a 16-byte block size (as per AES).
I have a bit of a weird one in this class:
<?php
namespace lib;
/**
* Short description of Crypt
*
* #author xxxx
* #package
*/
class Encryption
{
/**
* Short description of _ch
* handle to the mcrypt resource
*
* #access private
* #var $_ch
*/
private $_ch;
/**
* Short description of __construct
*
* #access public
* #author xxxx
* #param
* #return void
*/
public function __construct( $keyData = NULL, $algorithm = \MCRYPT_RIJNDAEL_256, $mode = MCRYPT_MODE_ECB, $encLibPath = '', $modeDir = '' )
{
$this->_ch = mcrypt_module_open( $algorithm, $encLibPath, $mode, $modeDir );
$vector = mcrypt_create_iv ( mcrypt_enc_get_iv_size( $this->_ch ), \MCRYPT_DEV_URANDOM );
$keySize = mcrypt_enc_get_key_size( $this->_ch );
$key = substr( hash( 'SHA512', $keyData . $keySize ), 0, $keySize );
$x = mcrypt_generic_init( $this->_ch, $key, $vector );
}
/**
* Short description of encrypt
*
* #access public
* #author xxxx
* #param String $str
* #return String $res
*/
public function encrypt( $str )
{
if( !is_string( $str ) )
{
throw new \InvalidArgumentException( 'Attemptig to encrypt data that is not a string' );
return false;
}
$res = mcrypt_generic( $this->_ch, $str );
mcrypt_generic_deinit( $this->_ch );
mcrypt_module_close( $this->_ch );
#var_dump($str,$res);
return $res;
}
/**
* Short description of decrypt
*
* #access public
* #author xxxx
* #param String $str
* #return String $res
*/
public function decrypt( $str )
{
if( !is_string( $str ) )
{
throw new \InvalidArgumentException( 'Attemptig to decrypt data that is not a string' );
return false;
}
82 $res = mdecrypt_generic( $this->_ch, $str );
84 mcrypt_generic_deinit( $this->_ch );
85 mcrypt_module_close( $this->_ch );
#var_dump($str,$res);
return trim( $res);
}
}
when calling this like so:
<?php
$encryption = new \lib\Encryption( 'somekey' );
echo $encryption->decrypt( $safeInfo );
strangle yields:
Warning: mdecrypt_generic(): 90 is not a valid MCrypt resource in E:\htdocs\site\application\lib\encryption.cls.php on line 82
Warning: mcrypt_generic_deinit(): 90 is not a valid MCrypt resource in E:\htdocs\site\application\lib\encryption.cls.php on line 84
Warning: mcrypt_module_close(): 90 is not a valid MCrypt resource in E:\htdocs\site\application\lib\encryption.cls.php on line 85
(these lines are shown in the encryption class.)
AND
the expected decrypted string (as in successfully decrypted).
I would be grateful to anyone who might point out why the warnings are raised and why it doesn't seem to affect the outcome.
PS any comments on the effectiveness of the encryption class most welcome.
it looks well
<?php
$encryption = new \lib\Encryption( 'somekey' );
echo $encryption->decrypt(pack("H*", "4a4a564f26618d47536ff35b8a0af3212814a5f0ba635d2cf6f8cd31589042e2"));
_ch lost beacuse mcrypt_module_close( $this->_ch ); in method encrypt()
Maybe you can change __construct and save args only, just create handle ( like _ch ) when you encrypt or decrypt every time.
I'm not good at Mcrypt, so maybe some batter way than mine, but the reason of "valid MCrypt resource" problem is truly mcrypt_module_close
Looks like a namespace issue since you didn't prefix MCRYPT_MODE_ECB in __construct().
This is something to check, but as I can't reproduce, not sure if it's the answer.
You have SHA512 (creating a 512 length key) but the algorythm is expecting a 256 length key. Does it make any difference if you use SHA256? Normally a mismatch in keys should produce garbage, but in this case it may still be working "with side effects".