Jelly, 2832 28 27 bytes
ØṖœØṖµœ!95Ż¤,ØṖṗ75Ż¤¤Ẏ€³œṗ75Ż¤$Ẏ€³œ?µḢi⁴ịḢ
Since this code generates all the permutations and therefore would take very long to finish, TIO link is to a limited version that supports characters abcdefg
, message length 4 and encoded length 5. I checked that these numbers follow similar constraints as the actual ones. Only the constants are changed, so the true version should also (theoretically) work.
Explanation
ØṖœØṖµœ!95Ż¤,ØṖṗ75Ż¤¤Ẏ€³œṗ75Ż¤$Ẏ€³œ?µḢi⁴ịḢ Dyadic link that accepts the boolean flag and message
ØṖ ASCII printable characters
œ! µ Permutations ofFeed size
into new monadic chain
95Ż¤ œ! 0..95
Permutations of size
, 95Ż¤ ¤ Pair with
0..95
ØṖ , $ ASCII printablePair characterswith
ṗ Cartesian power
75Ż¤ 0..75
Ẏ€ Flatten both lists (non-recursively)
³œ? Reverse the pair if the boolean flag is set
µ Feed into new monadic linkchain
Ḣ Pop first item of the pair
i⁴ Find index of the message
ịḢ Index into the head of what used to be the pair