首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP中的Vigenere

PHP中的Vigenere
EN

Stack Overflow用户
提问于 2013-09-18 16:05:41
回答 1查看 3.4K关注 0票数 4

有人能帮我修复PHP中的Vigenere密码吗?

抱歉,代码被撕碎了,那是我已经剖析了几个小时的代码--试图修复它!

无论如何,当代码输出'Abc‘时,它会输出'Ace’。

有一些奇怪的双偏移量,我没有数学头脑去修复!感谢您的阅读。

代码来源于这里在AutoHotkey脚本-我已经尝试转录它。网络上有PHP的例子(虽然不是在Rosetta码上,奇怪的是!)但无论如何,这是修改,以接受小写以及标准大写。谢谢。

代码语言:javascript
复制
  $key = "AAA";
  $keyLength = 3;
  $keyIndex = 0;
  $messageAsArray[0] = "A";
  $messageAsArray[1] = "b";
  $messageAsArray[2] = "c";

  foreach ($messageAsArray as $value)    //Loop through input string array
  {  
      $thisValueASCII = ord($value);
      if ($thisValueASCII >= 65 && $thisValueASCII <= 90) //if is uppercase                                  
      { 
        $thisValueASCIIOffset = 65; 
      }
      else //if is lowercase
      {
        $thisValueASCIIOffset = 97;  
      }
      $thisA = $thisValueASCII - $thisValueASCIIOffset;
      $thisB = fmod($keyIndex,$keyLength);
      $thisC = substr($key, $thisB, 1);
      $thisD = ord($thisC) - 65;
      $thisE = $thisA + $thisD;
      $thisF = fmod($thisE,26);
      $thisG = $thisF + $thisValueASCII  ;
      $thisOutput = chr($thisG); 
      $output = $output . $thisOutput  ; 
      $keyIndex++;
  }
  echo $output
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-18 16:49:43

好吧,我读了你的代码。

您正在编码,您的错误非常简单:

代码语言:javascript
复制
$thisG = $thisF + $thisValueASCII  ;

在这个步骤中,$thisF是加密的字母,其值介于0到25之间。您希望将其打印为ascii char,而不是添加偏移量,而是添加未加密的ascii值,这是没有意义的。

你应该:

代码语言:javascript
复制
$thisG = $thisF + $thisValueASCIIOffset;

一些小窍门。您不需要将文本或键作为数组,您可以像使用数组一样使用它。

您可以使用%运算符而不是fmod。使代码更容易阅读,但它只是个人偏好。

例如:

代码语言:javascript
复制
$key = "AAA";
$keyLength = strlen($key);
$keyIndex = 0;

$message = str_split("Abc");

$output = '';

foreach($message as $value) // Loop through input string array
{
    $thisValueASCII = ord($value);

    if($thisValueASCII >= 65 && $thisValueASCII <= 90) // if is uppercase
    {
        $thisValueASCIIOffset = 65;
    } else // if is lowercase
    {
        $thisValueASCIIOffset = 97;
    }

    $letter_value_corrected = $thisValueASCII - $thisValueASCIIOffset;
    $key_index_corrected = $keyIndex % $keyLength; // This is the same as fmod but I prefer this notation.

    $key_ascii_value = ord($key[$key_index_corrected]);

    if($key_ascii_value >= 65 && $key_ascii_value <= 90) // if is uppercase
    {
        $key_offset = 65;
    } else // if is lowercase
    {
        $key_offset = 97;
    }

    $final_key = $key_ascii_value - $key_offset;

    $letter_value_encrypted = ($letter_value_corrected + $final_key)%26;

    $output = $output . chr($letter_value_encrypted + $thisValueASCIIOffset);
    $keyIndex++;
}

echo $output;

祝您的实现愉快和好运!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18877121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档