安全加密

安全加密

记录接口中常见的简单内容加密方式:恺撒加密的PHP实现

PHPzkbhj 发表了文章 • 0 个评论 • 1618 次浏览 • 2017-05-23 16:17 • 来自相关话题

问题描述:
    凯撒密码是把字母表中的每个字母用该字母后的某个字母进行代替。
    凯撒密码的通用加密算法是:C=E(P)=(P+k) mod 260<k<26。
    凯撒密码的通用解密算法是:P=D(C)=(P-k) mod 260<k<26。

基本要求:
    实现凯撒密码的加密、解密算法,能够根据用户选择秘钥(移位数)和明文进行加解密。

实现提示:
    (1) 用户可以通过命令实现密钥和明文的选择;
    (2) 由于字母表中共有26个字符,因此,移位前应先将移动的位数(key)和26取模。
    (3) 尽管移位前已经将移动的位数和26取模,但是通过这种方式实现的右移和左移仍可能发生超界。因此,移位后仍要判断是否超界。
 一段Python代码:
#License:GPL v3 or higher.
#Copyright (C) 2012 Biergaizi

import sys
times=0
plain=input("Please input your plain text: ")
value=input("Please input your key(included negatives): ")
secret_list=list(plain)
secret_list_len=len(secret_list)

try:
value=int(value)
except ValueError:
print("Please input an integer.")
sys.exit()


#a的ANSI码是97, z的ANSI码是122。
#A的ANSI码是65, Z的ANSI码是90。

print("")
print("secret: ",end='')

while times < secret_list_len:
times=times+1
#ansi_raw即没有经过任何处理的原始ANSI。
ansi_raw=ord(secret_list[0+times-1])

#ansi是经过移位加密的ANSI。
ansi=ansi_raw+int(value)

#word是用户输入的原始字符。
word=(secret_list[0+times-1])

#如果ansi_raw小于65或大于90,而且还不是小写字母,那么则说明它根本就不是字母。不加密,直接输出原始内容。
if (ansi_raw < 65 or ansi_raw > 90) and word.islower() == False :
print(word,end='')

#如果ansi_raw小于97或大于122,而且还不是大写字母,那么则说明它根本不是字母。不加密,直接输出原始内容。
elif (ansi_raw < 97 or ansi_raw > 122) and word.isupper() == False:
print(word,end='')

#否则,它就是字母。
else:
#如果它是大写字母,而且ANSI码大于90,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。
while word.isupper() == True and ansi > 90:
ansi = -26 + ansi

#如果它是大写字母,而且ANSI码小于65,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。
while word.isupper() == True and ansi < 65:
ansi = 26 + ansi

#如果它是小写字母,而且ANSI码大于122,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。
while word.isupper() == False and ansi > 122:
ansi = -26 + ansi

#如果它是小写字母,而且ANSI码小于97,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。
while word.isupper() == False and ansi < 97:
ansi = 26 + ansi

#将处理过的ANSI转换为字符,来输出密文。
print(chr(ansi),end='')

print("")
思路:
①加密的整体思路是不是字母的数字不进行加密,若是小写字母,对字母移位(ASCII + 秘钥)后若ASCII码小于97或大于122则表示字母越界,只需要加26或减26直到移位后的在小写字母的范围内即可;同理大写字母也是相同的过程;
②解密的整体思路只需将移位后的的字母还原(ASCII - 秘钥),其他步骤和加密一样。

有了思路接下来写PHP代码:
<?php
class Caesar{

private $simple;//明文
private $secretKey;//秘钥
private $ciphertext;//密文
private $opResult;//加密或解密后的结果
private $operatorType;//操作类型;0代表加密1:代表解密

/**
* __construct 构造函数初始化类属性
* @param String $input 输入字符内容
* @param integer $secretKey 秘钥
* @param integer $operatorType 操作类型;0代表加密1:代表解密
*/
public function __construct($input,$secretKey = 1,$operatorType = 0){

$this->operatorType = intval($operatorType);
if($this->operatorType == 0){
$this->simple = $input;
$this->ciphertext = "";
}elseif ($this->operatorType == 1) {
$this->ciphertext = $input;
$this->simple = "";
}else{
echo "please input right operatorType";
exit();
}
$this->opResult = "";
$this->secretKey = intval($secretKey);
}


/**
* crypto 解密或加密函数
* @return String 加解密后的结果
*/
public function crypto(){

//获取加密解密后的字符串
$charArray = ($this->operatorType==0) ? str_split ($this->simple) : str_split ($this->ciphertext);

//遍历整个字符数组进行加密解密操作
foreach ($charArray as $key => $value) {
$asciiOriginal = ord($value);//字符的ASCII值
$asciiTransfrom =($this->operatorType==0) ? $asciiOriginal+$this->secretKey : $asciiOriginal-$this->secretKey;//加解密后的ASCII的值

//值得注意的是||的优先级比&&的优先级低,若不加括号会造成问题;
//若不是大写字母并且$asciiOriginal的值小于65或大于90则不加密
if ( ($asciiOriginal<65 || $asciiOriginal > 90 ) && ($this->isLowerCase($value)==false)) {
$this->opResult .= $value;

//若不是大写字母并且$asciiOriginal的值小于97或大于122则不加密
}elseif ( ($asciiOriginal<97 || $asciiOriginal > 122) &&($this->isCapital($value)==false)) {
$this->opResult .= $value;
}else{

//循环处理越界的问题
while ($asciiTransfrom<65&&$this->isCapital($value)) {
$asciiTransfrom += 26;
}

while ($asciiTransfrom>90&&$this->isCapital($value)) {
$asciiTransfrom -= 26;
}

while ($asciiTransfrom<97&&$this->isLowerCase($value)) {
$asciiTransfrom += 26;
}

while ($asciiTransfrom>122&&$this->isLowerCase($value)) {
$asciiTransfrom -= 26;
}
}
$this->opResult .= chr($asciiTransfrom);
}
return $this->opResult;
}

/**
* isLowerCase 判断是否为小写字母
* @param char $char 传入的字符
* @return boolean 返回boolean类型
*/
private function isLowerCase($char){
if(preg_match("/^[a-z]+$/", $char)){
return true;
}else{
return false;
}
}

/**
* isCapital 判断是否为小写字母
* @param char $char 传入的字符
* @return boolean 返回boolean类型
*/
private function isCapital($char){
if(preg_match("/^[A-Z]+$/", $char)){
return true;
}else{
return false;
}
}

}

$string = $_SERVER['argv'][1];
if (!$string) {
echo "please input parameter";
}
$test = new Caesar($string,1,1);
echo $test->crypto();
?>
  查看全部
问题描述:
    凯撒密码是把字母表中的每个字母用该字母后的某个字母进行代替。
    凯撒密码的通用加密算法是:C=E(P)=(P+k) mod 260<k<26。
    凯撒密码的通用解密算法是:P=D(C)=(P-k) mod 260<k<26。

基本要求:
    实现凯撒密码的加密、解密算法,能够根据用户选择秘钥(移位数)和明文进行加解密。

实现提示:
    (1) 用户可以通过命令实现密钥和明文的选择;
    (2) 由于字母表中共有26个字符,因此,移位前应先将移动的位数(key)和26取模。
    (3) 尽管移位前已经将移动的位数和26取模,但是通过这种方式实现的右移和左移仍可能发生超界。因此,移位后仍要判断是否超界。
 一段Python代码:
#License:GPL v3 or higher.
#Copyright (C) 2012 Biergaizi

import sys
times=0
plain=input("Please input your plain text: ")
value=input("Please input your key(included negatives): ")
secret_list=list(plain)
secret_list_len=len(secret_list)

try:
value=int(value)
except ValueError:
print("Please input an integer.")
sys.exit()


#a的ANSI码是97, z的ANSI码是122。
#A的ANSI码是65, Z的ANSI码是90。

print("")
print("secret: ",end='')

while times < secret_list_len:
times=times+1
#ansi_raw即没有经过任何处理的原始ANSI。
ansi_raw=ord(secret_list[0+times-1])

#ansi是经过移位加密的ANSI。
ansi=ansi_raw+int(value)

#word是用户输入的原始字符。
word=(secret_list[0+times-1])

#如果ansi_raw小于65或大于90,而且还不是小写字母,那么则说明它根本就不是字母。不加密,直接输出原始内容。
if (ansi_raw < 65 or ansi_raw > 90) and word.islower() == False :
print(word,end='')

#如果ansi_raw小于97或大于122,而且还不是大写字母,那么则说明它根本不是字母。不加密,直接输出原始内容。
elif (ansi_raw < 97 or ansi_raw > 122) and word.isupper() == False:
print(word,end='')

#否则,它就是字母。
else:
#如果它是大写字母,而且ANSI码大于90,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。
while word.isupper() == True and ansi > 90:
ansi = -26 + ansi

#如果它是大写字母,而且ANSI码小于65,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。
while word.isupper() == True and ansi < 65:
ansi = 26 + ansi

#如果它是小写字母,而且ANSI码大于122,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。
while word.isupper() == False and ansi > 122:
ansi = -26 + ansi

#如果它是小写字母,而且ANSI码小于97,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。
while word.isupper() == False and ansi < 97:
ansi = 26 + ansi

#将处理过的ANSI转换为字符,来输出密文。
print(chr(ansi),end='')

print("")

思路:
①加密的整体思路是不是字母的数字不进行加密,若是小写字母,对字母移位(ASCII + 秘钥)后若ASCII码小于97或大于122则表示字母越界,只需要加26或减26直到移位后的在小写字母的范围内即可;同理大写字母也是相同的过程;
②解密的整体思路只需将移位后的的字母还原(ASCII - 秘钥),其他步骤和加密一样。

有了思路接下来写PHP代码:
<?php
class Caesar{

private $simple;//明文
private $secretKey;//秘钥
private $ciphertext;//密文
private $opResult;//加密或解密后的结果
private $operatorType;//操作类型;0代表加密1:代表解密

/**
* __construct 构造函数初始化类属性
* @param String $input 输入字符内容
* @param integer $secretKey 秘钥
* @param integer $operatorType 操作类型;0代表加密1:代表解密
*/
public function __construct($input,$secretKey = 1,$operatorType = 0){

$this->operatorType = intval($operatorType);
if($this->operatorType == 0){
$this->simple = $input;
$this->ciphertext = "";
}elseif ($this->operatorType == 1) {
$this->ciphertext = $input;
$this->simple = "";
}else{
echo "please input right operatorType";
exit();
}
$this->opResult = "";
$this->secretKey = intval($secretKey);
}


/**
* crypto 解密或加密函数
* @return String 加解密后的结果
*/
public function crypto(){

//获取加密解密后的字符串
$charArray = ($this->operatorType==0) ? str_split ($this->simple) : str_split ($this->ciphertext);

//遍历整个字符数组进行加密解密操作
foreach ($charArray as $key => $value) {
$asciiOriginal = ord($value);//字符的ASCII值
$asciiTransfrom =($this->operatorType==0) ? $asciiOriginal+$this->secretKey : $asciiOriginal-$this->secretKey;//加解密后的ASCII的值

//值得注意的是||的优先级比&&的优先级低,若不加括号会造成问题;
//若不是大写字母并且$asciiOriginal的值小于65或大于90则不加密
if ( ($asciiOriginal<65 || $asciiOriginal > 90 ) && ($this->isLowerCase($value)==false)) {
$this->opResult .= $value;

//若不是大写字母并且$asciiOriginal的值小于97或大于122则不加密
}elseif ( ($asciiOriginal<97 || $asciiOriginal > 122) &&($this->isCapital($value)==false)) {
$this->opResult .= $value;
}else{

//循环处理越界的问题
while ($asciiTransfrom<65&&$this->isCapital($value)) {
$asciiTransfrom += 26;
}

while ($asciiTransfrom>90&&$this->isCapital($value)) {
$asciiTransfrom -= 26;
}

while ($asciiTransfrom<97&&$this->isLowerCase($value)) {
$asciiTransfrom += 26;
}

while ($asciiTransfrom>122&&$this->isLowerCase($value)) {
$asciiTransfrom -= 26;
}
}
$this->opResult .= chr($asciiTransfrom);
}
return $this->opResult;
}

/**
* isLowerCase 判断是否为小写字母
* @param char $char 传入的字符
* @return boolean 返回boolean类型
*/
private function isLowerCase($char){
if(preg_match("/^[a-z]+$/", $char)){
return true;
}else{
return false;
}
}

/**
* isCapital 判断是否为小写字母
* @param char $char 传入的字符
* @return boolean 返回boolean类型
*/
private function isCapital($char){
if(preg_match("/^[A-Z]+$/", $char)){
return true;
}else{
return false;
}
}

}

$string = $_SERVER['argv'][1];
if (!$string) {
echo "please input parameter";
}
$test = new Caesar($string,1,1);
echo $test->crypto();
?>

 

兼容Java的AES加密

PHPzkbhj 发表了文章 • 0 个评论 • 1532 次浏览 • 2016-08-15 16:26 • 来自相关话题

 <?php
class CryptAES
{
protected $cipher = MCRYPT_RIJNDAEL_128;
protected $mode = MCRYPT_MODE_ECB;
protected $pad_method = NULL;
protected $secret_key = '';
protected $iv = '';

public function set_cipher($cipher)
{
$this->cipher = $cipher;
}

public function set_mode($mode)
{
$this->mode = $mode;
}

public function set_iv($iv)
{
$this->iv = $iv;
}

public function set_key($key)
{
$this->secret_key = $key;
}

public function require_pkcs5()
{
$this->pad_method = 'pkcs5';
}

protected function pad_or_unpad($str, $ext)
{
if ( is_null($this->pad_method) )
{
return $str;
}
else
{
$func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad';
if ( is_callable($func_name) )
{
$size = mcrypt_get_block_size($this->cipher, $this->mode);
return call_user_func($func_name, $str, $size);
}
}
return $str;
}

protected function pad($str)
{
return $this->pad_or_unpad($str, '');
}

protected function unpad($str)
{
return $this->pad_or_unpad($str, 'un');
}

public function encrypt($str)
{
$str = $this->pad($str);
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');

if ( empty($this->iv) )
{
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
}
else
{
$iv = $this->iv;
}

mcrypt_generic_init($td, $this->secret_key, $iv);
$cyper_text = mcrypt_generic($td, $str);
$rt=base64_encode($cyper_text);
//$rt = bin2hex($cyper_text);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return $rt;
}

public function decrypt($str){
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');

if ( empty($this->iv) )
{
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
}
else
{
$iv = $this->iv;
}

mcrypt_generic_init($td, $this->secret_key, $iv);
//$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));
$decrypted_text = mdecrypt_generic($td, base64_decode($str));
$rt = $decrypted_text;
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return $this->unpad($rt);
}

public static function hex2bin($hexdata) {
$bindata = '';
$length = strlen($hexdata);
for ($i=0; $i < $length; $i += 2)
{
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}

public static function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}

public static function pkcs5_unpad($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);
}
}

$keyStr = '8dfw091qdfdl5l2tt6wewewfdqxj';
$plainText = 'this is a string will be AES_Encrypt1';
$params = array(
"uid"=>"77a968d1-1d67-6fc0-fb48-88848f99da63",
"systemSource"=> "ami"
);
$string = json_encode($params);
$aes = new CryptAES();
$aes->set_key($keyStr);
$aes->require_pkcs5();
$encText = $aes->encrypt($string);
$decString = $aes->decrypt($encText);

echo $encText,"<br>",$string;

?> 查看全部
 
<?php
class CryptAES
{
protected $cipher = MCRYPT_RIJNDAEL_128;
protected $mode = MCRYPT_MODE_ECB;
protected $pad_method = NULL;
protected $secret_key = '';
protected $iv = '';

public function set_cipher($cipher)
{
$this->cipher = $cipher;
}

public function set_mode($mode)
{
$this->mode = $mode;
}

public function set_iv($iv)
{
$this->iv = $iv;
}

public function set_key($key)
{
$this->secret_key = $key;
}

public function require_pkcs5()
{
$this->pad_method = 'pkcs5';
}

protected function pad_or_unpad($str, $ext)
{
if ( is_null($this->pad_method) )
{
return $str;
}
else
{
$func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad';
if ( is_callable($func_name) )
{
$size = mcrypt_get_block_size($this->cipher, $this->mode);
return call_user_func($func_name, $str, $size);
}
}
return $str;
}

protected function pad($str)
{
return $this->pad_or_unpad($str, '');
}

protected function unpad($str)
{
return $this->pad_or_unpad($str, 'un');
}

public function encrypt($str)
{
$str = $this->pad($str);
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');

if ( empty($this->iv) )
{
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
}
else
{
$iv = $this->iv;
}

mcrypt_generic_init($td, $this->secret_key, $iv);
$cyper_text = mcrypt_generic($td, $str);
$rt=base64_encode($cyper_text);
//$rt = bin2hex($cyper_text);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return $rt;
}

public function decrypt($str){
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');

if ( empty($this->iv) )
{
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
}
else
{
$iv = $this->iv;
}

mcrypt_generic_init($td, $this->secret_key, $iv);
//$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));
$decrypted_text = mdecrypt_generic($td, base64_decode($str));
$rt = $decrypted_text;
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return $this->unpad($rt);
}

public static function hex2bin($hexdata) {
$bindata = '';
$length = strlen($hexdata);
for ($i=0; $i < $length; $i += 2)
{
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}

public static function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}

public static function pkcs5_unpad($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);
}
}

$keyStr = '8dfw091qdfdl5l2tt6wewewfdqxj';
$plainText = 'this is a string will be AES_Encrypt1';
$params = array(
"uid"=>"77a968d1-1d67-6fc0-fb48-88848f99da63",
"systemSource"=> "ami"
);
$string = json_encode($params);
$aes = new CryptAES();
$aes->set_key($keyStr);
$aes->require_pkcs5();
$encText = $aes->encrypt($string);
$decString = $aes->decrypt($encText);

echo $encText,"<br>",$string;

?>

记录接口中常见的简单内容加密方式:恺撒加密的PHP实现

PHPzkbhj 发表了文章 • 0 个评论 • 1618 次浏览 • 2017-05-23 16:17 • 来自相关话题

问题描述:
    凯撒密码是把字母表中的每个字母用该字母后的某个字母进行代替。
    凯撒密码的通用加密算法是:C=E(P)=(P+k) mod 260<k<26。
    凯撒密码的通用解密算法是:P=D(C)=(P-k) mod 260<k<26。

基本要求:
    实现凯撒密码的加密、解密算法,能够根据用户选择秘钥(移位数)和明文进行加解密。

实现提示:
    (1) 用户可以通过命令实现密钥和明文的选择;
    (2) 由于字母表中共有26个字符,因此,移位前应先将移动的位数(key)和26取模。
    (3) 尽管移位前已经将移动的位数和26取模,但是通过这种方式实现的右移和左移仍可能发生超界。因此,移位后仍要判断是否超界。
 一段Python代码:
#License:GPL v3 or higher.
#Copyright (C) 2012 Biergaizi

import sys
times=0
plain=input("Please input your plain text: ")
value=input("Please input your key(included negatives): ")
secret_list=list(plain)
secret_list_len=len(secret_list)

try:
value=int(value)
except ValueError:
print("Please input an integer.")
sys.exit()


#a的ANSI码是97, z的ANSI码是122。
#A的ANSI码是65, Z的ANSI码是90。

print("")
print("secret: ",end='')

while times < secret_list_len:
times=times+1
#ansi_raw即没有经过任何处理的原始ANSI。
ansi_raw=ord(secret_list[0+times-1])

#ansi是经过移位加密的ANSI。
ansi=ansi_raw+int(value)

#word是用户输入的原始字符。
word=(secret_list[0+times-1])

#如果ansi_raw小于65或大于90,而且还不是小写字母,那么则说明它根本就不是字母。不加密,直接输出原始内容。
if (ansi_raw < 65 or ansi_raw > 90) and word.islower() == False :
print(word,end='')

#如果ansi_raw小于97或大于122,而且还不是大写字母,那么则说明它根本不是字母。不加密,直接输出原始内容。
elif (ansi_raw < 97 or ansi_raw > 122) and word.isupper() == False:
print(word,end='')

#否则,它就是字母。
else:
#如果它是大写字母,而且ANSI码大于90,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。
while word.isupper() == True and ansi > 90:
ansi = -26 + ansi

#如果它是大写字母,而且ANSI码小于65,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。
while word.isupper() == True and ansi < 65:
ansi = 26 + ansi

#如果它是小写字母,而且ANSI码大于122,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。
while word.isupper() == False and ansi > 122:
ansi = -26 + ansi

#如果它是小写字母,而且ANSI码小于97,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。
while word.isupper() == False and ansi < 97:
ansi = 26 + ansi

#将处理过的ANSI转换为字符,来输出密文。
print(chr(ansi),end='')

print("")
思路:
①加密的整体思路是不是字母的数字不进行加密,若是小写字母,对字母移位(ASCII + 秘钥)后若ASCII码小于97或大于122则表示字母越界,只需要加26或减26直到移位后的在小写字母的范围内即可;同理大写字母也是相同的过程;
②解密的整体思路只需将移位后的的字母还原(ASCII - 秘钥),其他步骤和加密一样。

有了思路接下来写PHP代码:
<?php
class Caesar{

private $simple;//明文
private $secretKey;//秘钥
private $ciphertext;//密文
private $opResult;//加密或解密后的结果
private $operatorType;//操作类型;0代表加密1:代表解密

/**
* __construct 构造函数初始化类属性
* @param String $input 输入字符内容
* @param integer $secretKey 秘钥
* @param integer $operatorType 操作类型;0代表加密1:代表解密
*/
public function __construct($input,$secretKey = 1,$operatorType = 0){

$this->operatorType = intval($operatorType);
if($this->operatorType == 0){
$this->simple = $input;
$this->ciphertext = "";
}elseif ($this->operatorType == 1) {
$this->ciphertext = $input;
$this->simple = "";
}else{
echo "please input right operatorType";
exit();
}
$this->opResult = "";
$this->secretKey = intval($secretKey);
}


/**
* crypto 解密或加密函数
* @return String 加解密后的结果
*/
public function crypto(){

//获取加密解密后的字符串
$charArray = ($this->operatorType==0) ? str_split ($this->simple) : str_split ($this->ciphertext);

//遍历整个字符数组进行加密解密操作
foreach ($charArray as $key => $value) {
$asciiOriginal = ord($value);//字符的ASCII值
$asciiTransfrom =($this->operatorType==0) ? $asciiOriginal+$this->secretKey : $asciiOriginal-$this->secretKey;//加解密后的ASCII的值

//值得注意的是||的优先级比&&的优先级低,若不加括号会造成问题;
//若不是大写字母并且$asciiOriginal的值小于65或大于90则不加密
if ( ($asciiOriginal<65 || $asciiOriginal > 90 ) && ($this->isLowerCase($value)==false)) {
$this->opResult .= $value;

//若不是大写字母并且$asciiOriginal的值小于97或大于122则不加密
}elseif ( ($asciiOriginal<97 || $asciiOriginal > 122) &&($this->isCapital($value)==false)) {
$this->opResult .= $value;
}else{

//循环处理越界的问题
while ($asciiTransfrom<65&&$this->isCapital($value)) {
$asciiTransfrom += 26;
}

while ($asciiTransfrom>90&&$this->isCapital($value)) {
$asciiTransfrom -= 26;
}

while ($asciiTransfrom<97&&$this->isLowerCase($value)) {
$asciiTransfrom += 26;
}

while ($asciiTransfrom>122&&$this->isLowerCase($value)) {
$asciiTransfrom -= 26;
}
}
$this->opResult .= chr($asciiTransfrom);
}
return $this->opResult;
}

/**
* isLowerCase 判断是否为小写字母
* @param char $char 传入的字符
* @return boolean 返回boolean类型
*/
private function isLowerCase($char){
if(preg_match("/^[a-z]+$/", $char)){
return true;
}else{
return false;
}
}

/**
* isCapital 判断是否为小写字母
* @param char $char 传入的字符
* @return boolean 返回boolean类型
*/
private function isCapital($char){
if(preg_match("/^[A-Z]+$/", $char)){
return true;
}else{
return false;
}
}

}

$string = $_SERVER['argv'][1];
if (!$string) {
echo "please input parameter";
}
$test = new Caesar($string,1,1);
echo $test->crypto();
?>
  查看全部
问题描述:
    凯撒密码是把字母表中的每个字母用该字母后的某个字母进行代替。
    凯撒密码的通用加密算法是:C=E(P)=(P+k) mod 260<k<26。
    凯撒密码的通用解密算法是:P=D(C)=(P-k) mod 260<k<26。

基本要求:
    实现凯撒密码的加密、解密算法,能够根据用户选择秘钥(移位数)和明文进行加解密。

实现提示:
    (1) 用户可以通过命令实现密钥和明文的选择;
    (2) 由于字母表中共有26个字符,因此,移位前应先将移动的位数(key)和26取模。
    (3) 尽管移位前已经将移动的位数和26取模,但是通过这种方式实现的右移和左移仍可能发生超界。因此,移位后仍要判断是否超界。
 一段Python代码:
#License:GPL v3 or higher.
#Copyright (C) 2012 Biergaizi

import sys
times=0
plain=input("Please input your plain text: ")
value=input("Please input your key(included negatives): ")
secret_list=list(plain)
secret_list_len=len(secret_list)

try:
value=int(value)
except ValueError:
print("Please input an integer.")
sys.exit()


#a的ANSI码是97, z的ANSI码是122。
#A的ANSI码是65, Z的ANSI码是90。

print("")
print("secret: ",end='')

while times < secret_list_len:
times=times+1
#ansi_raw即没有经过任何处理的原始ANSI。
ansi_raw=ord(secret_list[0+times-1])

#ansi是经过移位加密的ANSI。
ansi=ansi_raw+int(value)

#word是用户输入的原始字符。
word=(secret_list[0+times-1])

#如果ansi_raw小于65或大于90,而且还不是小写字母,那么则说明它根本就不是字母。不加密,直接输出原始内容。
if (ansi_raw < 65 or ansi_raw > 90) and word.islower() == False :
print(word,end='')

#如果ansi_raw小于97或大于122,而且还不是大写字母,那么则说明它根本不是字母。不加密,直接输出原始内容。
elif (ansi_raw < 97 or ansi_raw > 122) and word.isupper() == False:
print(word,end='')

#否则,它就是字母。
else:
#如果它是大写字母,而且ANSI码大于90,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。
while word.isupper() == True and ansi > 90:
ansi = -26 + ansi

#如果它是大写字母,而且ANSI码小于65,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。
while word.isupper() == True and ansi < 65:
ansi = 26 + ansi

#如果它是小写字母,而且ANSI码大于122,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。
while word.isupper() == False and ansi > 122:
ansi = -26 + ansi

#如果它是小写字母,而且ANSI码小于97,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。
while word.isupper() == False and ansi < 97:
ansi = 26 + ansi

#将处理过的ANSI转换为字符,来输出密文。
print(chr(ansi),end='')

print("")

思路:
①加密的整体思路是不是字母的数字不进行加密,若是小写字母,对字母移位(ASCII + 秘钥)后若ASCII码小于97或大于122则表示字母越界,只需要加26或减26直到移位后的在小写字母的范围内即可;同理大写字母也是相同的过程;
②解密的整体思路只需将移位后的的字母还原(ASCII - 秘钥),其他步骤和加密一样。

有了思路接下来写PHP代码:
<?php
class Caesar{

private $simple;//明文
private $secretKey;//秘钥
private $ciphertext;//密文
private $opResult;//加密或解密后的结果
private $operatorType;//操作类型;0代表加密1:代表解密

/**
* __construct 构造函数初始化类属性
* @param String $input 输入字符内容
* @param integer $secretKey 秘钥
* @param integer $operatorType 操作类型;0代表加密1:代表解密
*/
public function __construct($input,$secretKey = 1,$operatorType = 0){

$this->operatorType = intval($operatorType);
if($this->operatorType == 0){
$this->simple = $input;
$this->ciphertext = "";
}elseif ($this->operatorType == 1) {
$this->ciphertext = $input;
$this->simple = "";
}else{
echo "please input right operatorType";
exit();
}
$this->opResult = "";
$this->secretKey = intval($secretKey);
}


/**
* crypto 解密或加密函数
* @return String 加解密后的结果
*/
public function crypto(){

//获取加密解密后的字符串
$charArray = ($this->operatorType==0) ? str_split ($this->simple) : str_split ($this->ciphertext);

//遍历整个字符数组进行加密解密操作
foreach ($charArray as $key => $value) {
$asciiOriginal = ord($value);//字符的ASCII值
$asciiTransfrom =($this->operatorType==0) ? $asciiOriginal+$this->secretKey : $asciiOriginal-$this->secretKey;//加解密后的ASCII的值

//值得注意的是||的优先级比&&的优先级低,若不加括号会造成问题;
//若不是大写字母并且$asciiOriginal的值小于65或大于90则不加密
if ( ($asciiOriginal<65 || $asciiOriginal > 90 ) && ($this->isLowerCase($value)==false)) {
$this->opResult .= $value;

//若不是大写字母并且$asciiOriginal的值小于97或大于122则不加密
}elseif ( ($asciiOriginal<97 || $asciiOriginal > 122) &&($this->isCapital($value)==false)) {
$this->opResult .= $value;
}else{

//循环处理越界的问题
while ($asciiTransfrom<65&&$this->isCapital($value)) {
$asciiTransfrom += 26;
}

while ($asciiTransfrom>90&&$this->isCapital($value)) {
$asciiTransfrom -= 26;
}

while ($asciiTransfrom<97&&$this->isLowerCase($value)) {
$asciiTransfrom += 26;
}

while ($asciiTransfrom>122&&$this->isLowerCase($value)) {
$asciiTransfrom -= 26;
}
}
$this->opResult .= chr($asciiTransfrom);
}
return $this->opResult;
}

/**
* isLowerCase 判断是否为小写字母
* @param char $char 传入的字符
* @return boolean 返回boolean类型
*/
private function isLowerCase($char){
if(preg_match("/^[a-z]+$/", $char)){
return true;
}else{
return false;
}
}

/**
* isCapital 判断是否为小写字母
* @param char $char 传入的字符
* @return boolean 返回boolean类型
*/
private function isCapital($char){
if(preg_match("/^[A-Z]+$/", $char)){
return true;
}else{
return false;
}
}

}

$string = $_SERVER['argv'][1];
if (!$string) {
echo "please input parameter";
}
$test = new Caesar($string,1,1);
echo $test->crypto();
?>

 

兼容Java的AES加密

PHPzkbhj 发表了文章 • 0 个评论 • 1532 次浏览 • 2016-08-15 16:26 • 来自相关话题

 <?php
class CryptAES
{
protected $cipher = MCRYPT_RIJNDAEL_128;
protected $mode = MCRYPT_MODE_ECB;
protected $pad_method = NULL;
protected $secret_key = '';
protected $iv = '';

public function set_cipher($cipher)
{
$this->cipher = $cipher;
}

public function set_mode($mode)
{
$this->mode = $mode;
}

public function set_iv($iv)
{
$this->iv = $iv;
}

public function set_key($key)
{
$this->secret_key = $key;
}

public function require_pkcs5()
{
$this->pad_method = 'pkcs5';
}

protected function pad_or_unpad($str, $ext)
{
if ( is_null($this->pad_method) )
{
return $str;
}
else
{
$func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad';
if ( is_callable($func_name) )
{
$size = mcrypt_get_block_size($this->cipher, $this->mode);
return call_user_func($func_name, $str, $size);
}
}
return $str;
}

protected function pad($str)
{
return $this->pad_or_unpad($str, '');
}

protected function unpad($str)
{
return $this->pad_or_unpad($str, 'un');
}

public function encrypt($str)
{
$str = $this->pad($str);
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');

if ( empty($this->iv) )
{
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
}
else
{
$iv = $this->iv;
}

mcrypt_generic_init($td, $this->secret_key, $iv);
$cyper_text = mcrypt_generic($td, $str);
$rt=base64_encode($cyper_text);
//$rt = bin2hex($cyper_text);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return $rt;
}

public function decrypt($str){
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');

if ( empty($this->iv) )
{
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
}
else
{
$iv = $this->iv;
}

mcrypt_generic_init($td, $this->secret_key, $iv);
//$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));
$decrypted_text = mdecrypt_generic($td, base64_decode($str));
$rt = $decrypted_text;
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return $this->unpad($rt);
}

public static function hex2bin($hexdata) {
$bindata = '';
$length = strlen($hexdata);
for ($i=0; $i < $length; $i += 2)
{
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}

public static function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}

public static function pkcs5_unpad($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);
}
}

$keyStr = '8dfw091qdfdl5l2tt6wewewfdqxj';
$plainText = 'this is a string will be AES_Encrypt1';
$params = array(
"uid"=>"77a968d1-1d67-6fc0-fb48-88848f99da63",
"systemSource"=> "ami"
);
$string = json_encode($params);
$aes = new CryptAES();
$aes->set_key($keyStr);
$aes->require_pkcs5();
$encText = $aes->encrypt($string);
$decString = $aes->decrypt($encText);

echo $encText,"<br>",$string;

?> 查看全部
 
<?php
class CryptAES
{
protected $cipher = MCRYPT_RIJNDAEL_128;
protected $mode = MCRYPT_MODE_ECB;
protected $pad_method = NULL;
protected $secret_key = '';
protected $iv = '';

public function set_cipher($cipher)
{
$this->cipher = $cipher;
}

public function set_mode($mode)
{
$this->mode = $mode;
}

public function set_iv($iv)
{
$this->iv = $iv;
}

public function set_key($key)
{
$this->secret_key = $key;
}

public function require_pkcs5()
{
$this->pad_method = 'pkcs5';
}

protected function pad_or_unpad($str, $ext)
{
if ( is_null($this->pad_method) )
{
return $str;
}
else
{
$func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad';
if ( is_callable($func_name) )
{
$size = mcrypt_get_block_size($this->cipher, $this->mode);
return call_user_func($func_name, $str, $size);
}
}
return $str;
}

protected function pad($str)
{
return $this->pad_or_unpad($str, '');
}

protected function unpad($str)
{
return $this->pad_or_unpad($str, 'un');
}

public function encrypt($str)
{
$str = $this->pad($str);
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');

if ( empty($this->iv) )
{
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
}
else
{
$iv = $this->iv;
}

mcrypt_generic_init($td, $this->secret_key, $iv);
$cyper_text = mcrypt_generic($td, $str);
$rt=base64_encode($cyper_text);
//$rt = bin2hex($cyper_text);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return $rt;
}

public function decrypt($str){
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');

if ( empty($this->iv) )
{
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
}
else
{
$iv = $this->iv;
}

mcrypt_generic_init($td, $this->secret_key, $iv);
//$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));
$decrypted_text = mdecrypt_generic($td, base64_decode($str));
$rt = $decrypted_text;
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return $this->unpad($rt);
}

public static function hex2bin($hexdata) {
$bindata = '';
$length = strlen($hexdata);
for ($i=0; $i < $length; $i += 2)
{
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}

public static function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}

public static function pkcs5_unpad($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);
}
}

$keyStr = '8dfw091qdfdl5l2tt6wewewfdqxj';
$plainText = 'this is a string will be AES_Encrypt1';
$params = array(
"uid"=>"77a968d1-1d67-6fc0-fb48-88848f99da63",
"systemSource"=> "ami"
);
$string = json_encode($params);
$aes = new CryptAES();
$aes->set_key($keyStr);
$aes->require_pkcs5();
$encText = $aes->encrypt($string);
$decString = $aes->decrypt($encText);

echo $encText,"<br>",$string;

?>