这个加密解密是如何工作的呢?

发布于 2024-11-09 04:25:15 字数 657 浏览 0 评论 0原文

在调试为什么它不工作后,我在 CakePHP 的核心类中发现了这个加密解密代码在我的服务器上。

我只是想知道其背后的逻辑。它究竟是如何加密和解密的?为什么 for..loop 与 $j 一起使用,异或运算符 ^ 对此有何帮助?

function cipher($text, $key) {
    if (!defined('CIPHER_SEED')) {
        //This is temporary will change later
        define('CIPHER_SEED', '76859309657453542496749683645');
    }
    srand(CIPHER_SEED);
    $out = '';

    for ($i = 0; $i < strlen($text); $i++) {
        for ($j = 0; $j < ord(substr($key, $i % strlen($key), 1)); $j++) {
            $toss = rand(0, 255);
        }
        $mask = rand(0, 255);
        $out .= chr(ord(substr($text, $i, 1)) ^ $mask);
    }
    return $out;
}

I found this encryption decryption code in CakePHP's core classes after debugging why it's not working on my server.

I'm just wondering the logic behind it. How exactly it manages to encrypt and decrypt? Why the for..loop with $j, and how XOR operator ^ help in this?

function cipher($text, $key) {
    if (!defined('CIPHER_SEED')) {
        //This is temporary will change later
        define('CIPHER_SEED', '76859309657453542496749683645');
    }
    srand(CIPHER_SEED);
    $out = '';

    for ($i = 0; $i < strlen($text); $i++) {
        for ($j = 0; $j < ord(substr($key, $i % strlen($key), 1)); $j++) {
            $toss = rand(0, 255);
        }
        $mask = rand(0, 255);
        $out .= chr(ord(substr($text, $i, 1)) ^ $mask);
    }
    return $out;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眉目亦如画i 2024-11-16 04:25:15

^ 是按位异或运算符。因此,它通过与“随机”字符按位异或来依次对每个字符进行加密。这个操作是它自己的逆操作,即(a ^ b) ^ b == a。因此,只要您在解密过程中生成与加密过程中相同的“随机”掩码字符序列,您就总能得到开始时的结果。

$j 循环看起来像是使用 $key 丢弃 rand() 生成的一定比例的值流。这看起来是一种从同一个 RNG 中获取许多不同随机流的廉价方法。不过,我不确定这是否是一种非常安全的方法。与 AES 等现有方法相比,自制的加密尝试通常存在极其严重的缺陷。

^ is the bitwise XOR operator. So it's ciphering each character in turn by bitwise XORing it with a "random" character. This operation is its own inverse, i.e. (a ^ b) ^ b == a. So as long as you generate the same sequence of "random" mask characters during decryption as you do during encryption, you'll always get back what you started with.

The $j loop looks like it's using the $key to discard a certain proportion of the stream of values that rand() generates. This looks like a cheap way of getting many different random streams out of the same RNG. I'm not sure whether this is a very secure method, though. Home-brewed attempts at encryption usually have extremely serious flaws, compared to established methods such as AES.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文