首页 > 代码库 > 数据加密与解密的简单原理
数据加密与解密的简单原理
网络上频频报道到某网站用户密码泄漏,用户数据被黑客下载之类的新闻。对用户的敏感数据,私隐没有什么安全可言。出于对用户负责,我们开发者应该对用户的敏感信息进行加密存储,读取后需要解密才能正常显示,增加敏感信息泄漏的难度。算法如下:
<?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码进行运算生成新的字符串。盐码可以全站统一配置,也可针对每一条数据另外存放不同的盐值以增加解密的难度。
数据加密与解密的简单原理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。