gpt4 book ai didi

php - 凯撒密码未按预期运行

转载 作者:可可西里 更新时间:2023-10-31 22:53:44 24 4
gpt4 key购买 nike

我正在使用 Caesar Cipher,但它似乎不起作用。

这是我的代码:

class CaesarCipher {
const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
protected $encrypt_sequence = array();
protected $decrypt_sequence = array();

public function __construct($seed = 1) {
$total_chars = strlen(self::CHARS);
$seed = $seed % $total_chars;
for ($i = 0; $i < $total_chars; $i++) {
$src = substr(self::CHARS, $i, 1);
$dst = substr(self::CHARS, ($i + $seed) % $total_chars, 1);
$this->encrypt_sequence[$src] = $dst;
$this->decrypt_sequence[$dst] = $src;
}
$this->encrypt_sequence[' '] = ' ';
$this->decrypt_sequence[' '] = ' ';
}

public function encrypt($value) {
$value = strtoupper($value);
return str_replace($this->encrypt_sequence, $this->decrypt_sequence, $value);
}

public function decrypt($value) {
$value = strtoupper($value);
return str_replace($this->decrypt_sequence, $this->encrypt_sequence, $value);
}

public function getEncryptSequence() {
return $this->encrypt_sequence;
}

public function getDecryptSequence() {
return $this->decrypt_sequence;
}
}

运行它:

$seed = mt_rand(1, 35);
$cipher = new CaesarCipher($seed);
$source = 'THIS IS JUST A TEST WITH 123 NUMBERS';
$encrypted = $cipher->encrypt($source);
$decrypted = $cipher->decrypt($encrypted);

这是我的输出:

CAESAR CIPHER (seed=16)

Source: THIS IS JUST A TEST WITH 123 NUMBERS
Encrypted: X12W 2W 3YWX U XYWX 02X1 567 7Y6VYVW ENCRYPTED :)
Decrypted: DHIC IC JECD A DECD GIDH LMN NEMBEBC DOES NOT MATCH SOURCE :(


Encryption: A>Q B>R C>S D>T E>U F>V G>W H>X I>Y J>Z K>0 L>1 M>2 N>3 O>4 P>5 Q>6 R>7 S>8 T>9 U>A V>B W>C X>D Y>E Z>F 0>G 1>H 2>I 3>J 4>K 5>L 6>M 7>N 8>O 9>P
Decryption: Q>A R>B S>C T>D U>E V>F W>G X>H Y>I Z>J 0>K 1>L 2>M 3>N 4>O 5>P 6>Q 7>R 8>S 9>T A>U B>V C>W D>X E>Y F>Z G>0 H>1 I>2 J>3 K>4 L>5 M>6 N>7 O>8 P>9

谁能告诉我为什么它不起作用?

最佳答案

最明显的问题是 str_replace 手册中的这一部分:

Caution

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

您多次替换某些字符,这导致了您得到的结果。

这适用于加密和解密,因此您不能将 str_replace() 与数组一起使用来执行您想要执行的操作。

一个可能的解决方案是逐个字符地加密(en decrypt...)您的字符串,以便您只传递每个字符一次。

关于php - 凯撒密码未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29702076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com