Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //NOTE: I am using POST requests to send the data to and from the server, that is why everything is in $_POST variables.
- //ENCRYPTION
- if ($_POST['password'] == "password"){
- if ($_POST['type'] == "test") $key = pack("H*", "myKey"); //The key is not actually myKey, it is a 256-bit key in hex.
- else if ($_POST['type'] == "name") $key = pack("H*", "myKey");
- else if ($_POST['type'] == "email") $key = pack("H*", "myKey");
- //Creates an ilitialization vector (basically a private key used when encrypting data).
- //It does NOT need to be remembered: http://i.stack.imgur.com/LFHlH.png
- $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
- $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
- //Creates a cipher, which is basically encrypting the text.
- $cipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $_POST['data'], MCRYPT_MODE_CBC, $iv);
- //Add the IV to the start of the string (prepend it) so it is available for decryption.
- $ciphertext = base64_encode($iv) . ":" . base64_encode($cipher); //It's 256-bit so it will be the first 256 chars.
- $encoded = $ciphertext; //Encode the ciphertext so it can be represented as a string and used as such.
- echo($encoded);
- }else{
- echo("UNAUTHORISED.");
- }
- //DECRYPTION (this is where the problem is)
- if ($_POST['password'] == "password"){
- if ($_POST['type'] == "test") $key = pack("H*", "myKey");
- else if ($_POST['type'] == "name") $key = pack("H*", "myKey");
- else if ($_POST['type'] == "email") $key = pack("H*", "myKey");
- $ciphertext_dec = $_POST['data']; //Text was encoded into base64 after encryption, so it now must be decoded for decryption. This also has the initialization vector attached.
- $split = explode(":", $ciphertext_dec, 2); //Seperate the IV from the main cipher text.
- echo($split[1] . "<br><br>"); //Used for testing.
- $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); //Get the size of the IV used (256-bit).
- //$iv = base64_decode($split[0]); //Decode the IV.
- $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB));
- $data = base64_decode($split[1]); //Decode the cipher text.
- print_r("DATA: " . $data . "<br><br>"); //Used for testing.
- $text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, $iv); //Decrypt the ciphertext.
- $val = rtrim($text, "\0");
- echo($val); //Return the decrypted text. No need for encoding.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement