mCrypt
From
porkchop@porkchop@invalid.foo (Mike Sanders) to
comp.lang.awk on Sun Oct 1 10:29:17 2023
From Newsgroup: comp.lang.awk
Okay, taken this about as far as I can without revealing some work-related stuff. This is realted to the 'mHash' thread elsewhere.
A little string substitution cipher called 'mCrypt' (Mike's Crypt) below...
Couple of quick additional notes:
. substitution ciphers have a surface area of attack that are prone to
frequency analysis, so the astute user will use a long password, or better
yet a 'passphrase'. Song lyrics are easy to remember, eg:
passphrase: 'We all live in a yellow Subm@rine321"
. error-checking is your baby, here's its handled in advance, be sure to look
at the length of input strings and password length.
. the line containing the string 'BASE' may wrap in your newsreader, so watch
for that issue, it needs to on a single line...
Have fun =)
# init_map(password): Initializes and returns the substitution map based on
# the provided password. The password influences the ordering of characters
# in the map.
#
# sanitize_password(password): Sanitizes the provided password by removing
# any character not present in the BASE character set. It also ensures that
# each character is unique in the sanitized password.
#
# mCrypt(str, password, mode): Depending on the mode, it either encodes or
# decodes the input string str using the substitution cipher. Mode 1 is for
# encoding, and Mode 0 is for decoding. The function returns the transformed
# string.
#
# The string variable 'BASE' contains all printable ASCII characters except
# newline ('\n'), which are in the range 32 to 126 inclusive.
BEGIN {
BASE = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
e = mCrypt("Obladi Oblada Life Goes On Brah!", "P@ssw0rd", 1)
d = mCrypt(e, "P@ssw0rd", 0)
printf("Encoded: %s\n", e)
printf("Decoded: %s\n", d)
}
# ---------------------------------------------------------------------------
function init_map(password, x, y, p, c, map) {
map = ""
password = sanitize_password(password, BASE)
p = password
x = length(BASE)
while(length(map) < x) {
for(y = 1; y <= length(p); y++) {
c = substr(p, y, 1)
if(index(map, c) == 0) map = map c
}
p = BASE
}
return map
}
# ---------------------------------------------------------------------------
function sanitize_password(password, x, y, c, tmp) {
tmp = ""
y = length(password)
while(++x <= y) {
c = substr(password, x, 1)
if(index(BASE, c) != 0 && index(tmp, c) == 0) tmp = tmp c
}
return tmp
}
# ---------------------------------------------------------------------------
function mCrypt(str, password, mode, x, y, z, c, s, map, buf) {
map = init_map(password)
buf = ""
y = length(str)
while(++x <= y) {
c = substr(str, x, 1)
z = (mode == 1 ? index(BASE, c) : index(map, c))
s = (z == 0 ? c : substr(mode == 1 ? map : BASE, z, 1))
buf = buf s
}
return buf
}
# eof
--
:wq
Mike Sanders
--- Synchronet 3.20a-Linux NewsLink 1.114