码迷,mamicode.com
首页 > 其他好文 > 详细

数据加密与解密的简单原理

时间:2014-11-06 14:50:16      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   使用   for   sp   数据   on   2014   

网络上频频报道到某网站用户密码泄漏,用户数据被黑客下载之类的新闻。对用户的敏感数据,私隐没有什么安全可言。出于对用户负责,我们开发者应该对用户的敏感信息进行加密存储,读取后需要解密才能正常显示,增加敏感信息泄漏的难度。算法如下:

<?php
class sys {
	
	/**
	 * 使用盐对内容加密
	 * @param string $context 需要加密的数据
	 * @param string $mask 密码盐
	 * @return string
	 */
	public static function security_encode( $context, $mask ) {
		$new_mask_word = '';
		$new_word      = '';
		$word_length   = strlen( $context );
		$mask_length   = strlen( $mask );
		$mask          = str_split( $mask );
		$word          = str_split( $context );
		$loop          = 0;
		
		for( $i=0; $i<$word_length; $i++ ) {
			if( $loop == $mask_length ){
				$loop = 0;
			}
			$new_mask_word .= $mask[$loop];
			$loop++;
		}
		
		for( $i=0; $i<$word_length; $i++) {
			$new_word .= chr( ord($word[$i])+ord($new_mask_word[$i]) );
		}
		return $new_word;
	}
	
	/**
	 * 使用盐对内容解密
	 * @param string $context 需要解密的数据
	 * @param string $mask 密码盐
	 * @return string
	 */
	public static function security_decode( $context, $mask ) {
		$new_mask_word = '';
		$new_word      = '';
		$word_length   = strlen( $context );
		$mask_length   = strlen( $mask );
		$mask          = str_split( $mask );
		$word          = str_split( $context );
		$loop          = 0;
		
		for( $i=0; $i<$word_length; $i++ ) {
			if( $loop == $mask_length ){
				$loop = 0;
			}
			$new_mask_word .= $mask[$loop];
			$loop++;
		}
		
		for( $i=0; $i<$word_length; $i++) {
			$new_word .= chr( ord($word[$i])-ord($new_mask_word[$i]) );
		}
		return $new_word;
	}
}

原理很简单,就是使用掩码对数据的asscii码进行运算生成新的字符串。盐码可以全站统一配置,也可针对每一条数据另外存放不同的盐值以增加解密的难度。

数据加密与解密的简单原理

标签:blog   io   ar   使用   for   sp   数据   on   2014   

原文地址:http://blog.csdn.net/yagas/article/details/40860351

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!