Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypt and Decrypt AES

I want to encrypt the original string after i click the encrypt button and inputs element will not clear and after i click the decrypt it will decrypt. My problem is after i click the decrypt there is no value to the decrypt only the encrypt is moving. Can someone help me about this?

here is the output after i click the decrypt. enter image description here

here is my code.

<?php
/*
 * PHP mcrypt - Basic encryption and decryption of a string
 */
error_reporting(E_ALL ^ E_NOTICE);
$secret_key = "thisismykey12345";
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);

if(isset($_POST['encrypt'])){
    $string = $_POST['ostring'];

$encrypted_string = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secret_key, $string, MCRYPT_MODE_CBC, $iv);

}
else if(isset($_POST['decrypt'])){
    $decrypted_string = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $secret_key, $encrypted_string, MCRYPT_MODE_CBC, $iv);

}

?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form method="post"> 
Original String <input type="text" name="ostring" value="<?php echo $string; ?>"><br>
<input type="submit" name="encrypt" value="Encrypt"><br>
Encrypted String <input type="text" style="width:500px;" name="encrypted" value="<?php echo $encrypted_string; ?>"><br>
<input type="submit" name="encrypt" value="Decrypt"><br>
Decrypted String <input type="text" style="width:500px" name="decrypted" value="<?php echo $decrypted_string; ?>"><br>
</form> 
</form>
</body>
</html>
like image 327
Yukihira Soma Avatar asked Feb 11 '26 23:02

Yukihira Soma


1 Answers

This part has 2 logical flaws:

if(isset($_POST['encrypt'])){
    $string = $_POST['ostring'];
    $encrypted_string = ...;
}
else if(isset($_POST['decrypt'])){
    $decrypted_string = ...$encrypted_string...;
}
  1. $decrypted_string will never be set because it relies on $encrypted_string. But $encrypted_string only exists if the execution path enters the first if block and skips the elseif block.
  2. Besides you never check whether ostring is available before encrypting even though it's required

Put the two execution paths in separate if blocks:

if(isset($_POST['encrypt'],$_POST['ostring'])){
    $encrypted_string = ...;
}

if(isset($_POST['decrypt'],$encrypted_string)){
    $decrypted_string = ...;
}
like image 83
BeetleJuice Avatar answered Feb 14 '26 14:02

BeetleJuice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!