首页 > 代码库 > 数据加密与解密的简单原理

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

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

<?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码进行运算生成新的字符串。盐码可以全站统一配置,也可针对每一条数据另外存放不同的盐值以增加解密的难度。

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