<分区>
所以今天我做了一些我有时会做的事情,只是为了好玩而编写程序,我决定制作我自己的加密方法。我认为这是一个基本的流密码。问题是我对密码学几乎一无所知,所以我不知道它有多安全。
这是方法(用PHP实现)
public function encrypt($data)
{
$keylen = sizeof($this->key);
$i=0;
$current = 0; //Current offset for the cipher
$ascii = utf8_decode($data);
$output = "";
for ($i=0;$i<strlen($ascii);$i++)
{
//Moves the cipher offset based on the key and the value of what is being
//encrypted
$current += ord($ascii[$i]) + $this->key[$i % $keylen];
$current = $current % 256;
$output .= chr($this->cipher[$current]);
//Moves the cipher offset to the value of the subsequent cipher key
$current = $this->cipher[($current+1)%256];
}
return $output;
}
解释
$this->cipher
一个由 0-255 之间的所有整数值组成的预洗牌数组,每个值只显示一次。 (实际上是一对一的功能,没有任何一种模式)
$this->key
一个 512 字节的随 secret 钥(不像密码数组可能包含重复值)
用于解密的密码和 key 必须与用于加密的密码和 key 相同才能恢复明文。
解密方法
public function decrypt($data)
{
$keylen = sizeof($this->key);
$i=0;
$offset = 0;
$output = "";
for ($i=0;$i<strlen($data);$i++)
{
$current = $this->r_cipher[ord($data[$i])];
//Calculates the offset for the next iteration
$next = $this->cipher[($current+1)%256];
//Subtracts the calculated offset and key value
$current -= $offset + $this->key[$i % $keylen];
//Makes sure value is between 0 and 255
$current = ($current+512)%256;
$output .= chr($current);
$offset = $next;
}
return utf8_encode($output);
}
r_cipher
只是 cipher 函数的反函数
http://pastebin.com/KbvHZnD1使用的算法示例,给出示例 key 和密码以及几个例子