Thursday, 22 December 2011

Encrypt and decrypt string

Encrypt and decrypt string
This task use php to encrypt and decrypt string.
Encrypt and decrypt string using RIJNDAEL_256
  1. Create crypto.php as following
  2. Call encrypt and decrypt method as following
call methods
1$key = uniqid();
2$src = "Hello world!";
3
4require_once('crypto.php');
5$cp = new crypto();
6$tag1 = $cp->encrypt($src, $key);
7$tag2 = $cp->decrypt($tag1, $key);
8print($src . "<br />" . $tag1 . "<br />" . $tag2);
$key = uniqid();
$src = "Hello world!";

require_once('crypto.php');
$cp = new crypto();
$tag1 = $cp->encrypt($src, $key);
$tag2 = $cp->decrypt($tag1, $key);
print($src . "<br />" . $tag1 . "<br />" . $tag2);
crypto.php
1<?php
2
3class crypto {
4
5 public function encrypt($text, $key) {
6 $src = uniqid() . $text;
7 $tag = trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $src, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
8 return $tag;
9 }
10
11 public function decrypt($text, $key) {
12 $src = $text;
13 $tag = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($src), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
14 $tag = substr($tag, 13);
15 return $tag;
16 }
17
18}
19
20?>
<?php

class crypto {

    public function encrypt($text, $key) { 
        $src = uniqid() . $text;
        $tag = trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $src, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
        return $tag;
    } 

    public function decrypt($text, $key) { 
        $src = $text;
        $tag = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($src), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
        $tag = substr($tag, 13);
        return $tag;
    } 

}

?>
PHP

  Protected by Copyscape Online Copyright Protection

No comments:

Post a Comment