des加密算法,加密与解密实现方法(php net两个版本),感兴趣的朋友,可以看看,说不好哪天就用上了。
必须说明的是:如果是php5.x及以上版本,需要添加php扩展php_mcrypt,记住哦。
一、PHP版
<?php
/**
des 加密 解密
*/
class STD3Des
{
private $key = "";
private $iv = "";
/**
* 构造,传递二个已经进行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;
2、.net版本
//des 加密 解密
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;
}
}
//调用
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));
看完以上两段代码,不知道你有收获没有?个人比较喜欢php版的des加密与解密方法,简洁清晰。
(www.),专心为您。
您可能感兴趣的文章:
php DES加密解密的代码一例
php使用3des加密的代码(兼容.net)
如何实现呢?请望下看吧。
我这么想的:
遍历一遍多维数组,将所有的键建立索引生成一个一维数组;
每次通过键名去查这个键的上级数组及数据。
indexKey创建索引数组函数:
/**
* FILE_NAME : arr.php FILE_PATH : test/
* 在多维数组中根据键名快速查询其父键以及父键值
*
* @copyright Copyright (c) 2006-2010
* @author Levi
* @package test.arr
* @subpackage
* @version 2011-04-29
* @link www.
*/
header("Content-Type: text/html; charset=utf-8");
$arr = array
(
'china' => array
(
'name' => '中国',
'cite' => array
(
'beijing' => array
(
'name' => '北京',
'site' => array('chaoyang' => '朝阳区', 'xuanwu' => '宣武区')
),
'shanghai' => array
(
'name' => '上海',
'site' => array('jingan' => '静安区', 'huangpu' => '黄浦区')
)
)
)
);
function printA($data)
{
echo '<pre>';
print_r($data);
echo '</pre>';
}
function indexKey($data, $parent = NULL)
{
$arr = array();
foreach ($data as $key => $value)
{
$arr[$key] = $parent;
if (is_array($value))
{
$arr += indexKey($value, $key);
}
}
return (Array)$arr;
}
printA(indexKey($arr));
?>
打印出数据如下
Array
(
[china] =>
[name] => china
[cite] => china
[beijing] => cite
[site] => beijing
[chaoyang] => site
[xuanwu] => site
[shanghai] => cite
[jingan] => site
[huangpu] => site
)
不过上面那样写存在一个问题,即:如果有同名键,会造成丢失,于是我写了这么一个类
只需要将数组传递给对象,对象提供两个接口
printArr 打印索引数组
search 查询键名的父数组键名
IndexKey创建查询索引查询类:
/**
* FILE_NAME : arr.php FILE_PATH : test/
* 在多维数组中根据键名快速查询其父键以及父键值
*
* @copyright Copyright (c) 2006-2010
* @author Levi
* @package test.arr
* @subpackage
* @version 2011-04-29
* @link www.
*/
header("Content-Type: text/html; charset=utf-8");
$arr = array
(
'china' => array
(
'name' => '中国',
'cite' => array
(
'beijing' => array
(
'name' => '北京',
'site' => array('chaoyang' => '朝阳区', 'xuanwu' => '宣武区')
),
'shanghai' => array
(
'name' => '上海',
'site' => array('jingan' => '静安区', 'huangpu' => '黄浦区')
)
)
)
);
function printA($data)
{
echo '<pre>';
print_r($data);
echo '</pre>';
}
function printP(IndexKey $obj, $key)
{
$parent = $obj->search($key);
if ($parent)
{
echo '"'.$key.'" Parent Key is: ';
if (!is_array($parent))
{
echo $parent."<br />\n";
}
else printA($parent);
}
else echo 'NO Parent OR No Search of "'.$key.'"!'."<br /><br />\n";
}
class IndexKey
{
private $_arr = array();
public function __construct($data)
{
$this->_createIndex($data);
}
public function printArr()
{
return (Array)$this->_arr;
}
public function search($key)
{
return isset()($this->_arr[$key]) ? $this->_arr[$key] : NULL;
}
private function _createIndex($data, $parent = NULL)
{
foreach ($data as $key => $value)
{
$this->_checkIndex($key, $parent);
if (is_array($value))
{
$this->_createIndex($value, $key);
}
}
}
private function _checkIndex($key, $parent)
{
$index = isset($this->_arr[$key]) ? $this->_arr[$key] : NULL;
if ($index)
{
if (is_array($index))
{
array_push($this->_arr[$key], $parent);
}
else $this->_arr[$key] = array($index, $parent);
}
else $this->_arr[$key] = $parent;
}
}
$index = (Object)new IndexKey($arr);
printA($index->printArr());
printP($index, 'beijing');
printP($index, 'name');
printP($index, 'china');
?>
最后只差一个数据的输出了,于是我将这个类修改了下
提供了三个对外的方法
printArr 打印索引数组
search 查询键名的父数组键名
parentValue 查询父键值
/**
* FILE_NAME : arr.php FILE_PATH : test/
* 在多维数组中根据键名快速查询其父键以及父键值
*
* @copyright Copyright (c) 2006-2010
* @author Levi
* @package test.arr
* @subpackage
* @version 2011-04-29
* @link www.
*/
header("Content-Type: text/html; charset=utf-8");
$arr = array
(
'china' => array
(
'name' => '中国',
'cite' => array
(
'beijing' => array
(
'name' => '北京',
'site' => array('chaoyang' => '朝阳区', 'xuanwu' => '宣武区')
),
'shanghai' => array
(
'name' => '上海',
'site' => array('jingan' => '静安区', 'huangpu' => '黄浦区')
)
)
)
);
function printA($data)
{
echo '<pre>';
print_r($data);
echo '</pre>';
}
function printP2(IndexArr $obj, $key)
{
$parent = $obj->search($key);
if (!is_array($parent))
{
if ($parent)
{
echo '"'.$key.'" Parent Key is: '.$parent."<br />\n";
}
else echo 'NO Parent OR No Search of "'.$key.'"!'."<br />\n";;
echo '"'.$key.'" Parent "'.$parent.'" Value is: ';
printA($obj->parentValue($key));
}
else printA($parent);
}
class IndexArr
{
private $_arr = array();
public function __construct($data)
{
$this->_createIndex($data);
}
public function printArr()
{
return (Array)$this->_arr;
}
public function search($key)
{
return isset($this->_arr[$key]) ? $this->_arr[$key]['parent'] : NULL;
}
public function parentValue($key)
{
return isset($this->_arr[$key]) ? $this->_arr[$key]['data'] : NULL;
}
private function _createIndex($data, $parent = NULL)
{
foreach ($data as $key => $value)
{
$this->_checkIndex($key, $parent, $data);
if (is_array($value))
{
$this->_createIndex($value, $key);
}
}
}
private function _checkIndex($key, $parent, $data)
{
$data = $parent & isset($data[$parent]) ? $data[$parent] : $data;
!isset($this->_arr[$key]) & $this->_arr[$key] = array('data' => $data, 'parent' => '');
$index = &$this->_arr[$key]['parent'];
if (!empty($index))
{
if (is_array($index))
{
array_push($index, $parent);
}
else $index = array($index, $parent);
}
else $index = $parent;
}
}
$index2 = (Object)new IndexArr($arr);
printA($index2->printArr());
printP2($index2, 'beijing');
printP2($index2, 'name');
printP2($index2, 'china');
?>
PHP获取当前网址及域名的代码,其实就是$_SERVER全局变量的应用,很简单,供初学的朋友参考。
echo SERVER['SERVER_NAME'];//获取来源网址,即点击来到本页的上页网址
echo SERVER["HTTP_REFERER"];
SERVER['REQUEST_URI'];//获取当前域名的后缀
SERVER['HTTP_HOST'];//获取当前域名
dirname(__FILE__);//获取当前文件的物理路径
dirname(__FILE__)."/../";//获取当前文件的上一级物理路径
?>
您可能感兴趣的文章:
PHP获取域名的几个全局变量
php 实现dns域名查询的方法详解(图文)
php 从url中获取域名的实例代码
php获取站点的来路域名的方法
探讨:PHP获取域名及域名IP地址的方法
php获取URL中domain域名的代码一例
PHP获取当前网址及域名的代码
php正则表达式匹配URL中的域名
PHP调用万网接口实现域名查询的功能