Last active
February 29, 2020 03:58
-
-
Save alvin4frnds/e2b7a9a03d665551d99d4c4dc88a260e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: praveen | |
* Date: 02/09/17 | |
* Time: 1:32 PM | |
*/ | |
namespace App\Medi; | |
class MCrypt { | |
private $iv = '0000000000000000'; #Same as in JAVA | |
private $key = 'oshi12wq!@WQ'; #Same as in JAVA | |
function __construct() { | |
$this->key = hash('sha256', $this->key, true); | |
} | |
function encrypt($str) { | |
$iv = $this->iv; | |
$td = @mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); | |
@mcrypt_generic_init($td, substr($this->key, 0, 32), $iv); | |
$block = @mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); | |
$pad = $block - (strlen($str) % $block); | |
$str .= str_repeat(chr($pad), $pad); | |
$encrypted = @mcrypt_generic($td, $str); | |
@mcrypt_generic_deinit($td); | |
@mcrypt_module_close($td); | |
return base64_encode($encrypted); | |
} | |
function decrypt($code) { | |
$iv = $this->iv; | |
$td = @mcrypt_module_open('rijndael-128', '', 'cbc', ''); | |
@mcrypt_generic_init($td, $this->key, $iv); | |
// http://php.net/manual/en/function.base64-decode.php#102113 | |
$code = str_replace(" ", "+", $code); | |
$str = @mdecrypt_generic($td, base64_decode($code)); | |
$block = @mcrypt_get_block_size('rijndael-128', 'cbc'); | |
@mcrypt_generic_deinit($td); | |
@mcrypt_module_close($td); | |
return $str; | |
//return $this->strippadding($str); | |
} | |
/* | |
For PKCS7 padding | |
*/ | |
private function addpadding($string, $blocksize = 16) { | |
$len = strlen($string); | |
$pad = $blocksize - ($len % $blocksize); | |
$string .= str_repeat(chr($pad), $pad); | |
return $string; | |
} | |
private function strippadding($string) { | |
$slast = ord(substr($string, -1)); | |
$slastc = chr($slast); | |
$pcheck = substr($string, -$slast); | |
if (preg_match("/$slastc{" . $slast . "}/", $string)) { | |
$string = substr($string, 0, strlen($string) - $slast); | |
return $string; | |
} else { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment