-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkrypton.c
More file actions
2286 lines (2132 loc) · 107 KB
/
krypton.c
File metadata and controls
2286 lines (2132 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* krypton.c — Multi-method file encryption / decryption / hashing tool
* Version 4.1
*
* ─── COMPILE — LINUX ─────────────────────────────────────────────────────────
*
* 1. Install OpenSSL development headers (if not already present):
* sudo apt install libssl-dev # Debian / Ubuntu
* sudo dnf install openssl-devel # Fedora / RHEL / CentOS
* sudo pacman -S openssl # Arch Linux
*
* 2. Compile:
* gcc -Wall -Wextra -o krypton krypton.c -lssl -lcrypto
*
* Alternative — Ubuntu/Debian without libssl-dev but with Node.js present:
* gcc -Wall -Wextra -o krypton krypton.c \
* -I/usr/include/node \
* /usr/lib/x86_64-linux-gnu/libcrypto.so.3
*
* ─── COMPILE — macOS ─────────────────────────────────────────────────────────
*
* macOS ships LibreSSL (not OpenSSL) which lacks several algorithms.
* Install the real OpenSSL via Homebrew first:
*
* 1. Install Homebrew (if not already present):
* /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
*
* 2. Install OpenSSL:
* brew install openssl
*
* 3. Compile (adjust the version path if needed — check with: brew --prefix openssl):
* gcc -Wall -Wextra -o krypton krypton.c \
* -I$(brew --prefix openssl)/include \
* -L$(brew --prefix openssl)/lib \
* -lssl -lcrypto
*
* Note: if you see "library not found for -lssl", confirm OpenSSL is installed:
* brew list openssl
*
* ─── COMPILE — WINDOWS ───────────────────────────────────────────────────────
*
* Option A — MSYS2 / MinGW-w64 (recommended, closest to Linux workflow)
* -----------------------------------------------------------------------
* MSYS2 provides a full GCC toolchain and a native Windows OpenSSL build.
*
* 1. Download and install MSYS2 from https://www.msys2.org/
*
* 2. Open the "MSYS2 UCRT64" shell (Start menu → MSYS2 UCRT64), then:
* pacman -Syu # update package database
* pacman -S mingw-w64-ucrt-x86_64-gcc \
* mingw-w64-ucrt-x86_64-openssl # install GCC + OpenSSL
*
* 3. Compile inside the UCRT64 shell:
* gcc -Wall -Wextra -o krypton.exe krypton.c -lssl -lcrypto
*
* 4. Run:
* ./krypton.exe -h
*
* The resulting krypton.exe can be copied to any Windows machine that has
* the MSYS2 runtime DLLs (libssl-3-x64.dll, libcrypto-3-x64.dll,
* libgcc_s_seh-1.dll, libwinpthread-1.dll) in the same folder or on PATH.
* To find those DLLs: ldd krypton.exe | grep -v /c/Windows
*
* Option B — WSL 2 (Windows Subsystem for Linux)
* -----------------------------------------------------------------------
* WSL 2 runs a real Linux kernel inside Windows. The Linux compile
* instructions above apply without modification.
*
* 1. Install WSL 2 (PowerShell as Administrator):
* wsl --install
* (installs Ubuntu by default; restart required)
*
* 2. Open the Ubuntu shell, then follow the Linux instructions above.
*
* Option C — Visual Studio / MSVC (advanced)
* -----------------------------------------------------------------------
* MSVC does not support C99 variable-length features and strsep() is a
* POSIX extension absent from the CRT. A shim for strsep() is already
* included in this file (see the #ifdef _WIN32 block below).
*
* 1. Download and install Visual Studio 2022 (Community edition is free):
* https://visualstudio.microsoft.com/
* Select the "Desktop development with C++" workload.
*
* 2. Download a pre-built OpenSSL for Windows from one of:
* https://slproweb.com/products/Win32OpenSSL.html (Win64 OpenSSL v3.x)
* https://vcpkg.io/ (vcpkg install openssl:x64-windows)
* Install to e.g. C:\OpenSSL-Win64
*
* 3. Open a "Developer Command Prompt for VS 2022" and compile:
* cl krypton.c ^
* /I "C:\OpenSSL-Win64\include" ^
* /link "C:\OpenSSL-Win64\lib\VC\x64\MD\libssl.lib" ^
* "C:\OpenSSL-Win64\lib\VC\x64\MD\libcrypto.lib" ^
* /out:krypton.exe
*
* 4. Copy the OpenSSL runtime DLLs next to krypton.exe:
* libssl-3-x64.dll libcrypto-3-x64.dll
* (found in C:\OpenSSL-Win64\bin\)
*
* ─── LEGACY PROVIDER NOTE (all platforms) ───────────────────────────────────
*
* OpenSSL 3.x moved DES, Blowfish, CAST5, and MD4 into a separate "legacy"
* provider module. krypton loads it automatically at startup via:
* OSSL_PROVIDER_load(NULL, "legacy")
* The module file is named legacy.dll (Windows), legacy.dylib (macOS), or
* legacy.so (Linux) and is usually installed alongside OpenSSL itself.
* If the module is missing, modern ciphers still work; only the legacy ones
* (des, blowfish, cast5, md4) will report "not available in this build".
* Typical locations:
* Linux : /usr/lib/x86_64-linux-gnu/ossl-modules/legacy.so
* macOS : $(brew --prefix openssl)/lib/ossl-modules/legacy.dylib
* Windows : C:\OpenSSL-Win64\lib\ossl-modules\legacy.dll
*
* ─── MODES ───────────────────────────────────────────────────────────────────
*
* -e <method> Encrypt (requires -k, -i, -o)
* -d <method> Decrypt (requires -k, -i, -o)
* --hash <alg> Hash (requires -i; -o optional — saves hex to file)
* -h / --help Show full help and examples
*
* ─── COMMAND-LINE FLAGS ──────────────────────────────────────────────────────
*
* -e <method> Cipher method name (see full list below)
* -d <method> Same method name used for encryption
* -k <key> Key / passphrase (format varies per method, see below)
* -i <file> Input file path (any file type: binary, text, PDF, etc.)
* -o <file> Output file path
* --hash <alg> Hash algorithm name (one-way, no -k required)
*
* ─── KEY SYNTAX BY METHOD ────────────────────────────────────────────────────
*
* Most cipher methods:
* -k "any passphrase"
* OpenSSL-backed ciphers derive a proper key via PBKDF2/SHA-256
* (10 000 iterations) from this passphrase + a random 16-byte salt.
* The salt is automatically prepended to the output file and read
* back transparently on decryption.
*
* atbash, rot13:
* -k "" (no key required; self-inverse)
*
* polybe, bacon:
* -k "" (no key required; encode with -e, decode with -d)
*
* caesar:
* -k "N" where N is an integer shift 0–255 (e.g. -k "13")
*
* vigenere:
* -k "word" alphabetic characters only, a–z or A–Z (e.g. -k "lemon")
*
* playfair:
* -k "keyword" any word used to build the 5×5 Polybius key square
* (e.g. -k "monarchy"). J is treated as I.
* Input is alpha-only; X is inserted as padding per spec.
*
* railfence:
* -k "N" integer number of rails >= 2 (e.g. -k "3")
*
* adfgvx:
* -k "SUBKEY:TRANSKEY"
* SUBKEY = word used to build the 6×6 substitution grid (A–Z + 0–9)
* TRANSKEY = word used for columnar transposition
* Example: -k "DEUTSCH:ANGRIFF"
* Output characters are exclusively from the set {A, D, F, G, V, X}.
*
* enigma:
* -k "R1:R2:R3:POS:PAIRS"
* R1 R2 R3 = rotor identifiers, left to right: I II III IV V
* POS = 3-letter start positions (e.g. AAA or XKZ)
* PAIRS = plugboard (Steckerbrett) pairs, space-separated (optional)
* Examples:
* -k "I:II:III:AAA:" (no plugboard)
* -k "IV:I:V:XKZ:AB CD EF GH" (4 plugboard pairs)
* Simulation details:
* - Rotors I–V with correct Wehrmacht wirings
* - Reflector B (Umkehrwalze B)
* - Authentic double-stepping anomaly implemented
* - Only A–Z processed; all other bytes pass through unchanged
* - Self-inverse: encrypting ciphertext with the same settings
* yields the original plaintext
*
* vernam (One-Time Pad):
* -k "@/path/to/keyfile"
* The key must be a binary file at least as large as the input.
* The '@' prefix signals that the argument is a file path, not a
* passphrase. The key file is XOR-ed byte-for-byte with the input.
* Self-inverse: same key file decrypts what it encrypts.
* WARNING: each key file must NEVER be reused; reuse breaks security.
*
* xor:
* -k "passphrase" (any non-empty string; key cycles over input bytes)
* Self-inverse: same operation encrypts and decrypts.
*
* rc4:
* -k "passphrase" (any string up to 256 characters)
* Self-inverse: same key decrypts.
*
* chacha20:
* -k "passphrase" (derived to 256-bit key via PBKDF2; unauthenticated)
*
* chacha20-poly1305:
* -k "passphrase" (AEAD — authenticated; detects any tampering)
*
* 3des / camellia-128 / camellia-256 / aria-128 / aria-256 / sm4:
* -k "passphrase" (CBC mode, PKCS#7 padding, PBKDF2 key derivation)
*
* aes-128 / aes-192 / aes-256:
* -k "passphrase" (CBC mode, PKCS#7 padding, PBKDF2 key derivation)
*
* aes-128-gcm / aes-192-gcm / aes-256-gcm:
* -k "passphrase" (GCM mode — authenticated; detects any tampering)
* File format: [16-byte salt][12-byte nonce][ciphertext][16-byte tag]
*
* ─── ALL CIPHER METHODS ──────────────────────────────────────────────────────
*
* Historical — Classical Antiquity (pure C):
* scytale Scytale (~700 BC, Sparta). Columnar transposition on a staff.
* Key: integer column-width >= 2 (e.g. -k "4")
* atbash Atbash cipher (~600 BC). Reverses alphabet A<->Z. Self-inverse.
* Key: none (use -k "")
* affine Affine cipher (classical antiquity). C = (a*P + b) mod 26.
* Key: "a,b" where a is coprime to 26 (e.g. -k "7,3")
* polybe Polybius square (~200 BC). Maps letters to row/col digit pairs.
* Output is larger than input (text). -e encodes, -d decodes.
* Key: none (use -k "")
* caesar Caesar byte-shift cipher (~50 BC).
* Key: integer shift 0-255
*
* Historical — Renaissance (pure C):
* trithemius Trithemius cipher (Johannes Trithemius, 1508). Auto-key
* progressive shift using the tabula recta. Key: none.
* vigenere Vigenere polyalphabetic cipher (Giovan Battista Bellaso, 1553).
* Key: alphabetic string a-z/A-Z
* porta Porta cipher (Giovanni Battista della Porta, 1563). Reciprocal
* 13-row alphabet table. Self-inverse.
* Key: any alphabetic string (e.g. -k "secret")
* bacon Bacon's cipher (Francis Bacon, 1605). Binary steganography:
* each letter -> 5 A/B characters. -e encodes, -d decodes.
* Key: none (use -k "")
*
* Historical — 19th Century (pure C):
* playfair Playfair digraph cipher (Charles Wheatstone, 1854).
* First digraph cipher; used by British Army in WWI.
* Handles alpha text only; J treated as I; X used for padding.
* Key: any keyword
* beaufort Beaufort cipher (Admiral Sir Francis Beaufort, 1857).
* Vigenère variant: C = (K - P) mod 26. Self-inverse.
* Key: alphabetic string a-z/A-Z (e.g. -k "royalnavy")
* railfence Rail Fence transposition cipher (US Civil War era).
* Zigzag write across N rails, read row by row.
* Key: integer number of rails >= 2
*
* Historical — World War I (pure C):
* adfgvx ADFGVX cipher (German Army, March 1918).
* 6×6 Polybius substitution + columnar transposition.
* Handles A–Z and 0–9; output is {A,D,F,G,V,X} letters.
* Key: "SUBKEY:TRANSKEY"
* columnar Columnar transposition (WWI / WWII). Writes text into rows,
* reads columns in keyword-sorted order.
* Key: any alphabetic keyword (e.g. -k "ZEBRAS")
*
* Historical — World War II (pure C):
* double Double transposition (SOE / Allied WWII field cipher).
* Two rounds of columnar transposition with two keys.
* Key: "KEY1:KEY2" (e.g. -k "SECURITY:LONDON")
* enigma Full Enigma machine simulation (Germany, 1923–1945).
* Rotors I–V, Reflector B, plugboard. Self-inverse.
* Key: "R1:R2:R3:POS:PAIRS"
*
* Historical — Other 20th Century Ciphers (pure C):
* foursquare Four-Square cipher (Felix Delastelle, 1901). Four 5x5 grids.
* Key: "KEY1:KEY2" (e.g. -k "EXAMPLE:KEYWORD")
* vernam Vernam cipher / One-Time Pad (Gilbert Vernam, 1917).
* Proven information-theoretically secure (Shannon, 1949).
* Key must be a file path prefixed with '@'.
* rot13 ROT13 letter substitution (Usenet, ~1980). Self-inverse.
* Key: none (use -k "")
* rot47 ROT47 (Usenet, ~1990s). Rotates all 94 printable ASCII chars
* by 47. Self-inverse. Key: none (use -k "")
*
* Modern stream ciphers (pure C):
* xor XOR byte cipher. Self-inverse.
* rc4 RC4 stream cipher (Ron Rivest, 1987). Self-inverse.
*
* Modern stream ciphers (OpenSSL):
* chacha20 ChaCha20 (Daniel J. Bernstein, 2008). Unauthenticated.
* chacha20-poly1305 ChaCha20 + Poly1305 MAC. Authenticated (AEAD). [*]
*
* Block ciphers — CBC mode (OpenSSL, PKCS#7 padding, PBKDF2 key derivation):
* des DES-CBC. [BROKEN — 56-bit key, brute-forceable]
* blowfish Blowfish-CBC. [LEGACY — 64-bit block, SWEET32 risk]
* cast5 CAST5-CBC. [LEGACY — 64-bit block, SWEET32 risk]
* 3des Triple-DES-EDE-CBC. [LEGACY — deprecated by NIST 2023]
* camellia-128 Camellia-128-CBC. ISO/IEC 18033-3, NESSIE-approved.
* camellia-256 Camellia-256-CBC. ISO/IEC 18033-3, NESSIE-approved.
* aria-128 ARIA-128-CBC. Korean national standard KS X 1213.
* aria-256 ARIA-256-CBC. Korean national standard KS X 1213.
* sm4 SM4-CBC. Chinese national standard GB/T 32907-2016.
* aes-128 AES-128-CBC. NIST FIPS 197.
* aes-192 AES-192-CBC. NIST FIPS 197.
* aes-256 AES-256-CBC. NIST FIPS 197. Recommended general-purpose.
*
* Block ciphers — GCM mode / Authenticated Encryption (OpenSSL): [*]
* aes-128-gcm AES-128-GCM.
* aes-192-gcm AES-192-GCM.
* aes-256-gcm AES-256-GCM. Recommended — best security.
*
* [*] Authenticated modes (AEAD) provide both confidentiality AND integrity.
* Any modification to the ciphertext is detected on decryption and
* causes an explicit error ("Authentication FAILED").
*
* ─── HASH ALGORITHMS (--hash mode) ──────────────────────────────────────────
*
* All hash modes compute a digest and print it as a hex string to stdout.
* Optionally save to file with -o. No key required.
*
* Legacy (cryptographically broken — use only for compatibility):
* md4 MD4 (Ron Rivest, 1990). 128-bit / 32 hex chars.
* Predecessor of MD5; still used internally by NTLM/Windows.
* Requires OpenSSL legacy provider (loaded automatically).
* md5 MD5 (Ron Rivest, 1992). 128-bit / 32 hex chars.
* sha1 SHA-1 (NIST, 1995). 160-bit / 40 hex chars.
* Note: "sha" is accepted as an alias for sha1.
* SHA-0 (the withdrawn 1993 original) is not available in
* modern OpenSSL builds and is not supported.
*
* SHA-2 family (NIST FIPS 180-4):
* sha224 SHA-224. 224-bit / 56 hex chars.
* sha256 SHA-256. 256-bit / 64 hex chars. Recommended general use.
* sha384 SHA-384. 384-bit / 96 hex chars.
* sha512 SHA-512. 512-bit / 128 hex chars.
*
* SHA-3 family (NIST FIPS 202 — Keccak):
* sha3-256 SHA3-256. 256-bit / 64 hex chars.
* sha3-512 SHA3-512. 512-bit / 128 hex chars.
*
* BLAKE2 family:
* blake2b BLAKE2b-512. 512-bit / 128 hex chars. Fast on 64-bit systems.
* blake2s BLAKE2s-256. 256-bit / 64 hex chars. Fast on 32-bit systems.
*
* ─── SECURITY NOTES ──────────────────────────────────────────────────────────
*
* - For any new system, prefer aes-256-gcm or chacha20-poly1305.
* These are AEAD modes: they guarantee both confidentiality and integrity.
* - CBC modes (aes-128/192/256, camellia-*, aria-*, sm4, 3des) provide
* confidentiality only; a tampered ciphertext may decrypt without error.
* - Historical ciphers (atbash, caesar, vigenere, enigma, etc.) offer NO
* modern security. Use them only for educational or recreational purposes.
* - Vernam/OTP is the only cipher proven information-theoretically secure,
* but requires a truly random key as large as the message, used only once.
* - All OpenSSL-backed ciphers derive keys via PBKDF2-HMAC-SHA256 with a
* random 16-byte salt and 10 000 iterations, making brute-force harder.
* - rc4 has known statistical biases; avoid it for sensitive data.
* - 3des is deprecated by NIST (2023); included for legacy compatibility only.
*
* ─── EXAMPLES ────────────────────────────────────────────────────────────────
*
* # Best modern security (authenticated)
* ./krypton -e aes-256-gcm -k "P@ss!" -i doc.pdf -o doc.enc
* ./krypton -d aes-256-gcm -k "P@ss!" -i doc.enc -o doc.pdf
*
* # Fast modern security (authenticated)
* ./krypton -e chacha20-poly1305 -k "P@ss!" -i video.mp4 -o video.enc
* ./krypton -d chacha20-poly1305 -k "P@ss!" -i video.enc -o video.mp4
*
* # Enigma (self-inverse — same command decrypts)
* ./krypton -e enigma -k "I:II:III:AAA:AB CD" -i msg.txt -o msg.enc
* ./krypton -e enigma -k "I:II:III:AAA:AB CD" -i msg.enc -o msg.dec
*
* # Vernam / One-Time Pad
* ./krypton -e vernam -k "@/secure/pad.bin" -i msg.txt -o msg.enc
* ./krypton -d vernam -k "@/secure/pad.bin" -i msg.enc -o msg.txt
*
* # ADFGVX (WWI German cipher)
* ./krypton -e adfgvx -k "DEUTSCH:ANGRIFF" -i msg.txt -o msg.enc
* ./krypton -d adfgvx -k "DEUTSCH:ANGRIFF" -i msg.enc -o msg.txt
*
* # Playfair
* ./krypton -e playfair -k "monarchy" -i plain.txt -o cipher.txt
* ./krypton -d playfair -k "monarchy" -i cipher.txt -o plain.txt
*
* # Rail Fence (3 rails)
* ./krypton -e railfence -k "3" -i plain.txt -o cipher.txt
* ./krypton -d railfence -k "3" -i cipher.txt -o plain.txt
*
* # Polybius square encoding
* ./krypton -e polybe -k "" -i plain.txt -o encoded.txt
* ./krypton -d polybe -k "" -i encoded.txt -o plain.txt
*
* # Bacon binary steganography
* ./krypton -e bacon -k "" -i plain.txt -o bacon.txt
* ./krypton -d bacon -k "" -i bacon.txt -o plain.txt
*
* # Hash a file (SHA-256)
* ./krypton --hash sha256 -i firmware.bin
* ./krypton --hash blake2b -i archive.tar.gz -o archive.b2
*
* ─────────────────────────────────────────────────────────────────────────────
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdint.h>
#include <math.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/provider.h>
/* ═══════════════════════════════════════════════════════════════════════════
Constants
═══════════════════════════════════════════════════════════════════════════ */
#define CHUNK_SIZE 4096
#define SALT_LEN 16
#define GCM_TAG_LEN 16
#define GCM_IV_LEN 12
#define KDF_ITER 10000
#define MAX_KEY_BYTES 32
#define MAX_IV_BYTES 16
#ifdef _WIN32
/* ═══════════════════════════════════════════════════════════════════════════
Implementation of strsep for Windows (MinGW / MSVC)
Same behavior as version POSIX
═══════════════════════════════════════════════════════════════════════════ */
char *strsep(char **stringp, const char *delim) {
char *start = *stringp;
char *p;
if (start == NULL)
return NULL;
// Find the first delim
p = strpbrk(start, delim);
if (p) {
*p = '\0';
*stringp = p + 1;
} else {
*stringp = NULL;
}
return start;
}
#endif
/* ═══════════════════════════════════════════════════════════════════════════
Error helpers
═══════════════════════════════════════════════════════════════════════════ */
static void die(const char *msg)
{
fprintf(stderr, "[ERROR] %s\n", msg);
exit(EXIT_FAILURE);
}
static void openssl_die(const char *ctx)
{
fprintf(stderr, "[ERROR] %s: ", ctx);
ERR_print_errors_fp(stderr);
fprintf(stderr, "\n");
exit(EXIT_FAILURE);
}
/* ═══════════════════════════════════════════════════════════════════════════
print_help
═══════════════════════════════════════════════════════════════════════════ */
static void print_help(const char *p)
{
printf(
"+---------------------------------------------------------------------------+\n"
"| krypton -- file encryptor / decryptor / hasher v0.8 |\n"
"+---------------------------------------------------------------------------+\n\n"
"USAGE\n"
" %s -e <method> -k <key> -i <input> -o <output> # encrypt\n"
" %s -d <method> -k <key> -i <input> -o <output> # decrypt\n"
" %s --hash <algorithm> -i <input> [-o <output>] # hash\n"
" %s -h # help\n\n"
"OPTIONS\n"
" -e <method> Encrypt -d <method> Decrypt\n"
" --hash <alg> Hash (one-way, no decryption)\n"
" -k <key> Key / passphrase (see per-method notes)\n"
" -i <file> Input file -o <file> Output file\n\n"
"===========================================================================\n"
" HISTORICAL CIPHERS (pure C, zero dependencies)\n"
"===========================================================================\n\n"
" -- Classical Antiquity --------------------------------------------------\n\n"
" scytale Scytale transposition cipher (~700 BC, Sparta)\n"
" Wraps text around a staff; key is the number of columns.\n"
" Key: integer column-width >= 2 (e.g. -k \"4\")\n\n"
" atbash Atbash cipher (~600 BC, Hebrew, Biblical)\n"
" Reverses the alphabet: A<->Z, B<->Y ... Self-inverse.\n"
" Key: none (use -k \"\")\n\n"
" affine Affine cipher (Antiquity, precise date unknown)\n"
" Encrypts each letter as (a*x + b) mod 26.\n"
" Key: \"a,b\" (e.g. -k \"7,3\") a must be coprime to 26.\n"
" Valid a values: 1 3 5 7 9 11 15 17 19 21 23 25\n\n"
" polybe Polybius square (~200 BC, Ancient Greece)\n"
" Maps letters to row/column pairs in a 5x5 grid.\n"
" Output is larger than input (text pairs: \"11\" \"12\" ...).\n"
" Key: none (use -k \"\") | -e encodes, -d decodes\n\n"
" caesar Caesar shift cipher (~50 BC)\n"
" Key: integer shift 0-255 (e.g. -k \"13\")\n\n"
" -- Renaissance ----------------------------------------------------------\n\n"
" trithemius Trithemius cipher (Johannes Trithemius, 1508)\n"
" Auto-key progressive shift: position i shifts by i mod 26.\n"
" First printed book on cryptography (Polygraphia, 1508).\n"
" Key: none (use -k \"\")\n\n"
" vigenere Vigenere polyalphabetic cipher (Giovan Battista Bellaso, 1553)\n"
" Key: alphabetic string a-z/A-Z (e.g. -k \"lemon\")\n\n"
" porta Porta cipher (Giovanni Battista della Porta, 1563)\n"
" Reciprocal 13-row alphabet table. Self-inverse.\n"
" First book dedicated to cryptanalysis.\n"
" Key: alphabetic string (e.g. -k \"secret\")\n\n"
" bacon Bacon's cipher (Francis Bacon, 1605)\n"
" Steganographic binary encoding: each letter -> 5 A/B bits.\n"
" Key: none (use -k \"\") | -e encodes, -d decodes\n\n"
" -- 19th Century ---------------------------------------------------------\n\n"
" playfair Playfair cipher (Charles Wheatstone, 1854)\n"
" First digraph cipher; used by British Army in WWI.\n"
" Key: any word (e.g. -k \"monarchy\") | alpha only in/out\n\n"
" beaufort Beaufort cipher (Admiral Sir Francis Beaufort, 1857)\n"
" Vigenere variant: C = (K - P) mod 26. Self-inverse.\n"
" Key: alphabetic string a-z/A-Z (e.g. -k \"royalnavy\")\n\n"
" railfence Rail Fence transposition cipher (US Civil War era)\n"
" Writes text in zigzag across N rails, reads off row by row.\n"
" Key: integer number of rails >= 2 (e.g. -k \"3\")\n\n"
" -- World War I ----------------------------------------------------------\n\n"
" adfgvx ADFGVX cipher (German Army, 1918)\n"
" Polybius-like substitution over 6x6 grid + columnar transposition.\n"
" Key: \"SUBKEY:TRANSKEY\" (e.g. -k \"DEUTSCH:ANGRIFF\")\n"
" Output letters are from the set A D F G V X.\n\n"
" columnar Columnar transposition cipher (WWI / WWII)\n"
" Writes text into rows, reads columns in keyword-sorted order.\n"
" Key: alphabetic keyword (e.g. -k \"ZEBRAS\")\n\n"
" -- World War II ---------------------------------------------------------\n\n"
" double Double transposition cipher (SOE / WWII field cipher)\n"
" Two rounds of columnar transposition with two independent keys.\n"
" Key: \"KEY1:KEY2\" (e.g. -k \"SECURITY:LONDON\")\n\n"
" enigma Enigma machine simulation (1923-1945, Wehrmacht/Kriegsmarine)\n"
" Full simulation: 3 rotors (I-V), reflector B, plugboard.\n"
" Self-inverse: same settings decrypt what they encrypt.\n"
" Key format: \"R1:R2:R3:POS:PAIRS\"\n"
" R1/R2/R3 = rotor numbers I II III IV V (left to right)\n"
" POS = 3-letter start positions (e.g. AAA or XKZ)\n"
" PAIRS = plugboard pairs, space-separated (e.g. AB CD EF)\n"
" Examples:\n"
" -k \"I:II:III:AAA:\" (no plugboard)\n"
" -k \"IV:I:V:XKZ:AB CD EF GH\" (4 plugboard pairs)\n"
" Only A-Z processed; other bytes pass through unchanged.\n\n"
" -- Other 20th Century Ciphers -------------------------------------------\n\n"
" foursquare Four-Square cipher (Felix Delastelle, 1901)\n"
" Four 5x5 Playfair-like grids for digraph substitution.\n"
" Key: \"KEY1:KEY2\" (e.g. -k \"EXAMPLE:KEYWORD\") | alpha only\n\n"
" vernam Vernam cipher / One-Time Pad (Gilbert Vernam, 1917)\n"
" XOR with a key file of the same size as the input.\n"
" Proven information-theoretically secure (Shannon, 1949).\n"
" Key: @/path/to/keyfile (e.g. -k \"@/secure/mykey.bin\")\n"
" Self-inverse: same key file decrypts what it encrypts.\n\n"
" rot13 ROT13 substitution (Usenet, ~1980) Self-inverse.\n"
" Key: none (use -k \"\")\n\n"
" rot47 ROT47 substitution (Usenet, ~1990s) Self-inverse.\n"
" Rotates all 94 printable ASCII characters (0x21 to 0x7E) by 47.\n"
" Key: none (use -k \"\")\n\n"
"===========================================================================\n"
" MODERN STREAM CIPHERS (pure C)\n"
"===========================================================================\n\n"
" xor XOR byte cipher. Key: any string. Self-inverse.\n"
" rc4 RC4 stream cipher. Key: any string <= 256 chars. Self-inverse.\n\n"
"===========================================================================\n"
" MODERN BLOCK CIPHERS (OpenSSL, CBC mode + PKCS#7, PBKDF2 key derivation)\n"
"===========================================================================\n\n"
" chacha20 ChaCha20 (unauthenticated) Key: any passphrase\n"
" chacha20-poly1305 ChaCha20+Poly1305 [AUTH *] Key: any passphrase\n"
" camellia-128 Camellia-128-CBC Key: any passphrase\n"
" camellia-256 Camellia-256-CBC Key: any passphrase\n"
" aria-128 ARIA-128-CBC Key: any passphrase\n"
" aria-256 ARIA-256-CBC Key: any passphrase\n"
" sm4 SM4-CBC (Chinese std) Key: any passphrase\n"
" 3des Triple-DES-EDE-CBC [LEGACY] Key: any passphrase\n"
" aes-128 AES-128-CBC Key: any passphrase\n"
" aes-192 AES-192-CBC Key: any passphrase\n"
" aes-256 AES-256-CBC (recommended) Key: any passphrase\n"
" aes-128-gcm AES-128-GCM [AUTH *] Key: any passphrase\n"
" aes-192-gcm AES-192-GCM [AUTH *] Key: any passphrase\n"
" aes-256-gcm AES-256-GCM [AUTH *] (best) Key: any passphrase\n\n"
" -- Legacy block ciphers (OpenSSL legacy provider, CBC mode) -------------\n\n"
" des DES-CBC *** CRYPTOGRAPHICALLY BROKEN (56-bit key) ***\n"
" Key: any passphrase | included for legacy/educational use\n\n"
" blowfish Blowfish-CBC [LEGACY -- 64-bit block, SWEET32 risk]\n"
" Key: any passphrase | variable key 32-448 bits\n\n"
" cast5 CAST5-CBC [LEGACY -- 64-bit block, SWEET32 risk]\n"
" Key: any passphrase | used in older PGP and SSH\n\n"
" [*] Authenticated: decryption fails if the file was tampered with.\n\n"
"===========================================================================\n"
" HASH ALGORITHMS (--hash mode -- one-way)\n"
"===========================================================================\n\n"
" -- Legacy (broken -- for compatibility only) ----------------------------\n"
" md4 MD4 128-bit predecessor of MD5, used in NTLM\n"
" md5 MD5 128-bit broken since 2004\n"
" sha / sha1 SHA-1 160-bit deprecated; collision found 2017\n\n"
" -- SHA-2 family (NIST FIPS 180-4) --------------------------------------\n"
" sha224 SHA-224 224-bit / 56 hex chars\n"
" sha256 SHA-256 256-bit / 64 hex chars (recommended)\n"
" sha384 SHA-384 384-bit / 96 hex chars\n"
" sha512 SHA-512 512-bit / 128 hex chars\n\n"
" -- SHA-3 family (NIST FIPS 202) ----------------------------------------\n"
" sha3-256 SHA3-256 256-bit / 64 hex chars\n"
" sha3-512 SHA3-512 512-bit / 128 hex chars\n\n"
" -- BLAKE2 family -------------------------------------------------------\n"
" blake2b BLAKE2b 512-bit / 128 hex chars (fast on 64-bit)\n"
" blake2s BLAKE2s 256-bit / 64 hex chars (fast on 32-bit)\n\n"
"===========================================================================\n"
" EXAMPLES\n"
"===========================================================================\n\n"
" # Best modern security\n"
" %s -e aes-256-gcm -k \"P@ss!\" -i doc.pdf -o doc.enc\n"
" %s -d aes-256-gcm -k \"P@ss!\" -i doc.enc -o doc.pdf\n\n"
" # Enigma simulation (self-inverse -- same command decrypts)\n"
" %s -e enigma -k \"I:II:III:AAA:AB CD\" -i msg.txt -o msg.enc\n"
" %s -e enigma -k \"I:II:III:AAA:AB CD\" -i msg.enc -o msg.dec\n\n"
" # Vernam / One-Time Pad\n"
" %s -e vernam -k \"@/secure/pad.bin\" -i msg.txt -o msg.enc\n"
" %s -d vernam -k \"@/secure/pad.bin\" -i msg.enc -o msg.txt\n\n"
" # Playfair\n"
" %s -e playfair -k \"monarchy\" -i plain.txt -o cipher.txt\n\n"
" # ADFGVX\n"
" %s -e adfgvx -k \"DEUTSCH:ANGRIFF\" -i plain.txt -o cipher.txt\n\n"
" # Polybius (encoding)\n"
" %s -e polybe -k \"\" -i plain.txt -o encoded.txt\n"
" %s -d polybe -k \"\" -i encoded.txt -o plain.txt\n\n"
" # Bacon steganography\n"
" %s -e bacon -k \"\" -i plain.txt -o bacon.txt\n"
" %s -d bacon -k \"\" -i bacon.txt -o plain.txt\n\n"
" # Hash\n"
" %s --hash sha256 -i firmware.bin\n\n",
p,p,p,p, p,p,p,p,p,p,p,p,p,p,p,p,p,p);
}
/* ═══════════════════════════════════════════════════════════════════════════
███ HISTORICAL CIPHERS
═══════════════════════════════════════════════════════════════════════════ */
/* ───────────────────────────────────────────────────────────────────────────
Shared transposition helpers
─────────────────────────────────────────────────────────────────────────── */
/* Read entire FILE into a malloc'd buffer; set *len to byte count. */
static uint8_t *read_all(FILE *in, size_t *len)
{
uint8_t *buf = NULL; size_t n = 0, cap = 0; int ch;
while ((ch = fgetc(in)) != EOF) {
if (n + 1 > cap) {
cap = cap ? cap * 2 : 256;
uint8_t *nb = (uint8_t *)realloc(buf, cap);
if (!nb) { free(buf); die("out of memory"); }
buf = nb;
}
buf[n++] = (uint8_t)ch;
}
*len = n;
return buf ? buf : (uint8_t *)calloc(1, 1);
}
/* Build sorted column order from keyword: order[i] = original column for
the i-th column in sorted (alphabetical) keyword order. */
static int *keyword_order(const char *key, int ncols)
{
int *order = (int *)malloc((size_t)ncols * sizeof(int));
if (!order) die("out of memory");
for (int i = 0; i < ncols; i++) order[i] = i;
/* Stable sort: compare keyword chars, tie-break by original position */
for (int i = 0; i < ncols - 1; i++)
for (int j = i + 1; j < ncols; j++)
if (toupper((unsigned char)key[order[i]]) >
toupper((unsigned char)key[order[j]])) {
int t = order[i]; order[i] = order[j]; order[j] = t;
}
return order;
}
/* KEY INSIGHT FOR RAGGED GRIDS
* When tlen is not a multiple of ncols:
* nrows = ceil(tlen / ncols)
* full_cols = tlen % ncols
*
* In the plain grid (written row by row), the last row has only
* full_cols characters, occupying ORIGINAL columns 0 .. full_cols-1.
* ORIGINAL columns full_cols .. ncols-1 are empty in the last row.
*
* Therefore:
* col_rows(col) = nrows if col < full_cols (or full_cols == 0)
* col_rows(col) = nrows-1 if col >= full_cols (and full_cols != 0)
*
* This is purely about ORIGINAL column indices, not sorted positions.
*/
#define COL_ROWS(col, nrows, full_cols) \
(((full_cols) == 0 || (col) < (full_cols)) ? (nrows) : (nrows)-1)
/* Columnar encrypt: write columns of text[] in order[] sequence. */
static void columnar_enc_core(const uint8_t *text, size_t tlen,
int ncols, const int *order, FILE *out)
{
if (tlen == 0) return;
int nrows = (int)((tlen + (size_t)ncols - 1) / (size_t)ncols);
int full_cols = (int)(tlen % (size_t)ncols);
for (int ci = 0; ci < ncols; ci++) {
int col = order[ci];
int col_rows = COL_ROWS(col, nrows, full_cols);
for (int r = 0; r < col_rows; r++)
fputc((int)text[(size_t)r * (size_t)ncols + (size_t)col], out);
}
}
/* Columnar decrypt: reconstruct plaintext from cipher and column order.
* Returns malloc'd buffer of exactly clen bytes; caller must free(). */
static uint8_t *columnar_dec_core(const uint8_t *cipher, size_t clen,
int ncols, const int *order)
{
if (clen == 0) return (uint8_t *)calloc(1, 1);
int nrows = (int)((clen + (size_t)ncols - 1) / (size_t)ncols);
int full_cols = (int)(clen % (size_t)ncols);
/* Allocate the plain grid (row-major). */
uint8_t *grid = (uint8_t *)calloc((size_t)(nrows * ncols), 1);
if (!grid) die("out of memory");
/* Fill each column from the cipher stream in sorted order. */
size_t src = 0;
for (int ci = 0; ci < ncols; ci++) {
int col = order[ci];
int col_rows = COL_ROWS(col, nrows, full_cols);
for (int r = 0; r < col_rows; r++)
grid[(size_t)r * (size_t)ncols + (size_t)col] = cipher[src++];
}
/* Read the grid back in row-major order, skipping padding cells.
* A cell (r, col) is padding iff r == nrows-1 AND col >= full_cols
* (and full_cols != 0). We collect exactly clen bytes. */
uint8_t *result = (uint8_t *)malloc(clen);
if (!result) { free(grid); die("out of memory"); }
size_t dst = 0;
for (int r = 0; r < nrows && dst < clen; r++)
for (int c = 0; c < ncols && dst < clen; c++) {
int is_pad = (full_cols != 0)
&& (r == nrows - 1)
&& (c >= full_cols);
if (!is_pad)
result[dst++] = grid[(size_t)r * (size_t)ncols + (size_t)c];
}
free(grid);
return result;
}
/* ───────────────────────────────────────────────────────────────────────────
SCYTALE (~700 BC, Sparta)
The oldest known device-based cipher. A leather strip was wound helically
around a staff (skytale); the message was written lengthwise and appeared
random when unwound. Only a staff of the same diameter could decode it.
Here the key is the number of columns (the staff circumference in chars).
─────────────────────────────────────────────────────────────────────────── */
static void scytale_encrypt(FILE *in, FILE *out, int cols)
{
if (cols < 2) die("Scytale: key must be an integer >= 2.");
size_t tlen; uint8_t *text = read_all(in, &tlen);
/* Identity order: read columns left-to-right */
int *order = (int *)malloc((size_t)cols * sizeof(int));
if (!order) die("out of memory");
for (int i = 0; i < cols; i++) order[i] = i;
columnar_enc_core(text, tlen, cols, order, out);
free(text); free(order);
}
static void scytale_decrypt(FILE *in, FILE *out, int cols)
{
if (cols < 2) die("Scytale: key must be an integer >= 2.");
size_t clen; uint8_t *cipher = read_all(in, &clen);
int *order = (int *)malloc((size_t)cols * sizeof(int));
if (!order) die("out of memory");
for (int i = 0; i < cols; i++) order[i] = i;
uint8_t *plain = columnar_dec_core(cipher, clen, cols, order);
fwrite(plain, 1, clen, out);
free(cipher); free(order); free(plain);
}
/* ───────────────────────────────────────────────────────────────────────────
AFFINE CIPHER (classical antiquity)
Generalisation of Caesar using modular arithmetic:
encrypt: C = (a * P + b) mod 26
decrypt: P = a_inv * (C - b) mod 26
a must be coprime to 26: valid values are 1 3 5 7 9 11 15 17 19 21 23 25.
Key format: "a,b" (e.g. -k "7,3")
Only letters are transformed; all other bytes pass through unchanged.
─────────────────────────────────────────────────────────────────────────── */
static int affine_modinv(int a, int m)
{
int t = 0, newt = 1, r = m, newr = a;
while (newr) {
int q = r / newr, tmp;
tmp = t - q * newt; t = newt; newt = tmp;
tmp = r - q * newr; r = newr; newr = tmp;
}
return (r > 1) ? -1 : (t < 0 ? t + m : t);
}
static void affine_cipher(FILE *in, FILE *out, const char *key, int dec)
{
int a = 1, b = 0;
if (sscanf(key, "%d,%d", &a, &b) != 2)
die("Affine: key must be \"a,b\" e.g. -k \"7,3\".");
a = ((a % 26) + 26) % 26;
b = ((b % 26) + 26) % 26;
int a_inv = affine_modinv(a, 26);
if (a_inv < 0)
die("Affine: 'a' must be coprime to 26.\n"
" Valid values: 1 3 5 7 9 11 15 17 19 21 23 25");
uint8_t buf[CHUNK_SIZE]; size_t n, i;
while ((n = fread(buf, 1, CHUNK_SIZE, in)) > 0) {
for (i = 0; i < n; i++) {
uint8_t c = buf[i];
if (isalpha(c)) {
uint8_t base = isupper(c) ? 'A' : 'a';
int p = c - base;
int q = dec ? (a_inv * (p - b + 26)) % 26
: (a * p + b) % 26;
buf[i] = (uint8_t)(base + q);
}
}
fwrite(buf, 1, n, out);
}
}
/* ───────────────────────────────────────────────────────────────────────────
TRITHEMIUS CIPHER (Johannes Trithemius, 1508)
Described in Polygraphia (1508), the first printed book on cryptography.
Each letter at position i (counting only letters) is shifted by i mod 26,
using the tabula recta — an auto-key progressive Caesar. No secret keyword;
it introduced the concept of a polyalphabetic cipher for later work.
Only letters are transformed; other bytes pass through unchanged.
─────────────────────────────────────────────────────────────────────────── */
static void trithemius_cipher(FILE *in, FILE *out, int dec)
{
uint8_t buf[CHUNK_SIZE]; size_t n, i;
int shift = 0;
while ((n = fread(buf, 1, CHUNK_SIZE, in)) > 0) {
for (i = 0; i < n; i++) {
uint8_t c = buf[i];
if (isalpha(c)) {
uint8_t base = isupper(c) ? 'A' : 'a';
int p = c - base;
int q = dec ? ((p - shift) % 26 + 26) % 26
: (p + shift) % 26;
buf[i] = (uint8_t)(base + q);
shift = (shift + 1) % 26;
}
}
fwrite(buf, 1, n, out);
}
}
/* ───────────────────────────────────────────────────────────────────────────
PORTA CIPHER (Giovanni Battista della Porta, 1563)
Described in De Furtivis Literarum Notis, the first book dedicated entirely
to cryptanalysis. A 13-row reciprocal table keyed by a repeating keyword:
each key-char selects a row; the row maps A–M <-> N–Z. Because the mapping
is its own inverse, Porta is self-inverse.
Only letters are transformed; other bytes pass through unchanged.
─────────────────────────────────────────────────────────────────────────── */
static const int PORTA_TABLE[13][13] = {
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12},
{ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 0},
{ 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 0, 1},
{ 3, 4, 5, 6, 7, 8, 9,10,11,12, 0, 1, 2},
{ 4, 5, 6, 7, 8, 9,10,11,12, 0, 1, 2, 3},
{ 5, 6, 7, 8, 9,10,11,12, 0, 1, 2, 3, 4},
{ 6, 7, 8, 9,10,11,12, 0, 1, 2, 3, 4, 5},
{ 7, 8, 9,10,11,12, 0, 1, 2, 3, 4, 5, 6},
{ 8, 9,10,11,12, 0, 1, 2, 3, 4, 5, 6, 7},
{ 9,10,11,12, 0, 1, 2, 3, 4, 5, 6, 7, 8},
{10,11,12, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{11,12, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10},
{12, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11},
};
static void porta_cipher(FILE *in, FILE *out, const char *key)
{
size_t klen = strlen(key);
if (!klen) die("Porta: key must be a non-empty alphabetic string.");
for (size_t i = 0; i < klen; i++)
if (!isalpha((unsigned char)key[i]))
die("Porta: key must contain only letters (a-z / A-Z).");
uint8_t buf[CHUNK_SIZE]; size_t n, ki = 0;
while ((n = fread(buf, 1, CHUNK_SIZE, in)) > 0) {
for (size_t i = 0; i < n; i++) {
uint8_t c = buf[i];
if (!isalpha(c)) continue;
int upper = toupper(c) - 'A';
int row = (tolower(key[ki++ % klen]) - 'a') / 2;
if (upper < 13) {
buf[i] = (uint8_t)((isupper(c) ? 'N' : 'n')
+ PORTA_TABLE[row][upper]);
} else {
int target = upper - 13;
for (int j = 0; j < 13; j++) {
if (PORTA_TABLE[row][j] == target) {
buf[i] = (uint8_t)((isupper(c) ? 'A' : 'a') + j);
break;
}
}
}
}
fwrite(buf, 1, n, out);
}
}
/* ───────────────────────────────────────────────────────────────────────────
BEAUFORT CIPHER (Admiral Sir Francis Beaufort, 1857)
Vigenère variant with the formula reversed: C = (K - P) mod 26.
This makes it self-inverse: the same key and same operation both encrypts
and decrypts. Used by the British Royal Navy; referenced in Ian Fleming's
James Bond novels (From Russia with Love).
Only letters are transformed; other bytes pass through unchanged.
─────────────────────────────────────────────────────────────────────────── */
static void beaufort_cipher(FILE *in, FILE *out, const char *key)
{
size_t klen = strlen(key);
if (!klen) die("Beaufort: key must be a non-empty alphabetic string.");
for (size_t i = 0; i < klen; i++)
if (!isalpha((unsigned char)key[i]))
die("Beaufort: key must contain only letters (a-z / A-Z).");
uint8_t buf[CHUNK_SIZE]; size_t n, ki = 0;
while ((n = fread(buf, 1, CHUNK_SIZE, in)) > 0) {
for (size_t i = 0; i < n; i++) {
uint8_t c = buf[i];
if (isalpha(c)) {
uint8_t base = isupper(c) ? 'A' : 'a';
int p = c - base;
int k = tolower(key[ki++ % klen]) - 'a';
buf[i] = (uint8_t)(base + ((k - p + 26) % 26));
}
}
fwrite(buf, 1, n, out);
}
}
/* ───────────────────────────────────────────────────────────────────────────
ROT47 (Usenet, ~1990s)
Extends ROT13 to all 94 printable ASCII characters (0x21 '!' to 0x7E '~').
Each character is rotated 47 positions within that range, making the cipher
self-inverse. Used on Usenet to hide spoilers and adult content.
Characters outside 0x21–0x7E pass through unchanged.
─────────────────────────────────────────────────────────────────────────── */
static void rot47_cipher(FILE *in, FILE *out)
{
uint8_t buf[CHUNK_SIZE]; size_t n, i;
while ((n = fread(buf, 1, CHUNK_SIZE, in)) > 0) {
for (i = 0; i < n; i++) {
uint8_t c = buf[i];
if (c >= 33 && c <= 126)
buf[i] = (uint8_t)(33 + (c - 33 + 47) % 94);
}
fwrite(buf, 1, n, out);
}
}
/* ───────────────────────────────────────────────────────────────────────────
FOUR-SQUARE CIPHER (Félix Delastelle, 1901)
Invented by Félix Delastelle (who also devised bifid and trifid). Uses four
5×5 Playfair-like squares: top-left and bottom-right are the standard plain
alphabet (I=J); top-right is keyed from KEY1; bottom-left from KEY2.
Encrypts digraphs: for (P1, P2), locate P1 in top-left and P2 in
bottom-right; output is top-right[row(P1)][col(P2)] and
bottom-left[row(P2)][col(P1)].
Handles alpha only; J treated as I. Key format: "KEY1:KEY2".
─────────────────────────────────────────────────────────────────────────── */
static void foursquare_build(const char *key, char sq[5][5])
{
int used[26] = {0}, r = 0, c = 0;
for (int i = 0; key[i] && r < 5; i++) {
int k = toupper((unsigned char)key[i]) - 'A';
if (k < 0 || k > 25 || k == 9 || used[k]) continue; /* skip J */
used[k] = 1; sq[r][c] = (char)('A' + k);
if (++c == 5) { c = 0; r++; }
}
for (int k = 0; k < 26 && r < 5; k++) {
if (k == 9 || used[k]) continue;
sq[r][c] = (char)('A' + k);
if (++c == 5) { c = 0; r++; }
}
}