JustPaste.it

// ==UserScript==
// @name         РАБОТАЕТ ECH Secret Text Decryptor
// @namespace    http://tampermonkey.net/
// @version      3.0
// @description  Расшифровка приватного текста ECH, включая короткие тексты
// @match        https://ech.bz/*
// @match        https://ech.ist/*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function () {
    'use strict';

    const MAX_VARIANTS = 20;
    const TOP_QUAD = 20;
    const BEAM_SIZE = 40;

    const B64 =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

    const B64_SET =
        new Set([...B64].map(c => c.charCodeAt(0)));

    const B64_TABLE = {};

    for (let i = 0; i < 64; i++) {
        B64_TABLE[B64.charCodeAt(i)] = i;
    }

    // "="
    B64_TABLE[61] = 0;

    const HEX =
        [...'0123456789abcdef']
            .map(c => c.charCodeAt(0));


    function b64ToBytes(str) {
        str = String(str || '')
            .trim()
            .replace(/\s+/g, '');

        while (str.length % 4 !== 0) {
            str += '=';
        }

        const raw = atob(str);
        const out = new Uint8Array(raw.length);

        for (let i = 0; i < raw.length; i++) {
            out[i] = raw.charCodeAt(i);
        }

        return out;
    }


    function utf8(bytes) {
        try {
            return new TextDecoder(
                'utf-8',
                { fatal: true }
            ).decode(bytes);
        } catch {
            return null;
        }
    }


    function decodeQuad(a, b, c, d) {
        const v0 = B64_TABLE[a] ?? 0;
        const v1 = B64_TABLE[b] ?? 0;
        const v2 = B64_TABLE[c] ?? 0;
        const v3 = B64_TABLE[d] ?? 0;

        const n =
            (v0 << 18) |
            (v1 << 12) |
            (v2 << 6) |
            v3;

        const out = [
            (n >> 16) & 255
        ];

        if (c !== 61) {
            out.push((n >> 8) & 255);
        }

        if (d !== 61) {
            out.push(n & 255);
        }

        return out;
    }


    function scoreBytes(bytes) {
        let score = 0;

        for (const b of bytes) {

            // ASCII
            if (b >= 32 && b <= 126) {
                score += 2;
                continue;
            }

            // UTF-8 начало русской буквы
            if (b === 0xD0 || b === 0xD1) {
                score += 5;
                continue;
            }

            // UTF-8 continuation
            if (b >= 0x80 && b <= 0xBF) {
                score += 4;
                continue;
            }

            // переносы
            if (b === 10 || b === 13 || b === 9) {
                score += 1;
                continue;
            }

            score -= 8;
        }

        return score;
    }


    function scoreText(text) {
        if (!text) {
            return -999999;
        }

        let score = 0;

        for (const ch of text) {
            const c = ch.charCodeAt(0);

            // Кириллица
            if (
                (c >= 0x0400 && c <= 0x04FF) ||
                (c >= 0x0500 && c <= 0x052F)
            ) {
                score += 5;
                continue;
            }

            // Латиница
            if (
                (c >= 65 && c <= 90) ||
                (c >= 97 && c <= 122)
            ) {
                score += 3;
                continue;
            }

            // цифры
            if (c >= 48 && c <= 57) {
                score += 2;
                continue;
            }

            // пробелы
            if (
                c === 32 ||
                c === 10 ||
                c === 13 ||
                c === 9
            ) {
                score += 2;
                continue;
            }

            // HTML / пунктуация
            if (
                '.,!?;:()[]{}<>/"\'-_=+*#@%&'
                    .includes(ch)
            ) {
                score += 1;
                continue;
            }

            score -= 10;
        }

        const s = text.toLowerCase();

        const words = [
            'это',
            'что',
            'как',
            'для',
            'не ',
            'на ',
            'по ',
            'из ',
            'и ',
            'но ',
            'the',
            'this',
            'that',
            'with',
            'you'
        ];

        for (const word of words) {
            if (s.includes(word)) {
                score += 8;
            }
        }

        // Нормальные русские окончания/пробелы
        score +=
            (text.match(/[аеёиоуыэюя] /gi) || []).length * 2;

        return score;
    }


    /*
     * Полная расшифровка кандидата.
     *
     * ВАЖНО:
     * Здесь только ОДИН Base64 decode.
     */

    function evalKey(data, key) {
        const encryptedB64 =
            new Uint8Array(data.length);

        for (let i = 0; i < data.length; i++) {
            encryptedB64[i] =
                data[i] ^ key[i % 32];
        }

        try {
            const b64 =
                new TextDecoder('ascii')
                    .decode(encryptedB64);

            const plain =
                utf8(
                    b64ToBytes(b64)
                );

            if (plain === null) {
                return null;
            }

            return {
                text: plain,
                score: scoreText(plain)
            };

        } catch {
            return null;
        }
    }


    /*
     * Какие hex-символы могут стоять
     * в каждой позиции 32-байтного ключа.
     */

    function getValidKeys(data) {
        const blocks = [];

        /*
         * Раньше было floor().
         *
         * Для маленького текста это давало 0.
         * Теперь последняя неполная часть тоже используется.
         */

        for (
            let i = 0;
            i < data.length;
            i += 32
        ) {
            blocks.push(
                data.subarray(
                    i,
                    Math.min(i + 32, data.length)
                )
            );
        }

        const valid =
            Array.from(
                { length: 32 },
                () => []
            );

        for (let pos = 0; pos < 32; pos++) {

            const used =
                blocks.filter(
                    b => pos < b.length
                );

            // Эта позиция коротким текстом вообще не используется.
            if (!used.length) {
                valid[pos] = [48]; // "0"
                continue;
            }

            for (const h of HEX) {

                let ok = true;

                for (const block of used) {

                    const c =
                        block[pos] ^ h;

                    if (!B64_SET.has(c)) {
                        ok = false;
                        break;
                    }
                }

                if (ok) {
                    valid[pos].push(h);
                }
            }

            if (!valid[pos].length) {
                valid[pos] = [...HEX];
            }
        }

        return {
            valid,
            blocks
        };
    }


    /*
     * Подбор вариантов для одного 4-байтного
     * участка ключа.
     */

    function getQuadCandidates(
        data,
        valid,
        blocks,
        q
    ) {
        const p0 = q * 4;
        const p1 = p0 + 1;
        const p2 = p0 + 2;
        const p3 = p0 + 3;

        if (p0 >= data.length) {
            return [{
                key: [48, 48, 48, 48],
                score: 0
            }];
        }

        const a0 = valid[p0] || [48];
        const a1 =
            p1 < data.length
                ? valid[p1]
                : [48];

        const a2 =
            p2 < data.length
                ? valid[p2]
                : [48];

        const a3 =
            p3 < data.length
                ? valid[p3]
                : [48];

        const result = [];


        for (const k0 of a0) {
            for (const k1 of a1) {
                for (const k2 of a2) {
                    for (const k3 of a3) {

                        let score = 0;

                        /*
                         * Эта четверка ключа повторяется
                         * каждые 32 байта.
                         */

                        for (let blockIndex = 0;
                             blockIndex < blocks.length;
                             blockIndex++) {

                            const block =
                                blocks[blockIndex];

                            const base =
                                blockIndex * 32 + p0;

                            if (base >= data.length) {
                                continue;
                            }

                            const c0 =
                                block[p0] ^ k0;

                            const c1 =
                                p1 < block.length
                                    ? block[p1] ^ k1
                                    : 61;

                            const c2 =
                                p2 < block.length
                                    ? block[p2] ^ k2
                                    : 61;

                            const c3 =
                                p3 < block.length
                                    ? block[p3] ^ k3
                                    : 61;

                            if (
                                !B64_SET.has(c0) ||
                                !B64_SET.has(c1) ||
                                !B64_SET.has(c2) ||
                                !B64_SET.has(c3)
                            ) {
                                score -= 1000;
                                continue;
                            }

                            score +=
                                scoreBytes(
                                    decodeQuad(
                                        c0,
                                        c1,
                                        c2,
                                        c3
                                    )
                                );
                        }

                        result.push({
                            key: [
                                k0,
                                k1,
                                k2,
                                k3
                            ],
                            score
                        });
                    }
                }
            }
        }

        result.sort(
            (a, b) =>
                b.score - a.score
        );

        return result.slice(
            0,
            TOP_QUAD
        );
    }


    /*
     * Основной взлом.
     *
     * Возвращает сразу несколько кандидатов.
     */

    function crack(encB64) {
        let raw;

        try {
            raw =
                b64ToBytes(encB64);
        } catch {
            return [];
        }

        if (raw.length <= 32) {
            return [];
        }

        const data =
            raw.subarray(32);

        const {
            valid,
            blocks
        } =
            getValidKeys(data);


        /*
         * Для каждого из 8 четырехбайтных
         * участков 32-байтного ключа.
         */

        const quadOptions = [];

        for (let q = 0; q < 8; q++) {

            quadOptions.push(
                getQuadCandidates(
                    data,
                    valid,
                    blocks,
                    q
                )
            );
        }


        /*
         * Beam search.
         *
         * Не перебираем все комбинации целиком.
         */

        let beam = [{
            key: new Uint8Array(32),
            localScore: 0
        }];


        for (let q = 0; q < 8; q++) {

            const expanded = [];

            for (const state of beam) {

                for (
                    const option of quadOptions[q]
                ) {

                    const key =
                        new Uint8Array(
                            state.key
                        );

                    const p =
                        q * 4;

                    for (let j = 0; j < 4; j++) {
                        key[p + j] =
                            option.key[j];
                    }

                    expanded.push({
                        key,
                        localScore:
                            state.localScore +
                            option.score
                    });
                }
            }


            expanded.sort(
                (a, b) =>
                    b.localScore -
                    a.localScore
            );

            beam =
                expanded.slice(
                    0,
                    BEAM_SIZE
                );
        }


        /*
         * Проверяем кандидатов уже
         * настоящей полной дешифровкой.
         */

        const candidates = [];
        const seen = new Set();

        for (const state of beam) {

            const r =
                evalKey(
                    data,
                    state.key
                );

            if (!r || !r.text) {
                continue;
            }

            const id =
                r.text;

            if (seen.has(id)) {
                continue;
            }

            seen.add(id);

            let keyString = '';

            for (let i = 0; i < 32; i++) {
                keyString +=
                    String.fromCharCode(
                        state.key[i]
                    );
            }

            candidates.push({
                text: r.text,
                score: r.score,
                key: keyString
            });
        }


        /*
         * Дополнительные варианты.
         *
         * Перебираем изменение каждого отдельного
         * символа ключа относительно лучшего.
         */

        if (beam.length) {

            const base =
                beam[0].key;

            for (let pos = 0; pos < 32; pos++) {

                for (
                    const h of valid[pos]
                ) {

                    if (h === base[pos]) {
                        continue;
                    }

                    const key =
                        new Uint8Array(base);

                    key[pos] = h;

                    const r =
                        evalKey(
                            data,
                            key
                        );

                    if (!r || !r.text) {
                        continue;
                    }

                    if (seen.has(r.text)) {
                        continue;
                    }

                    seen.add(r.text);

                    let keyString = '';

                    for (let i = 0; i < 32; i++) {
                        keyString +=
                            String.fromCharCode(
                                key[i]
                            );
                    }

                    candidates.push({
                        text: r.text,
                        score: r.score,
                        key: keyString
                    });
                }
            }
        }


        candidates.sort(
            (a, b) =>
                b.score -
                a.score
        );


        return candidates.slice(
            0,
            MAX_VARIANTS
        );
    }


    function decryptElement(el) {

        const encrypted =
            el.getAttribute(
                'data-encrypted'
            );

        if (!encrypted) {
            return;
        }

        const candidates =
            crack(encrypted);

        if (!candidates.length) {
            return;
        }

        render(
            el,
            candidates
        );
    }


    function render(
        el,
        candidates
    ) {
        let index = 0;

        el.innerHTML = '';

        el.style.background =
            'rgba(0,230,118,.12)';

        el.style.borderBottom =
            '2px solid #00e676';

        el.style.padding =
            '3px 5px';

        el.style.display =
            'inline-block';


        const text =
            document.createElement('span');

        text.textContent =
            candidates[0].text;

        el.appendChild(text);


        if (candidates.length > 1) {

            const button =
                document.createElement('button');

            button.textContent =
                'СЛАВА УКРАЇНІ';

            button.type =
                'button';

            button.style.marginLeft =
                '8px';

            button.style.cursor =
                'pointer';

            button.style.fontSize =
                '12px';


            const counter =
                document.createElement('span');

            counter.style.marginLeft =
                '5px';

            counter.style.fontSize =
                '10px';

            counter.style.opacity =
                '0.6';

            counter.textContent =
                `1/${candidates.length}`;


            el.appendChild(
                button
            );

            el.appendChild(
                counter
            );


            button.addEventListener(
                'click',
                function (e) {

                    e.preventDefault();
                    e.stopPropagation();

                    index++;

                    if (
                        index >=
                        candidates.length
                    ) {
                        index = 0;
                    }

                    text.textContent =
                        candidates[index].text;

                    counter.textContent =
                        `${index + 1}/${candidates.length}`;
                }
            );
        }
    }


    /*
     * Обработка страницы.
     */

    function process() {

        const elements =
            document.querySelectorAll(
                'span.secret-text[data-encrypted]'
            );

        for (const el of elements) {

            if (
                el.dataset
                    .echDecryptDone === '1'
            ) {
                continue;
            }

            el.dataset
                .echDecryptDone = '1';

            try {
                decryptElement(el);
            } catch (e) {
                console.error(
                    '[ECH Decryptor]',
                    e
                );

                el.dataset
                    .echDecryptDone = '0';
            }
        }
    }


    /*
     * Сначала текущие элементы.
     */

    process();


    /*
     * Новые посты / автообновление.
     *
     * Запускаем не мгновенно, чтобы не тормозить
     * загрузку страницы.
     */

    const observer =
        new MutationObserver(
            () => {
                setTimeout(
                    process,
                    50
                );
            }
        );

    observer.observe(
        document.documentElement,
        {
            childList: true,
            subtree: true
        }
    );

})();

 

 

00d040ad3a9f64aadd3f86d40ec2db2a.png