encrypt and decrypt with diacrits - php

I have these code for encrypt and decrypt.
It works good for text (for example: "This is a text"), which is withnout diacritics (that means without : ěščřžýáíéúů).
But I need encrypt and decrypt text with this special letters (with : ěščřžýáíéúů).
Can somebody help me, please?
Thank so much for every answer and help.
Have a nice day. M.
define ("ENCRYPTION_KEY", "QaY7e4d1c");
$string= "This is a text"; // -> this work alright
//$string= "áýžřčšě"; I NEED THIS TEXT ENCRYPT AND DECRTYPT
echo $encrypted = encrypt($string, ENCRYPTION_KEY);
echo "<br />";
echo $decrypted = decrypt($encrypted, ENCRYPTION_KEY);
function encrypt ($pure_string,$encryption_key)
{
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH,MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size,MCRYPT_RAND);
$encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH,$encryption_key,utf8_encode($pure_string),MCRYPT_MODE_ECB,$iv);
return $encrypted_string;
}
function decrypt ($encrypted_string,$encryption_key)
{
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH,MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size,MCRYPT_RAND);
$decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH,$encryption_key,$encrypted_string,MCRYPT_MODE_ECB ,$iv);
return $decrypted_string;
}

You're calling utf8_encode in your encryption function, but not calling utf8_decode when you decrypt, so your functions as they stand don't complement each other.
I'd recommend removing the call to utf8_encode entirely. mcrypt_encrypt doesn't care what encoding your string uses, so whatever you pass in will be what you get back out. Your script works fine for me if I remove it:
$encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, $pure_string, MCRYPT_MODE_ECB, $iv);
I'd also suggest reading this: https://paragonie.com/blog/2015/05/if-you-re-typing-word-mcrypt-into-your-code-you-re-doing-it-wrong

Related

PHP Encrypt and Decrypt Parameter URL in URL

I'm trying to pass a download URL from page 1 to page 2 in a GET request.
Page 1 gets the raw URL through the database, then encrypts the URL and makes it available on the site. When it's passed through the URL, page 2 decrypts the URL and downloads the file.
The URL looks like this currently:
https://example.com/download.php?dl=x6%1A%D8j%C4%D2%9Cx%8FA%8B%29%23Y%D9%D6%B4%DE8%18%2C%7B%F4%86l%B0%0A+%D3%B1%01I%CFo%FF%BA%9C%22%A1%08%11%DB%12%282%DEi%B5%CA%14K%FF%21%CB%F3%9D%3C9f%3C%09%FA9%BB%BD%C9%B2%275%F0%06%A2%80%08h%A7f%8C%87%28%A4%A5%99%A9%A9%FA%D6f%C5%CA%9B%81.%92%CD%89%FA3%5C%0C%F0%ED%F6%D9%1E%B9%D0%B1%CFSA%F4%95k%1EZ%D1%3A%D4H%1D%93%40%087%92%88%C3%A5p%C7WH%FA%CF%9D%BAKd%A0%9A%D7a6%80%5Ex%A5%87%07AK%D7%5BQ%10%98%07%7E%82%9A%BA9%25%D5%EA%03%FD%C2%9A%22%8FBW%94k%D8T%93%F5%E3%D7-
It contains a lot of %%% because it's urlencoded, is there a way to change this to make the URL less long and make it look less messy, but keep it safe as it is now?
Hope someone can help me out.
This is the encryption and decryption script:
define("ENCRYPTION_KEY", "ducksandpizza");
function encrypt($pure_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv);
return urlencode($encrypted_string);
}
function decrypt($encrypted_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypted_string = urldecode($encrypted_string);
$decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv);
return $decrypted_string;
}
//$encrypted = encrypt($_GET['dl'], ENCRYPTION_KEY);
$decrypted = decrypt($_GET['dl'], ENCRYPTION_KEY);
//echo 'encrypted: ' . $encrypted . '<br>';
echo 'decrypted: ' . $decrypted . '<br>';
Use some type of compression on the unencrypted data, like gzcompress() and then pass that to your encryption method, and the output of that to base64_encode. Base64 encoding will still increase the overall size, but not as much as url encode does.
While using base64_encode() isn't necessarily a bad idea, no one has mentioned that stock base64 encoding is not URL-safe as it uses the characters significant in URL syntax.
However, there's a variant that is safe that's used for encoding JWT tokens:
function base64url_encode($bin) {
return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($bin));
}
function base64url_decode($str) {
return base64_decode(str_replace(['-', '_'], ['+', '/'], $str));
}
You should also bear in mind the GET requests are subject to length restrictions which vary between HTTP server implementations and languages. You'll probably want to use something like gzcompress() as suggested in the comments, but more likely you should be passing this data in a POST instead.

Encrypt a string in PHP where the output is URL safe

I have a requirement where I need to move a string from one place to another via GET. e.g.
example.com?string=ENCRYPTED_STRING
Is there a algorithm or some other method to encrypt the string so it is URL safe?
By that I mean it will not have characters like = or & ...
I have tried openssl with AES-256-CBC but no luck.
The data is not overly very sensitive but I would prefer to obfuscate it in someway.
Oh hey, I've actually done this in one of my applications. My code looks a lot different (because of my custom tools, it's a one-liner), but works basically like this (uses defuse/php-encryption):
use \Defuse\Crypto\Crypto;
$url = "/my/endpoint?".http_build_query([
'something' => base64_encode(
Crypto::encrypt('my_secret_info', CRYPTO_SECRET_KEY)
)
]);
// Then you can either use $url in header('Location: '.$url) or in an HTML link safely.
Further reading:
base64_encode()
http_build_query()
urlencode() (if you don't want to use http_build_query())
Why you want authenticated encryption (which defuse/php-encryption provides) rather than just encryption (which OpenSSL's AES-CBC provides)
Footnote: If you (or anyone else) want a short encrypted URL parameter, read this answer instead. (I know what's not what you were asking for, but just in case someone finds this question years down the line...)
The code below allow you to encrypt (alpha/num) and decrypt a string. But you need Mcrypt php module installed to make it run.
static public function encrypt($text){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = "useasuperkey";
return (bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv)));
}
static public function decrypt($text){
$len = strlen($text);
$text = pack("H" . $len, $text);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = "useasuperkey";
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv));
}
I had to do exactly same thing.
My solution was encrypting string with openssl_encrypt($str, "AES-128-CBC", $key).
Then sending the URL using url_encode($str).
Destination page decodes data with openssl_decrypt($str, "AES-128-CBC", $key)

Decrypting with different IV

I've found a pair of encryption and decryption functions that look like they obey all the rules of data security that I'm desperate to fully understand but probably won't be able to without a doctorate in this stuff.
They work great when I'm encrypting and decrypting something on the same page with the same IV.
But when I try saving the results to an SQL database and then pulling them back out again and decrypting, it doesn't work.
$key = "secretsecret";
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM);
function encrypt($key, $text, $iv) {
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv)));
}
function decrypt($key, $text, $iv) {
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($text), MCRYPT_MODE_CBC,$iv));
}
$text = "the text to encrypt";
echo "Plain Text: " . $text . "<br><br>";
$encrypted = encrypt($key, $text, $iv);
echo "Encrypted Text: " . $encrypted . "<br><br>";
echo "Decrypted Text: ". decrypt($key, $encrypted, $iv) . "<br><br>"; //this works fine
//save encrypted text to SQL
mysql_query("UPDATE table SET test='".addslashes($encrypted)."' WHERE id='1'");
Then if on another page view I pull the text back out and try to:
echo "Decrypted Text: ". decrypt($key, $textFromSQL, $iv) . "<br><br>";
I get gibberish. What do I need to do to get the text decrypted properly with a different IV?
You need to use the same Initialization Vector (IV) in the decryption as you do in the enryption. This means you need to store the IV in the database.
The IV doesn't need to be secret, unlike the key.
Something like this:
mysql_query("UPDATE table SET test='".addslashes($encrypted)."', IV='".addslashes($IV)."' WHERE id='1'");
Then when you decrypt the data use the stored IV.

mcrypt_decrypt wrong output after using encrypted data php

I have a small problem with php mcrypt_decrypt function. Firstly, I use a 16-byte string, and encrypt it using mcrypt_encrypt; then, I use base64_encode, and put the output to mcrypt_decrypt, in order to get the initial string.
But the output is not what's expected. I checked that my base64 decoded string input for decoding is the exact output produced by mcrypt_decrypt. Here is my code:
//encrypt
$str="KKQT9W4st7vmdkps";
$key="43625A8C1E4330BDF84DDEE3DD105037";
$block = mcrypt_get_block_size('rijndael_128', 'ecb');
$passcrypt=mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);
echo $passcrypt;
That outputs PTfZ6Ephh8LTxXL4In33Og==. The decryption script is the following:
//decrypt
$str='PTfZ6Ephh8LTxXL4In33Og==';
$key='43625A8C1E4330BDF84DDEE3DD105037';
$str = base64_decode($str);
$str = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
$str, MCRYPT_MODE_ECB,''),"\0");
$block = mcrypt_get_block_size('rijndael_128', 'ecb');
echo $str;
And the output is not KKQT9W4st7vmdkps, but -nγ kk7Ζn’T instead. Any ideas? I'm using XAMPP and Apache server.
Thx guys for the feedback it was a silly mistake that i made...actually 'PTfZ6Ephh8LTxXL4In33Og==' was wrong in the decrypt function cause "I" was "l" in the end...so the decryption was not correct...but it was not my fault either since I was getting this string from a QR CODE scanner and both "I" and "l" are displayed the same...
For encryption, you need to:
1) Create an encryption resource
$str = "KKQT9W4st7vmdkps";
$key = "43625A8C1E4330BDF84DDEE3DD105037";
$r = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '',MCRYPT_MODE_ECB, '');
2) Randomly create encryption vector based on the size of $r
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($r),MCRYPT_RAND);
3) Initiliazing module using the resource,key and string vector
mcrypt_generic_init($r,$key,$iv);
4) Encrypt data/string using resource $r
$encrypted = mcrypt_generic($r,$str);
5) Encode it using base64_encode
$encoded = base64_encode($encrypted);
if(!mcrypt_generic_deinit($r) || !mcrypt_module_close($r))
$encoded = false;
6) Echoing it
echo 'Encrypted: '.$encoded;
For decryption, it's like a reverse process of encrypt
//Using the same enrypted string
$decoded = (string) base64_decode(trim($encoded));
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '',MCRYPT_MODE_ECB, '');
$ivs = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td,$key, $ivs);
$decoded = (string) trim(mdecrypt_generic($td, $decoded));
if(!mcrypt_generic_deinit($td) || !mcrypt_module_close($td))
$decoded = false;
Echoing it
echo 'Decrypted: '. $decoded;
Hope this helps. More info here.

How to decrypt using Blowfish algorithm in php?

I am supposed to write a PHP script to decrypt Blowfish encrypted data.
The data I am receiving for decryption is encrypted by another application (I have no access to it).
The data decrypts fine when am check it using a javascript script (blowfish.js).
How can I decrypt the data in php?
I have tried the mcrypt function in PHP. The code works fine if I encrypt and decrypt using the same code. If I decrypt an encrypted code (in another app) it gives junk.
No idea about what mode to set.
Can anyone suggest on the code below or any PHP BlowFish code without using mcrypt?
<?php
class Encryption
{
static $cypher = 'blowfish';
static $mode = 'cfb';
static $key = '12345678';
public function encrypt($plaintext)
{
$td = mcrypt_module_open(self::$cypher, '', self::$mode, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, self::$key, $iv);
$crypttext = mcrypt_generic($td, $plaintext);
mcrypt_generic_deinit($td);
return $iv.$crypttext;
}
public function decrypt($crypttext)
{
$plaintext = "";
$td = mcrypt_module_open(self::$cypher, '', self::$mode, '');
$ivsize = mcrypt_enc_get_iv_size($td);
$iv = substr($crypttext, 0, $ivsize);
$crypttext = substr($crypttext, $ivsize);
if ($iv)
{
mcrypt_generic_init($td, self::$key, $iv);
$plaintext = mdecrypt_generic($td, $crypttext);
}
return $plaintext;
}
}
$encrypted_text = Encryption::encrypt('this text is unencrypted');
echo "ENCRY=".$encrypted_text;echo "<br/>";
////I am using this part(decryption) coz data already encryption
// Encrypted text from app
$encrypted_text = '29636E7ADA7081E7F5D73121C45E20D5';
// Decrypt text
$decrypted_text = Encryption::decrypt($encrypted_text);
echo "ENCRY=".$decrypted_text;echo "<br/>";
?>
The $iv you use when decrypting must be the same as the Initialization Vector used when encrypting the data. Your own functions transfer this information by prepending the IV to the ciphertext (return $iv.$crypttext;), but the other application might not do so.
You need to find out what IV the other app uses, and pass that to your own code. Since the decrypt function reads the IV from the beginning of the ciphertext you can simply prepend it.
Also, you can test a bit by encrypting the same text with your encrypt function and with the other application. If the outputs do not have the same length (your own is larger), then the app is not including the IV inside the ciphertext and you must obtain this information in another manner.
And of course the cipher mode used (CFB) must be the same between your code and the other app.
There's a nice, easy to implement solution here:
www.codewalkers.com: Encrypt and Decrypt using Blowfish
There is a PEAR Library for creating blowfish encyptions that allow you to choose weather to use MCRYPT Libs, or purely native PHP:
you may view the Library here: Crypt_Blowfish 1.1.0RC2
Select the PHP.php file will show you the source code to do this hard coded in native PHP.

Categories