Encrypting strings in PHP - php

Currently im using
$key="pass";
$val="secret";
$encp=mcrypt_encrypt(MCRYPT_DES, $key, $val, MCRYPT_MODE_ECB);
But when i call printf($encp)
No value is displayed,im using PHP version 5.2.17
Is there a better way to do it.Please help.
EDIT:
<?PHP
define('SECURE_KEY','Somekey');
function encrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv);
}
function decrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv));
}
$temp=encrypt("teststring");
printf($temp);
?>

Update (27/09/17):
Since mcrypt_encrypt is DEPRECATED as of PHP 7.1.0. Ive added a simple encrypt/decrypt using openssl.
function encrypt($string, $key = 'PrivateKey', $secret = 'SecretKey', $method = 'AES-256-CBC') {
// hash
$key = hash('sha256', $key);
// create iv - encrypt method AES-256-CBC expects 16 bytes
$iv = substr(hash('sha256', $secret), 0, 16);
// encrypt
$output = openssl_encrypt($string, $method, $key, 0, $iv);
// encode
return base64_encode($output);
}
function decrypt($string, $key = 'PrivateKey', $secret = 'SecretKey', $method = 'AES-256-CBC') {
// hash
$key = hash('sha256', $key);
// create iv - encrypt method AES-256-CBC expects 16 bytes
$iv = substr(hash('sha256', $secret), 0, 16);
// decode
$string = base64_decode($string);
// decrypt
return openssl_decrypt($string, $method, $key, 0, $iv);
}
$str = 'Encrypt this text';
echo "Plain: " .$str. "\n";
// encrypt
$encrypted_str = encrypt($str);
echo "Encrypted: " .$encrypted_str. "\n";
// decrypt
$decrypted_str = decrypt($encrypted_str);
echo "Decrypted: " .$decrypted_str. "\n";
Try these: (PHP < 7.1.0) If your using > PHP 7.1.0 see above.
define('SECURE_KEY','Somekey');//Assigned within a config, pref outside of root dir
function encrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv);
}
function decrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv));
}
//Simple usage
$encryptedString = encrypt('This String Will Be encrypted');
echo decrypt($encryptedString);
Edited from source - http://php.net/manual/en/function.mcrypt-encrypt.php

Try these PHP functions convert_uuencode and convert_uudecode:
function encrypt_decrypt ($data, $encrypt) {
if ($encrypt == true) {
$output = base64_encode (convert_uuencode ($data));
} else {
$output = convert_uudecode (base64_decode ($data));
}
return $output;
}
$enc_txt = encrypt_decrypt ("PASSWORD TEXT", true);
echo $enc_txt."\n";
// LTQkJTM0VT0vNEQwQDUkNTg1YGBgCmAK
echo encrypt_decrypt ($enc_txt, false);
// PASSWORD TEXT
This is much simpler and does not depend on libraries installed in PHP

Related

PHP Mysqli mcrypt_get_iv_size deprecated, how to use a new function?

I was using the mcrypt_get_iv_size function with my website and now it seems that it's deprecated
function Encrypt($word){
$key = '.......';
$iv = mcrypt_create_iv(
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
MCRYPT_DEV_URANDOM
);
$encrypted = base64_encode(
$iv .
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
$word,
MCRYPT_MODE_CBC,
$iv
)
);
return $encrypted;
}
function Decrypt($word){
$key = '.......';
$data = base64_decode($word);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
$decrypted = rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
MCRYPT_MODE_CBC,
$iv
),
"\0"
);
return $decrypted;
}
Now I found a new function from stackoverflow which is this one
function Encrypt($word) {
$key = '.......';
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encrypted = openssl_encrypt($word, 'aes-256-cbc', $key, 0, $iv);
return base64_encode($encrypted . '::' . $iv);
}
function Decrypt($word) {
$key = '.......';
list($encrypted_data, $iv) = explode('::', base64_decode($word), 2);
return openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv);
}
My question is:
Do I have to use my previously working Decrypt function to get export all my encrypted words from my database and then Encrypt them with the new function and then import/update them into my database? Or is there a way to be able to Decrypt my words from the new function only?
Thanks!

PHP convert MCRYPT_ENCRYPT to OPENSSL_ENCRYPT (SOAP header)

I need to encrypt some SOAP header fields, and I currently have the following code working in a project with PHP 5.6 version.
function getBaseEncoded($data, $key)
{
$size = $this->pkcs5_pad($data, mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB));
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
$result = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $size, MCRYPT_MODE_ECB, $iv);
return trim(base64_encode($result));
}
private function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat (chr($pad), $pad);
}
What happens is that now I have in my hands a similiar project but with PHP 7, and the function MCRYPT is deprecated and I need to switch it to OPENSSL_ENCRYPT.
The code below is my first attempt:
function getBaseEncoded($data, $key)
{
$result = openssl_encrypt($data, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
return trim(base64_encode($result));
}
But I'm now receiving a SOAP error with the message
SoapFault => Could not connect to host
and it got me thinking if the problem is on my new function?
You are missing some initializator vector data.
$ivsize = openssl_cipher_iv_length('AES-128-ECB');
$iv = openssl_random_pseudo_bytes($ivsize);
$ciphertext = openssl_encrypt(
$data,
'AES-128-ECB',
$key,
OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
$iv
);
echo encrypt_openssl($data, $key);
function encrypt_openssl($msg, $key, $iv = null) {
$iv_size = openssl_cipher_iv_length('AES-128-ECB');
if (!$iv) {
$iv = openssl_random_pseudo_bytes($iv_size);
}
$encryptedMessage = openssl_encrypt($msg, 'AES-128-ECB', $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv . $encryptedMessage);
}

php Encryption not work in 5.6 or later version?

I am using this code to encrypt password but it doesn't work php 5.6 or later versions. Please suggest me new code without changing algo.
please give me new code without changing algorithm.
<?php
class Encryption {
var $skey = "844958uyjd875e89t5f4h6j4h5g"; // you can change it
public function safe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
public function safe_b64decode($string) {
$data = str_replace(array('-','_'),array('+','/'),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
public function encode($value){
if(!$value){return false;}
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
return trim($this->safe_b64encode($crypttext));
}
public function decode($value){
if(!$value){return false;}
$crypttext = $this->safe_b64decode($value);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
}
?>
Just use password_hash and password_verify. It's the safest way to protect passwords.
For example:
$password_hash = password_hash("yourpassword", PASSWORD_DEFAULT);
if (password_verify('yourpassword', $password_hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
http://php.net/manual/en/function.password-hash.php

PHP encryption / decryption adding padded characters

I'm trying to create a simple Encryption class but the resulting string is being padded with non-ascii characters. I've tried rtrim(), converting to utf8, etc. as mentioned in some other answers. What exactly am I missing? Here is what the characters show up when pasting the results into Notepad++
Pastebin containing the characters here. Appears as 't' in html, but copying that into notepad shows the random bits of data after it.
class Crypter implements ICrypter {
private $Key;
private $Algo;
public function __construct($Algo = MCRYPT_BLOWFISH) {
$this->Key = substr('key', 0, mcrypt_get_key_size($Algo, MCRYPT_MODE_ECB));
$this->Algo = $Algo;
}
public function Encrypt($data) {
//$iv_size = mcrypt_get_iv_size($this->Algo, MCRYPT_MODE_ECB);
//$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$blocksize = mcrypt_get_block_size('blowfish', 'ecb'); // get block size
$pkcs = $blocksize - (strlen($data) % $blocksize); // get pkcs5 pad length
$data.= str_repeat(chr($pkcs), $pkcs); // append pkcs5 padding to the data
$crypt = mcrypt_encrypt($this->Algo, $this->Key, $data, MCRYPT_MODE_ECB);
return rtrim(base64_encode($crypt));
}
public function Decrypt($data) {
$crypt = base64_decode($data);
$iv_size = mcrypt_get_iv_size($this->Algo, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypt = mcrypt_decrypt($this->Algo, $this->Key, $crypt, MCRYPT_MODE_ECB, $iv);
return rtrim($decrypt);
}
}
You need to handle the padding in the decryption same as the encryption. Here is a working example of your code:
<?php
class Crypter{
private $Key;
private $Algo;
public function __construct($Algo = MCRYPT_BLOWFISH) {
$this->Key = substr('key', 0, mcrypt_get_key_size($Algo, MCRYPT_MODE_ECB));
$this->Algo = $Algo;
}
public function Encrypt($data) {
//$iv_size = mcrypt_get_iv_size($this->Algo, MCRYPT_MODE_ECB);
//$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$blocksize = mcrypt_get_block_size('blowfish', 'ecb'); // get block size
$pkcs = $blocksize - (strlen($data) % $blocksize); // get pkcs5 pad length
$data.= str_repeat(chr($pkcs), $pkcs); // append pkcs5 padding to the data
$crypt = mcrypt_encrypt($this->Algo, $this->Key, $data, MCRYPT_MODE_ECB);
return rtrim(base64_encode($crypt));
}
public function Decrypt($data) {
$crypt = base64_decode($data);
$iv_size = mcrypt_get_iv_size($this->Algo, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypt = mcrypt_decrypt($this->Algo, $this->Key, $crypt, MCRYPT_MODE_ECB, $iv);
$block = mcrypt_get_block_size('blowfish', 'ecb');
$pad = ord($decrypt[($len = strlen($decrypt)) - 1]);
return substr($decrypt, 0, strlen($decrypt) - $pad);
}
}
$crypter = new Crypter();
$data = "Some data to encrypt";
$encryptedData = $crypter->Encrypt($data);
$decryptedData = $crypter->Decrypt($encryptedData);
echo "Decrypted Data = [$decryptedData]\n";
Notice the three lines I replaced your original Decrypt() return line with.

iOS/PHP kCCDecodeError

I can't for the life of me work out why when I encrypt something in PHP I can't then decrypt it in my iOS app, but PHP can decrypt iOS encrypted strings and decrypt/encrypt between itself.
PHP -> Obj-C FAILS.
Yes, I have looked across the net and the only solution I found was to use CBC in PHP which I'm already doing.
I'm using the FBEncryptor library for iOS and these are the encrypt/decrypt functions in PHP:
function encrypt($decrypted)
{
$iv = ''; for($i=0;$i<16;$i++){ $iv .= "\0";}
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $passKey, $decrypted, MCRYPT_MODE_CBC, $iv);
$ciphertext = base64_encode($ciphertext);
return $ciphertext;
}
function decrypt($encrypted)
{
$iv = ''; for($i=0;$i<16;$i++){ $iv .= "\0";}
$ciphertext = base64_decode($encrypted);
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $passKey, $ciphertext, MCRYPT_MODE_CBC, $iv);
return $plaintext;
}
From the FBEncryptor Github page (emphasis mine):
Supported encryption algorithm is AES 256 bit only.
But in your code snippet above, you're doing:
mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext, MCRYPT_MODE_CBC, $iv);
i.e. decrypting with AES 128 bit as your cipher.
You'll need to correct your code accordingly. Other common mistakes include using mismatched padding and block cipher operation modes.
I managed to work out the problem. Was a silly mistake on my part with the pass key variable. Here is my final implementation anyway for anyone else that comes across this problem:
function encrypt($decrypted)
{
$thePassKey = "12345678901234567890123456789012";
# Add PKCS7 padding.
$str = $decrypted;
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
if (($pad = $block - (strlen($str) % $block)) < $block)
{
$str .= str_repeat(chr($pad), $pad);
}
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = ''; for($i=0;$i<$iv_size;$i++){ $iv .= "\0";}
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $thePassKey, $str, MCRYPT_MODE_CBC, $iv));
}
function decrypt($encrypted)
{
$thePassKey = "12345678901234567890123456789012";
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = ''; for($i=0;$i<$iv_size;$i++){ $iv .= "\0";}
$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $thePassKey, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv);
# Strip PKCS7 padding.
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = ord($str[($len = strlen($str)) - 1]);
if ($pad && $pad < $block && preg_match(
'/' . chr($pad) . '{' . $pad . '}$/', $str))
{
return substr($str, 0, strlen($str) - $pad);
}
return $str;
}

Categories