Tuesday, July 17, 2012

Encryption and Decryption php



Encryption and Decryption php

Sending some data with encryption.Viewing then after decryption is very important in data security.  Following example created to encrypt data for sending and decrypt data for viewing.

<form action="encrypt.php" method="get">
<textarea name ="input" rows="2" cols="20">
</textarea>
<input type="submit" value="Encrypt"/>
</form>
<form action="decrypt.php" method="get">
<textarea name ="data" rows="2" cols="20">
</textarea>
<input type="submit" value="Decrypt"/>
</form>
<?php
function encrypt_string($input)
{

    $inputlen = strlen($input);
    $randkey = rand(1, 9);

    $i = 0;
    while ($i < $inputlen)
    {

        $inputchr[$i] = (ord($input[$i]) - $randkey);//encrpytion

        $i++; // For the loop to function
    }

//Puts the $inputchr array togtheir in a string with the $randkey add to the end of the string
    $encrypted = implode('.', $inputchr) . '.' . (ord($randkey)+50);
    return $encrypted;
}

$input = $_GET["input"];
$encrypted = encrypt_string($input);
echo "<strong>Encrypted:</strong> $encrypted";
?>
<?php
function decrypt_string($input)
{
  $input_count = strlen($input);

  $dec = explode(".", $input);
  $x = count($dec);
  $y = $x-1;

  $calc = $dec[$y]-50;
  $randkey = chr($calc);

  $i = 0;

   while ($i < $y)
  {

    $array[$i] = $dec[$i]+$randkey;
    $real .= chr($array[$i]);

    $i++;
  };

$input = $real;
return $input;
}

$input = $_GET["data"];
$decrypted = decrypt_string($input);
echo "<strong>Decrypted:</strong> $decrypted";
?>

No comments:

Post a Comment