Math 455.1  • 27 March 2009

Affine encryption scheme

Copyright © 2009 by Murray Eisenberg.  All rights reserved.

Conventions

The affine encryption scheme here follows the convention of first adding the "additive" part of the key and then, after that, multiplying by the "multiplicative" part of the key.  (Some authors do multiplication first, then addition.)

It also follows the convention of coding A numerically as 0, B as 1, etc.

Preparation: encoding and decoding between characters and numbers

The alphabet:

alph = Characters["ABCDEFGHIJKLMNOPQRSTUVWXYZ"];

Tests for characters and numbers in range:

letterQ[ch_]:=MemberQ[alph,ch]
inRangeQ[n_]:=IntegerQ[n]&&0≤n≤25

Encoding function:

toNumber[ch_?letterQ]:=First@First@Position[alph,ch]-1
SetAttributes[toNumber,Listable]

Decoding function:

toCharacter[n_?inRangeQ]:=alph[[n+1]]
SetAttributes[toCharacter,Listable]

Alice encodes and encrypts

msg = "SENDYAKS";

ptxt = toNumber[Characters[msg]]

encrypt[a_Integer?NonNegative, {c_, k_}] := Mod[c ( a + k),  26]

AliceEkey = {7, 2};
AliceEncrypt[a_] := encrypt[a, AliceEkey]

ctxt = Map[AliceEncrypt, ptxt]

StringJoin[toCharacter[ctxt]]

Bob decrypts and decodes

AliceEkey

PowerMod[7, -1, 26]

Check:

Mod[7 15, 26]

BobDkey = {PowerMod[AliceEkey[[1]], -1, 26], AliceEkey[[2]]}

decrypt[b_, {d_, h_}] := Mod[d b - h, 26]
(* encrypt[b, {d, -c k} *)

BobDecrypt[b_] := decrypt[b, BobDkey]

Map[BobDecrypt, ctxt]

StringJoin[toCharacter[%]]

Note

Notice that we had to use Map in order to make AliceEncrypt and BobDecrypt act upon whole lists of integers and not just single integers.  You might think that giving them, and the more general functions encrypt and decrypt, the attributes Listable, would accomplish the same thing.  But that ruse does not work here, because encrypt and decrypt each takes two arguments.