/*
 * StringEncryption.java
 * ===========================================================================
 * WHAT THIS IS
 *   A complete, working string-encryption implementation with its decryption
 *   routine — the developer's side of chapter 40 section 3.2, in all three
 *   variants, so you can build a target and then defeat it.
 *
 *     Variant A  XOR with a fixed key            (section 3.2 variant A)
 *     Variant B  AES with the key in the same DEX (variant B)
 *     Variant C  per-class decryptor with a position-dependent key (variant C)
 *
 *   Generate the ciphertext tables with gen-string-table.py in this directory.
 *
 * WHY IT MATTERS
 *   String encryption is the highest-value protection a developer can apply to
 *   Android bytecode, and the reason is the survivors table: after identifier
 *   renaming, strings are the only readable semantics left in the program.
 *   Removing them is the difference between an analyst grepping for
 *   "/v2/transfer" and an analyst having to instrument a running process.
 *
 *   It is also the protection with the cleanest universal counter, and holding
 *   both of those facts at once is the point of this file. You cannot properly
 *   assess a control you have never implemented, and you cannot properly
 *   advise a developer if you have only ever attacked it.
 *
 *   Build this, then run
 *   ../scripts/frida-string-decryptor.js against it. Watch every variant fall
 *   to the same script, unchanged, in the same amount of time. That experience
 *   is what makes the advice at the bottom of this file credible.
 *
 * HOW TO RUN
 *   # host — 1. generate the tables
 *   python3 gen-string-table.py --variant xor --key 0x5A --out XorTable.java \
 *       --strings strings.txt
 *
 *   # 2. drop the generated class into your app, replace the constants with
 *   #    calls, build, install
 *
 *   # 3. defeat it
 *   frida -U -f com.obflab.demo -l ../scripts/frida-string-decryptor.js --pause
 *
 * REQUIREMENTS
 *   Android API 21+. Variant B needs javax.crypto, which is always present.
 *
 * AUTHORISED TESTING ONLY — teaching material for chapter 40.
 * ===========================================================================
 */

package com.obflab.demo.crypto;

import android.util.Base64;

import java.nio.charset.StandardCharsets;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public final class StringEncryption {

    // =======================================================================
    // VARIANT A — XOR with a fixed key
    //
    // The simplest and by far the most common in home-grown and low-tier
    // commercial obfuscators.
    //
    // HOW IT APPEARS TO AN ANALYST
    //   In jadx: a byte[][] literal and a small static method containing a
    //   tight loop with a `^` operator, returning String.
    //
    //   In Smali, unmistakable:
    //       aget-byte v3, p0, v2
    //       xor-int/lit8 v3, v3, 0x5A      <-- the giveaway
    //       int-to-char v3, v3
    //       aput-char v3, v1, v2
    //
    //   `xor-int/lit8` inside a loop, in a method whose return type is
    //   Ljava/lang/String;, has essentially no false-positive rate. Ordinary
    //   application code does not XOR a byte array element by element and
    //   build a String from the result.
    //
    // HOW IT IS DEFEATED
    //   Statically in twenty minutes (read the loop, port it to Python,
    //   extract the arrays), or dynamically in one command. The static route
    //   is viable HERE and stops being viable at variant C, which is why the
    //   dynamic route is the one to learn.
    // =======================================================================

    public static final class XorStrings {

        private static final byte KEY = 0x5A;

        /*
         * Generated by gen-string-table.py. In a real build these arrays are
         * emitted by a bytecode transform, not written by hand.
         *
         * Index map (kept here for the lab; a real build would not ship it):
         *   0  "https://api.obflab.example.com/v2"
         *   1  "/auth/login"
         *   2  "/payments/transfer"
         *   3  "sk_live_EXAMPLE_NOT_A_REAL_KEY_ch40"
         *   4  "AES/CBC/PKCS5Padding"
         *   5  "SHA-256"
         */
        private static final byte[][] DATA = {
            // { 0x32, 0x2e, 0x2e, 0x29, 0x2c, ... },
            // ...generated...
        };

        public static String get(int index) {
            byte[] e = DATA[index];
            char[] out = new char[e.length];
            for (int i = 0; i < e.length; i++) {
                out[i] = (char) (e[i] ^ KEY);
            }
            return new String(out);
        }

        private XorStrings() { }
    }

    // =======================================================================
    // VARIANT B — AES with the key in the same DEX
    //
    // More sophisticated-looking, exactly as weak.
    //
    // THE POINT, STATED PRECISELY
    //   The threat model of string encryption is "an attacker holds the app".
    //   If the attacker holds the app, they hold the key, because the key must
    //   be in the app for the app to work.
    //
    //   AES buys you exactly one thing over XOR: an analyst cannot recover the
    //   strings with a twenty-line Python script that guesses a single byte.
    //   They recover them by RUNNING THE DECRYPTOR, which costs the same
    //   effort regardless of cipher.
    //
    //   This is categorically different from a real key-management failure.
    //   There is no key management here; there is a constant in a file. See
    //   ../../34-Cryptography/README.md.
    //
    // HOW IT APPEARS TO AN ANALYST
    //   `Cipher.getInstance` in a String-returning helper, plus byte[]
    //   literals of exactly 16 and 16 bytes (key and IV). The 16/16 pairing is
    //   itself a recognisable shape.
    // =======================================================================

    public static final class AesStrings {

        // 16 bytes. Generated at build time, shipped in the DEX, and therefore
        // public. Naming it KEY at least makes the situation honest.
        private static final byte[] KEY = {
            (byte) 0x8F, (byte) 0x2A, (byte) 0x14, (byte) 0xC3,
            (byte) 0x71, (byte) 0x0D, (byte) 0xB6, (byte) 0x59,
            (byte) 0xE2, (byte) 0x3C, (byte) 0x47, (byte) 0x90,
            (byte) 0xA5, (byte) 0x68, (byte) 0xFD, (byte) 0x1B
        };

        private static final byte[] IV = {
            (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33,
            (byte) 0x44, (byte) 0x55, (byte) 0x66, (byte) 0x77,
            (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB,
            (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF
        };

        /** Ciphertexts, base64, generated by gen-string-table.py. */
        private static final String[] DATA = {
            // "q1s0Xz...==",
            // ...generated...
        };

        public static String get(int index) {
            try {
                Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
                c.init(Cipher.DECRYPT_MODE,
                       new SecretKeySpec(KEY, "AES"),
                       new IvParameterSpec(IV));
                byte[] pt = c.doFinal(Base64.decode(DATA[index], Base64.NO_WRAP));
                return new String(pt, StandardCharsets.UTF_8);
            } catch (Exception e) {
                // A real obfuscator returns null and lets the caller NPE, which
                // is unhelpful for everyone including the developer.
                return null;
            }
        }

        private AesStrings() { }
    }

    // =======================================================================
    // VARIANT C — per-class decryptor with a position-dependent key
    //
    // The strongest common variant. Instead of one global decryptor, the
    // transform emits a DIFFERENT decryption method inside EVERY class, each
    // with a different key and often a slightly different algorithm.
    //
    // WHAT IT DEFEATS
    //   The static approach, completely. Reading one algorithm and porting it
    //   to Python is a twenty-minute job; doing it four hundred times, each
    //   with a different key and a different mixing step, is not a job anyone
    //   finishes.
    //
    //   Note the `- (i & 7)` term below. It is a position-dependent
    //   adjustment, so an analyst who guesses "single-byte XOR" from the Smali
    //   and tries it offline gets plausible-looking garbage rather than a
    //   clean failure — which costs more time than an obvious failure would.
    //
    // WHAT IT DOES NOT DEFEAT
    //   Anything dynamic, at all. Every one of the four hundred decryptors
    //   ends by constructing a java.lang.String, and that is a single choke
    //   point. Multiplying the number of decryptors multiplies the developer's
    //   build complexity and multiplies the attacker's cost by zero.
    //
    //   That asymmetry is the general shape of a good counter-technique: find
    //   the place the design MUST converge, and stand there.
    // =======================================================================

    /** The decryptor that would be emitted into class `PaymentService`. */
    public static final class S_PaymentService {

        private static final int K = 0x4B;          // different in every class

        private static final byte[][] DATA = {
            // ...generated with --variant perclass --key 0x4B...
        };

        static String a(int index) {
            byte[] e = DATA[index];
            char[] out = new char[e.length];
            for (int i = 0; i < e.length; i++) {
                // & 0xFF matters: a Java byte is signed, and the position term
                // pushes some encoded bytes above 0x7F. Without the mask, sign
                // extension corrupts exactly those characters — a bug that is
                // easy to write and slow to find, because most of the string
                // still decodes correctly.
                out[i] = (char)(((((e[i] & 0xFF) ^ K) - (i & 7)) & 0xFF));
            }
            return new String(out);
        }

        private S_PaymentService() { }
    }

    /** The decryptor that would be emitted into class `SessionManager`. */
    public static final class S_SessionManager {

        private static final int K = 0x9E;          // a DIFFERENT key

        private static final byte[][] DATA = {
            // ...generated with --variant perclass --key 0x9E...
        };

        static String a(int index) {
            byte[] e = DATA[index];
            char[] out = new char[e.length];
            for (int i = 0; i < e.length; i++) {
                // ...and a slightly different mixing step.
                out[i] = (char) (((((e[i] & 0xFF) - (i & 3)) & 0xFF) ^ K) & 0xFF);
            }
            return new String(out);
        }

        private S_SessionManager() { }
    }

    // =======================================================================
    // USING IT — the shape a transform produces
    // =======================================================================

    /*
     * BEFORE the transform:
     *
     *     private static final String BASE_URL =
     *             "https://api.obflab.example.com/v2";
     *
     *     public String login(String u, String p) {
     *         return post(BASE_URL + "/auth/login", body(u, p));
     *     }
     *
     * AFTER:
     *
     *     public String login(String u, String p) {
     *         return post(S_PaymentService.a(0) + S_PaymentService.a(1),
     *                     body(u, p));
     *     }
     *
     * NOTE what changed structurally, because it matters for the lab:
     *
     *   The constant became a METHOD CALL AT THE POINT OF USE, not a `static
     *   final String` initialised once. That is deliberate and it is what real
     *   transforms do. A `static final String X = decrypt(0);` would decrypt
     *   exactly once at class-initialisation time, giving an analyst a single
     *   call site and a single moment to hook — much easier than the real
     *   thing, where the decryptor is called from hundreds of places and the
     *   plaintext never sits in a field.
     *
     *   It also means the plaintext exists in memory for microseconds rather
     *   than for the process's lifetime, which defeats a naive memory search
     *   for the string. It does not defeat a hook, because a hook is present
     *   at exactly the microsecond that matters.
     */

    private StringEncryption() { }

    // =======================================================================
    // DEVELOPER'S BEST HARDENING, AND WHAT IT IS WORTH
    //
    // BEST AVAILABLE HARDENING
    //   - Per-class decryptors with per-class keys and per-class mixing steps
    //     (variant C). Defeats static reimplementation, which is a real
    //     population of low-effort attackers.
    //   - Position-dependent keys, so a wrong guess produces garbage rather
    //     than a clean failure.
    //   - Decrypt at the point of use, never into a field.
    //   - Never leave an index-to-plaintext map in the shipped build, and
    //     never ship the mapping file.
    //   - Move the decryptor into native code if you are willing to pay for
    //     it. It raises the floor; it does not change the ending, because
    //     NewStringUTF is as hookable as String.<init>.
    //
    // WHAT IT IS WORTH — the honest assessment
    //   HIGH against automated bulk analysis and casual attackers. Zero URLs
    //   in a string pool genuinely breaks the grep-based triage that most
    //   opportunistic analysis consists of, and that population is large.
    //
    //   LOW against anyone who runs one script. Every variant above falls to
    //   the same twenty-line hook, in the same few minutes, because the
    //   decrypted string MUST exist in memory for the program to use it. There
    //   is always a moment and always a function at which plaintext exists;
    //   the analyst does not break the cipher, they stand at the exit.
    //
    //   Measured in the labs for this chapter: variant A about twenty minutes
    //   end to end, variant C about twenty-five, and most of the extra five is
    //   waiting for a loop to finish rather than thinking.
    //
    //   THEREFORE: encrypt strings if you want to slow bulk analysis, and know
    //   that it buys half a day at most. If the concern is a specific value —
    //   an API credential, a signing key — the effective control is not to
    //   ship it. No amount of string encryption fixes a client-side secret,
    //   because the client must be able to use it, which means the attacker
    //   can too.
    // =======================================================================
}
