• AutoKey Cipher in AWK

    From Mike Sanders@21:1/5 to All on Sun Aug 18 09:01:57 2024
    One more! Meant to post this awhile back. Nifty little cipher
    (hopfully post does not suffer from wordwrap)...


    # AutoKey Cipher in AWK: Michael Sanders - 2024
    #
    # https://en.wikipedia.org/wiki/Autokey_cipher
    #
    # encryption example:
    #
    # echo "secret message?" | awk -f autokey.awk -v password=hunkyDory68 -v mode=1 #
    # decryption example:
    #
    # echo "ae@beTv?egumIe4" | awk -f autokey.awk -v password=hunkyDory68 -v mode=0

    BEGIN {

    if (length(password) < 1) exit

    if (mode != 1 && mode != 0) exit # 1 encrypt, 0 decrypt

    # base character set: beware chars & groupings of chars that require or produce # escaped values, also throughly randomize/shuffle the string for your own BASE # if a given char is not included in BASE it will be rendered as is...

    BASE = "5KVn?.PB 3iMhqgdxsClJ!7AcLrz@Ra=fTj2w9yIHFkYO8DEmoU0Wp1XZtv#SG4u-*N6Qb%"

    }

    { print autokeyCipher($0, password, mode) }

    function autokeyCipher(input, key, mode, ak, ic, oc, kc, ix, ox, kx, li, lb, x, buf) {

    li = length(input)
    lb = length(BASE)
    ak = key

    for(x = 1; x <= li; x++) {
    ic = substr(input, x, 1)
    ix = index(BASE, ic)

    if(ix == 0) {
    buf = buf ic
    continue
    }

    kc = substr(ak, (x - 1) % length(ak) + 1, 1)
    kx = index(BASE, kc)

    if(mode == 1) { # encryption mode
    ox = (ix + kx - 1) % lb + 1
    oc = substr(BASE, ox, 1)
    ak = ak ic # append ic to autokey
    } else { # decryption mode
    ox = (ix + lb - kx) % lb
    if(ox == 0) ox = lb
    oc = substr(BASE, ox, 1)
    ak = ak oc # append oc to autokey
    }

    buf = buf oc
    }

    return buf
    }

    # eof

    --
    :wq
    Mike Sanders

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)