Simple Encryption and decryption function in php
we use mcrypt php function to encrypt a string and decrpyt the same string.so these are the function to encypt and decrypt a string in php.
Php function to encrypt a string.
public function encryptHash($value)
{
$key = 'wt1U5qZAWJFYUGenFoMOiLwQrGLgdbHA';
$iv = mcrypt_create_iv(
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
MCRYPT_DEV_URANDOM
);
$encrypted = base64_encode(
$iv .
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
$value,
MCRYPT_MODE_CBC,
$iv
)
);
return $encrypted;
/*
$key = 'wt1U5qZAWJFYUGenFoMOiLwQrGLgdbHA'; //wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA
$result = Security::encrypt($value, $key);
return $result;
*/
}
{
$key = 'wt1U5qZAWJFYUGenFoMOiLwQrGLgdbHA';
$iv = mcrypt_create_iv(
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
MCRYPT_DEV_URANDOM
);
$encrypted = base64_encode(
$iv .
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
$value,
MCRYPT_MODE_CBC,
$iv
)
);
return $encrypted;
/*
$key = 'wt1U5qZAWJFYUGenFoMOiLwQrGLgdbHA'; //wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA
$result = Security::encrypt($value, $key);
return $result;
*/
}
Php function to decrypt a string
public function decryptHash($value)
{
$key = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
$data = base64_decode($value);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
$decrypted = rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
MCRYPT_MODE_CBC,
$iv
)
//"\0"
);
return $decrypted;
/*
$key = 'wt1U5MACWJFTXGenFoZoiLwQAbuDsaeQ';
$result = Security::decrypt($value, $key);
return $result;
*/
}
EXAMPLE -
$string ="your string";
$encrypted = encryptHash($string);
$decrypted_data = decryptHash($encrypted);
these functions will encrypt an string using key and decrypt the same string using the same key. you can use these function to encrypt and decrypt your passwords.
Comments
Post a Comment