A
A
arseniylebedev2021-12-20 19:59:45
PHP
arseniylebedev, 2021-12-20 19:59:45

Why doesn't it work in PHP?

Why does this code work fine in JS

spoiler

function encrypt(text, num) {
    let encrypted_text = '';

    for (const symbol of text.toString()) {
        encrypted_text += String.fromCharCode(symbol.charCodeAt(0) + num);
    }

    return encrypted_text;
}

function decrypt(encrypted_text, num) {
    let decrypted_text = '';

    for (const symbol of encrypted_text) {
        decrypted_text += String.fromCharCode(symbol.charCodeAt(0) - num);
    }

    return decrypted_text;
}
console.log(decrypt(encrypt('Hello World!', 1000000, 1000000)));



Isn't this one in PHP?
spoiler

class Encryption
{
    const DEFAULT_NUMBER= 1000000;
    const ENCODING = 'UTF-16';

    public static function encrypt($text, $num) {
        $text = strval($text);

        $encrypted_text = '';

        foreach (str_split($text) as $symbol) {
            $encrypted_text .= mb_chr(mb_ord($symbol, self::ENCODING) + $num, self::ENCODING);
        }

        return base64_encode($encrypted_text);
    }

    public static function decrypt($encrypted_text, $num) {
        $encrypted_text = base64_decode($encrypted_text);

        $decrypted_text = '';

        foreach (str_split($encrypted_text) as $symbol) {
            $decrypted_text .= mb_chr(mb_ord($symbol, self::ENCODING) - $num, self::ENCODING);
        }

        return $decrypted_text;
    }
}

$enc = \App\Encryption\Encryption::encrypt('Hello World!', 1000000);
$dec = \App\Encryption\Encryption::decrypt($enc, 1000000);
var_dump($enc, $dec);



PHP code result:
spoiler

C:\wamp64\www\test.local\routes\web.php:49:string '25DeQNuQ3kDbkN5A25DeQNuQ3kDbkN5A25DeQNuQ3kDbkN5A25DeQNuQ3kDbkN5A' (length=64)
C:\wamp64\www\test.local\routes\web.php:49:string '' (length=0)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2021-12-20
@arseniylebedev

str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string.

There is mb_str_split

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question