Wolfram Research

Function Repository Resource:

AffineCipher

Source Notebook

Encipher a string using the affine cipher

Contributed by: Sander Huisman

ResourceFunction["AffineCipher"][string,{a,b}]

enciphers string using the affine cipher with parameters a and b.

ResourceFunction["AffineCipher"][{a,b}]

represents an operator form of ResourceFunction["AffineCipher"] that can be applied to an expression.

Details and Options

The letters az are numbered 0–25. Each character in string is converted to a number (x) using the aforementioned numbering. Each number is then transformed by computing (ax+b) mod 26. The new numbers are then reinterpreted as letters. Here is an example enciphering the letters AZ for a=5 and b=8:

The case of the letters is retained by ResourceFunction["AffineCipher"].

Examples

Basic Examples

Convert a simple text:

In[1]:=
ResourceFunction["AffineCipher"]["affine cipher", {5, 8}]
Out[1]=

Scope

AffineCipher automatically threads over a list of strings:

In[2]:=
ResourceFunction["AffineCipher"][{"this", "is", "a", "test"}, {5, 8}]
Out[2]=

Create an operator:

In[3]:=
op = ResourceFunction["AffineCipher"][{5, 8}]
Out[3]=

Apply the operator to a string:

In[4]:=
op["balloon"]
Out[4]=

Properties and Relations

The Caesar cipher can be recreated using the affine cipher by choosing a=1:

In[5]:=
string = "This is just a test";
{ResourceFunction["AffineCipher"][string, {1, 8}], ResourceFunction["CaesarCipher"][string, 8]}
Out[6]=

Possible Issues

The parameter a must be coprime with 26:

In[7]:=
ResourceFunction["AffineCipher"]["Mathematica", {4, 2}]
Out[7]=

Some of the permissible values for a are:

In[8]:=
Select[Range[100], CoprimeQ[#, 26] &]
Out[8]=

Strings using numbers or letters with diacritics are not converted:

In[9]:=
ResourceFunction[
 "AffineCipher"]["It was Chloë who opened the 2 piñatas", {5, 8}]
Out[9]=

Use RemoveDiacritics, StringDelete, IntegerName and ToLowerCase to transform the message:

In[10]:=
string = StringReplace[
  ToLowerCase[
   StringDelete[
    RemoveDiacritics["It was Chloë who opened the 2 piñatas"], " "]], r : Longest[DigitCharacter ..] :> IntegerName[ToExpression@r]]
Out[10]=

Now the transformed message can be enciphered:

In[11]:=
ResourceFunction["AffineCipher"][string, {5, 8}]
Out[11]=

Resource History

Related Resources

License Information