2017-03-27 27 views
-1

它有比通過XOR加密數據更快的選擇嗎?PHP - 異或加密

private static function getBinary($string) 
{ 
    $output = ''; 
    for($i = 0; $i < strlen($string); $i++) 
    { 
     $value = decbin(ord($string[$i])); 
     $binary = str_pad($value, 8, '0', STR_PAD_LEFT); 
     $output .= $binary; 
    } 

    return ($output); 
} 

private static function getCrypted($key, $value) 
{ 
    $output = ''; 
    $key_index = 0; 
    $max = strlen($key); 

    for($i = 0; $i < strlen($value); $i++) 
    { 
     if($key_index >= $max){ $key_index = 0;} 
     $output .= ($key[$key_index] XOR $value[$i]) ? '1' : '0'; 
     $key_index++; 
    } 

    return ($output); 
} 

對於小文本,它相對較快,但我需要加密大文本(3MB數據)。但是對於這個文件getCrypted()函數需要10-20秒,這是不可接受的。

$bin_text = self::getBinary($text); // cca 4 sec. 
$bin_key = self::getBinary("12345"); // 0 sec. 

return self::getCrypted($bin_key, $bin_text); // 11 sec+ 

那麼,它有什麼最快的方法嗎?也許將文本轉換爲二進制文件而不使用0和1創建另一個字符串我不知道...謝謝你的回覆。

+1

'XOR'不是加密。 – axiac

+0

@axiac http://www.tech-faq.com/xor-encryption.html –

+0

任何你正在使用'^'操作符逐位完成而不是逐字節操作的原因......? – CBroe

回答

0

的解決方案是不轉讓位,但字節... @CBroe

$byte_text = unpack('C*', 'asasdkasndaksdnkas'); 
$byte_key = unpack('C*', '12345'); 

$output = ''; 
$key_index = 1; 

for($i = 1; $i < count($byte_text)+1; $i++) 
{ 
    if($key_index > count($byte_key)){ $key_index = 1;} 
    $output .= dechex(($byte_text[$i]^$byte_key[$key_index])); 
    $key_index++; 
} 

echo $output; 

這一切,謝謝。