ENCRYPTED UPDATES - HOW IT ALL WORKS
====================================
Files in this folder
  pc_tool/pico_encrypt.js      PC tool (Node.js): makes keys, encrypts a .bas into a .enc, decrypts one again for checking.
  samples/aeskey.txt           A SAMPLE key (test only - never ship it). Put it on a Pico as aeskey.txt.
  samples/update_pico_Ver4.enc The 100 KB test program (1_Working_Example/test_program/update_pico_Ver4.bas) encrypted with that key.
  samples/Ver4_otherkey.enc    The same program encrypted with a DIFFERENT key: INSTALL must refuse it ("wrong key").
  samples/Ver4_damaged.enc     update_pico_Ver4.enc with one byte changed: INSTALL must stop it after decrypting (checksum wrong).
  This file.

1. WHAT PROBLEM IT SOLVES
  You hand out program updates as files. A plain .bas can be opened in any text editor and copied. An .enc file is AES-128 ciphertext:
  opened in an editor it is random-looking bytes (the only plain part is the 16-byte random IV, which is itself random). Each Pico has
  its OWN key, so a file made for one Pico is useless on another and useless to anyone who finds it. The update still goes in through
  the same web page, with the same upload, checksum, backup and rollback.

  What it does NOT do: protect a program that is installed on a Pico from the person who owns that Pico. MMBasic runs readable
  source from flash (LIST, SAVE show it) and the key is a file on the Pico. Encryption protects distribution, not the device.

2. THE PIECES
  PC side   pico_encrypt.js           holds the key list (you keep it), encrypts, can decrypt to check.
  Pico side aeskey.txt                the Pico's key: 32 hex characters on the first line of a text file. Put it on the Pico FROM THE PC.
                                       The page cannot upload this file and /get will never send it (it is also hidden from the file list).
            the page (upload.html)    uploads the .enc exactly like a .bas (same checksum, same pieces). It does not decrypt anything.
            update_pico_Ver3.bas      stores the upload as new.enc; on INSTALL decrypts it into new.bas, checks it, installs it.

3. THE KEY
  16 random bytes = 32 hex characters, e.g. C66F609ACEEFDEE93C86C43E5C47974A.
  Make one:         node pico_encrypt.js newkey
  Put it on a Pico: a text file named aeskey.txt whose first line is the 32 hex characters (a trailing line break is fine).
                    Copy it onto the Pico's flash from the PC, the same way upload.html is copied. It survives program updates (it is just a file).
  Keep a record of which key belongs to which customer/Pico. Without the key you cannot make files for that Pico, and nobody else can.
  One key per Pico (or per customer) is the point: a leaked key then exposes only that customer's updates.
  The 128-bit key cannot realistically be guessed. The risk is the key being leaked or sent in the same message as the .enc files.

4. THE FILE FORMAT (.enc)
  Bytes 1-16   IV: 16 random bytes, new for every file (so the same program encrypts differently each time).
  Bytes 17-end AES-128-CBC ciphertext (no cipher padding; the length is always a multiple of 16) of this plain data:
      8 bytes   "PICOENC1"            magic. If it does not come out when decrypted, the key is wrong (or it is not an .enc file).
      8 bytes   program length         as 8 decimal digits, e.g. 00026222
      8 bytes   Adler-32 of the program  as 8 uppercase hex digits, e.g. CD527E9E
      8 bytes   "00000000"             spare
      n bytes   the program (the .bas file exactly as it is)
      0-15 bytes of zero               padding up to a multiple of 16
  The file is 48-63 bytes bigger than the program. It is exactly the layout the Pico's LONGSTRING AES128 command reads and writes:
  "the output starts with the 16-byte IV" (confirmed on the board, and a standard PC AES-128-CBC gives identical bytes).
  Adler-32: s1 = 1 + sum of the bytes, s2 = sum of the s1 values, both mod 65521; value = s2 * 65536 + s1.

5. ON THE PC: MAKING A FILE
  Needs Node.js (free, nodejs.org). Nothing else to install. In a command prompt in pc_tool:
      node pico_encrypt.js newkey                                  prints a new key
      node pico_encrypt.js encrypt prog.bas prog.enc aeskey.txt    the last argument is the key file, or the 32 hex characters
      node pico_encrypt.js decrypt prog.enc check.bas aeskey.txt   to check a file / recover a program
  "encrypt" writes the file and immediately decrypts it again to prove it matches. The program must be 1-150000 bytes and should end
  with the CodeChk sub (Print "Code Good") - INSTALL checks for that text.
  File name rule for the page: 3-24 characters, letters digits - _ and one dot (prog.enc, MyApp_Ver5.enc ...).

6. ON THE PICO: WHAT HAPPENS, STEP BY STEP
  a) Upload. The page sends prog.enc in pieces as for any program. The Pico appends them to the file new.enc and keeps an Adler-32
     of the bytes received. When all arrive it compares the checksum the page sent. Only then is new.ok written. (This checks the
     TRANSFER of the ciphertext, not the program.)
  b) INSTALL pressed. DoInstall -> CheckEncHeader (quick, a few ms):
       - aeskey.txt missing or not 32 hex characters -> refused: "no usable key on this Pico (aeskey.txt must be put on it from the PC)"
       - the first cipher block decrypts to something other than "PICOENC1" -> refused: "this encrypted program was not made for this
         Pico (wrong key)". Nothing is changed; the running program keeps running.
     If it passes, the Pico replies "ok, switching" and the page goes quiet.
  c) After the reply (1.5 s later, in the main loop) DoSwitch -> StageToBas decrypts new.enc into new.bas:
       - the file is read in CHUNKS of 8000 bytes of cipher, because a 100 KB program does not fit in memory twice.
       - CBC chaining across chunks: each chunk is decrypted as IV + cipher, where the IV is the 16 cipher bytes that came just before
         it (the file's IV for the first chunk, the last cipher block of the previous chunk after that). This gives exactly the same
         result as decrypting the whole file at once (checked on the board with a test vector).
       - The first 32 plain bytes are the inner header: magic, length, Adler-32. The program bytes that follow are written to new.bas
         (stopping at the stated length, so the zero padding is dropped) and fed into an Adler-32 as they are written.
       - At the end: bytes written must equal the stated length, the Adler-32 must equal the stated one, and new.bas must have that
         size. Any mismatch deletes new.bas and gives "Install stopped: ..." with the reason.
       - Speed: AES itself is fast (12 KB encrypted in 22 ms, decrypted in 39 ms); the BASIC loop that writes the bytes and the
         checksum is the slower part (its time for 100 KB has not been measured; the page allows 30 s before it starts asking again).
  d) PrepInstall: new.bas must end with "Code Good" (last 250 bytes), then the running program is saved as prev.bas with SAVE.
     If either fails the install stops with a reason and the running program is untouched.
  e) RUN new.bas. The new program starts and autoruns from then on. The page waits 30 s, asks /ver until the Pico answers, shows the
     version, and (if the version changed) asks /cleanup so the Pico deletes new.enc, new.bas and new.ok. prev.bas stays for ROLLBACK.
  If anything in steps b-d fails, the page shows the reason in red (the Pico reports it through /ver) and the old program is still running.

7. MESSAGES AND WHAT THEY MEAN
  "no usable key on this Pico ..."            aeskey.txt is missing, or its first line is not 32 hex characters.
  "... not made for this Pico (wrong key)"    the file was encrypted with a different key than this Pico holds.
  "the encrypted file is too small"           new.enc is under 64 bytes: not a real .enc.
  "Install stopped: wrong key"                (rare) the key passed the header check but the data does not decrypt: damaged file.
  "Install stopped: checksum of the decrypted program is wrong"   the file was altered or damaged after it was made (even one byte).
  "Install stopped: the program is shorter than it says"          the file is cut short.
  "Install stopped: new.bas does not end with the Code Good check ..."   the program lacks the CodeChk sub at its end.
  "Install stopped: backup failed ..."         SAVE of the running program failed; nothing was installed.
  "the key file can only be put on the Pico from the PC"          you tried to upload aeskey.txt through the page: refused by design.
  "checksum mismatch, start again"            (during UPLOAD) the bytes that arrived differ from the file: a transfer problem, retry.
  "name not allowed ..."                      the file name is longer than 24 characters, or has an unsupported extension.

8. SECURITY NOTES (honest version)
  - Confidentiality: strong. AES-128 with a random IV; the file reveals nothing but its approximate size.
  - Per-device: a file only installs where the key matches (the magic text is checked first).
  - Integrity: the length and Adler-32 inside the cipher detect corruption and clumsy tampering (changing ciphertext garbles the plain
    text, which then fails the magic/length/checksum). Adler-32 is NOT a cryptographic signature. Whoever holds the key can make a valid
    file, so the key IS the authority: guard it like a password.
  - No version ordering: an older valid .enc can be installed over a newer program. If that matters, add a minimum-version check in
    your own code (compare the version inside the new program to PROG_VER$ before RUN).
  - The key file is plain text on the Pico. Anyone with physical or console access to the Pico can read it, and LIST the running
    program. Encryption does not stop that.
  - This standalone version has no login; whoever can reach the page can upload and install. Add your login in front of every
    route before real use (see ../2_Minimum_Starting_Base/README.txt).
  - Do not ship samples/aeskey.txt. It exists only so the sample files can be tried.

9. MMBASIC FACTS THIS RELIES ON (tested on RP2350A WebMite, MMBasic 7.00.00RC7)
  LONGSTRING AES128 ENCRYPT CBC key$, in%(), out%() [,iv$]   output = 16-byte IV + cipher (an IV is made up if you omit it)
  LONGSTRING AES128 DECRYPT CBC key$, in%(), out%()          input = IV + cipher, output = plain text only
  Data lengths must be multiples of 16. The key is 16 bytes (a string of 16 characters). A standard PC AES-128-CBC produces the
  same bytes (verified with a test vector). Strings and program lines are limited to 255 characters; Input$ returns at most 255 bytes.
  MM.INFO(ID) (the chip ID) gave "Expected a number" on this firmware, so the key is a file rather than derived from the chip ID.
  Names must not START with an MMBasic word (LoadKey clashes with LOAD, KEY_FILE$ with KEY, PIECE with PI): the code uses
  AESKEY_FILE$, FetchKey, StageToBas.

10. FIRST TRIAL ON A BOARD (what was done and what to expect)
  1. Run update_pico_Ver3.bas, put upload.html on the Pico, put samples/aeskey.txt on it as aeskey.txt (from the PC).
  2. Upload Ver4_otherkey.enc, INSTALL      -> red "not made for this Pico (wrong key)", running program unchanged.
  3. Upload Ver4_damaged.enc, INSTALL       -> after the quiet period: red "Install stopped: checksum of the decrypted program is wrong",
                                               running program unchanged, new.bas deleted.
  4. Upload update_pico_Ver4.enc, INSTALL   -> console: "Decrypting new.enc ...", "Decrypted OK, the running program is saved as prev.bas",
                                               then the Ver4 banner; the page reports Ver4 and the cleanup message. ROLLBACK returns to Ver3.
  All four behaved like this on the test board.

11. TO ADD THIS TO ANOTHER PROGRAM
  Copy, from 2_Minimum_Starting_Base/updater_only_Ver3.bas: the constants ENC_FILE$, AESKEY_FILE$, ENC_MAGIC$, ENC_CHUNK; the arrays CIn()
  and COut(); the variables UpTarget, NewKind, Job, InstMsg; and the routines FetchKey, CheckEncHeader, StageToBas, PrepInstall, with the
  ".enc" handling in DoUpload / NewReady / DoInstall / DoSwitch / DoCleanup / DoGet / DoList / GoodName / IsProgName. Easiest is to take
  the whole file and delete what you do not need. Provide aeskey.txt per Pico, and a copy of pico_encrypt.js on your PC.
