Reputation: 1
I'm working on a small program that has to encrypt a basic sentence and echo the result. Then I want to be able to copy paste the result and be able to decode the text in the same way I encoded it. It doesn't need to be too safe, so therefore I opted to use Mcrypt.
When I try to decrypt, it gives weird (ASCII?) letters and I don't understand where they come from. Tried to solve it with a base64 encode/decode, but that didn't help either. What do I need to change to get it to work properly?
<?php
// Define Mcrypt variables
$enc = MCRYPT_RIJNDAEL_128;
$mode = MCRYPT_MODE_CBC;
$key = 'SanderDitIsNodigVoor16bi';
$iv = mcrypt_create_iv(mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM);
// Check if 'submit' is set
if (isset($_POST['submit'])) {
// Check if 'text' is set
if (!empty($_POST['text'])) {
// Check if 'crypt' is set
if (isset($_POST['crypt'])) {
// Retrieve 'text'
$input = $_POST['text'];
// Check for encrypt/decrypt
switch ($_POST['crypt']) {
case 'encrypt':
$result = encrypt();
break;
case 'decrypt':
$result = decrypt();
break;
}
echo $result;
}
// If 'crypt' is not set
else {
echo 'Please select encrypt or decrypt.';
}
}
// If 'text' is not set
else {
echo 'Please fill in some text.';
}
}
function encrypt() {
global $enc, $key, $input, $mode, $iv;
$encrypted = mcrypt_encrypt($enc, $key, $input, $mode, $iv);
$output = base64_encode($encrypted);
return $output;
}
function decrypt() {
global $enc, $key, $input, $mode, $iv;
$decrypted = base64_decode($input);
$output = mcrypt_decrypt($enc, $key, $decrypted, $mode, $iv);
return $output;
}
?>
To be clear, if I include the mcrypt_decrypt in the encryption to make sure it's not something I messed up in the function itself, it does decrypt it properly. But when I try to separate the two, it doesn't. I'm stumped.
Upvotes: 0
Views: 286
Reputation: 8308
you are sending to both encrypt
and decrypt
the same input , which is :
$input = $_POST['text'];
encrypt will encrypt successfully , but you are always trying to decrypt 'decrypted' phrase !
you must pass the encrypted
phrase to decrypt function
and don't forget about the important note that mcrypt_* extension has been deprecated :
This extension rely in libmcrypt which is dead, unmaintained since 2007.
Please don't rely on it, consider switching to well maintained alternatives (openssl, crypt, password hashing functions, phpseclib, password_compat...)
and , try to stop using global
variables , it isn't recommended .
Upvotes: 1