PHP和.net中des加解密的實現(xiàn)方法
更新時間:2013年02月27日 14:20:39 作者:
PHP和.net中des加解密的實現(xiàn)方法,需要的朋友可以參考一下
php5.x版本,要添加php擴展php_mcrypt。
PHP版:
復(fù)制代碼 代碼如下:
class STD3Des
{
private $key = "";
private $iv = "";
/**
* 構(gòu)造,傳遞二個已經(jīng)進(jìn)行base64_encode的KEY與IV
*
* @param string $key
* @param string $iv
*/
function __construct ($key, $iv)
{
if (empty($key) || empty($iv)) {
echo 'key and iv is not valid';
exit();
}
$this->key = $key;
$this->iv = $iv;
}
/**
*加密
* @param <type> $value
* @return <type>
*/
public function encrypt ($value)
{
$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
$iv = base64_decode($this->iv);
$value = $this->PaddingPKCS7($value);
$key = base64_decode($this->key);
mcrypt_generic_init($td, $key, $iv);
$ret = base64_encode(mcrypt_generic($td, $value));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $ret;
}
/**
*解密
* @param <type> $value
* @return <type>
*/
public function decrypt ($value)
{
$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
$iv = base64_decode($this->iv);
$key = base64_decode($this->key);
mcrypt_generic_init($td, $key, $iv);
$ret = trim(mdecrypt_generic($td, base64_decode($value)));
$ret = $this->UnPaddingPKCS7($ret);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $ret;
}
private function PaddingPKCS7 ($data)
{
$block_size = mcrypt_get_block_size('tripledes', 'cbc');
$padding_char = $block_size - (strlen($data) % $block_size);
$data .= str_repeat(chr($padding_char), $padding_char);
return $data;
}
private function UnPaddingPKCS7($text)
{
$pad = ord($text{strlen($text) - 1});
if ($pad > strlen($text)) {
return false;
}
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
return false;
}
return substr($text, 0, - 1 * $pad);
}
}
//使用
include('STD3Des.class.php');
$key='abcdefgh';
$iv='abcdefgh';
$msg='test string';
$des=new STD3Des(base64_encode($key),base64_encode($iv));
$rs1=$des->encrypt($msg);
echo $rs1.'<br />';
$rs2=$des->decrypt($rs1);
echo $rs2;
.net版本
復(fù)制代碼 代碼如下:
sealed public class CryptoHelper
{
/// <summary>
/// Encrypts the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <param name="key">key</param>
/// <param name="iv">iv</param>
/// <returns></returns>
public static string EncryptDes(string input, byte[] key, byte[] iv)
{
if (input == null || input.Length == 0)
return String.Empty;
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = null;
CryptoStream encStream = null;
StreamWriter sw = null;
string result = String.Empty;
try
{
ms = new MemoryStream();
// Create a CryptoStream using the memory stream and the
// CSP DES key.
//des.Mode = CipherMode.CBC;
//des.Padding = PaddingMode.PKCS7;
encStream = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
// Create a StreamWriter to write a string
// to the stream.
sw = new StreamWriter(encStream);
// Write the plaintext to the stream.
sw.Write(input);
sw.Flush();
encStream.FlushFinalBlock();
ms.Flush();
result = Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length, CultureInfo.InvariantCulture));
}
finally
{
//close objects
if (sw != null)
sw.Close();
if (encStream != null)
encStream.Close();
if (ms != null)
ms.Close();
}
// Return the encrypted string
return result;
}
/// <summary>
/// Decrypts the specified input.
/// </summary>
/// <param name="input">the input.</param>
/// <param name="key">key</param>
/// <param name="iv">iv</param>
/// <returns></returns>
public static string DecryptDes(string input, byte[] key, byte[] iv)
{
byte[] buffer;
try { buffer = Convert.FromBase64String(input); }
catch (System.ArgumentNullException) { return String.Empty; }
// length is zero, or not an even multiple of four (plus a few other cases)
catch (System.FormatException) { return String.Empty; }
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = null;
CryptoStream encStream = null;
StreamReader sr = null;
string result = String.Empty;
try
{
ms = new MemoryStream(buffer);
// Create a CryptoStream using the memory stream and the
// CSP DES key.
encStream = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Read);
// Create a StreamReader for reading the stream.
sr = new StreamReader(encStream);
// Read the stream as a string.
result = sr.ReadToEnd();
}
finally
{
//close objects
if (sr != null)
sr.Close();
if (encStream != null)
encStream.Close();
if (ms != null)
ms.Close();
}
return result;
}
}
//調(diào)用
string key = "abcdefgh";
string iv = "abcdefgh";
string msg="test string";
string rs1 = CryptoHelper.EncryptDes(msg, System.Text.Encoding.ASCII.GetBytes(key), System.Text.Encoding.ASCII.GetBytes(iv));
string rs2 = CryptoHelper.DecryptDes(rs1, System.Text.Encoding.ASCII.GetBytes(key), System.Text.Encoding.ASCII.GetBytes(iv));
相關(guān)文章
ThinkPHP水印功能實現(xiàn)修復(fù)PNG透明水印并增加JPEG圖片質(zhì)量可調(diào)整
這篇文章主要介紹了ThinkPHP水印功能實現(xiàn)修復(fù)PNG透明水印并增加JPEG圖片質(zhì)量可調(diào)整,包含了對多層水印設(shè)置代碼的修改,修改的部分在注釋里有較為詳細(xì)的說明,非常具有實用價值,需要的朋友可以參考下2014-11-11PHP設(shè)計模式之中介者模式(Mediator Pattern)入門與應(yīng)用案例詳解
這篇文章主要介紹了PHP設(shè)計模式之中介者模式(Mediator Pattern),結(jié)合實例形式詳細(xì)分析了PHP中介者模式的基本概念、原理、應(yīng)用案例與相關(guān)操作注意事項,需要的朋友可以參考下2019-12-12thinkPHP框架可添加js事件的分頁類customPage.class.php完整實例
這篇文章主要介紹了thinkPHP框架可添加js事件的分頁類customPage.class.php,以完整實例形式給出了分頁類customPage.class.php的實現(xiàn)代碼并分析了ajax動態(tài)加載數(shù)據(jù),設(shè)置分頁鏈接等功能,需要的朋友可以參考下2017-03-03使用composer 安裝 laravel框架的方法圖文詳解
這篇文章主要介紹了使用composer 安裝 laravel框架的方法,結(jié)合圖文說明的形式詳細(xì)分析了composer 安裝 laravel框架的具體步驟、相關(guān)命令與操作注意事項,需要的朋友可以參考下2019-08-08PHP 面向?qū)ο蟪绦蛟O(shè)計(oop)學(xué)習(xí)筆記 (五) - PHP 命名空間
PHP 在 5.3.0 以后的版本開始支持命名空間。什么是命名空間?從廣義上來說,命名空間是一種封裝事物的方法。在很多地方都可以見到這種抽象概念。2014-06-06