> | # a little bit of cryptography: |
> | with(StringTools): |
Warning, the assigned name Group now has a global binding
> | Map( Capitalize, "This is a test." );
|
> | Map( LowerCase, %);
|
> | convert("Test string", 'bytes');
|
> | convert([65,66,67], 'bytes');
|
> | convert("abcdefghijklmnopqrstuvwxyz", 'bytes');
|
> | convert("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 'bytes');
|
> | # irem(a, b) gives the remainder r of a upon division by b,
# i.e. the r in a = q * b + r with 0 <= r < b. # For example, |
> | irem(17,5);
|
> | # but |
> | irem(-1,5);
|
> | # the Caesar cipher is the following:
# it takes the plaintext and shifts the letters # alphabetically by some fixed amount # For instance, a shift by 3 amounts to # a -> d # b -> e # c -> f # ... # w -> z # x -> a # y -> b # z -> d # # So, abc becomes def, for instance. # to decipher, oneft back the other direction by the same amount. |
> | # now we implement the Caesar cipher,
# which is shifting the letters of the alphabet by some fixed amount |
> | caesar := proc(s::string, shift::integer)
local S, l, i, c; S := convert(s,'bytes'); l := nops(S); for i to l do c := S[i]; if c >= 97 and c <= 122 then c := c - 97 + shift; c := irem(c, 26); if c < 0 then c := c + 26; end; S[i] := 97 + c; end; end; return convert(S,'bytes'); end; |
> | # encryption: |
> | caesar("abcdefghijklmnopqrstuvwxyz", 3);
|
> | # decryption using the negative shift |
> | caesar(%, -3);
|
> | caesar("abcdefghijklmnopqrstuvwxyz", 26);
|
> | caesar("ilovethiscourse", 17); |
> | caesar(%, -17); |
> |