  [Caesar cipher for Rosetta Code.
  EDSAC program, Initial Orders 2.]

  [Table for converting alphabetic position 0..25 to EDSAC code.
   The EDSAC code is in the high 5 bits.]
            T   54 K [access table via C parameter]
            P   56 F
            T   56 K
   AFBFCFDFEFFFGFHFIFJFKFLFMFNFOFPFQFRFSFTFUFVFWFXFYFZF

  [Table for converting 5-bit EDSAC code to alphabetic position 0..25.
   Computed at run time (so the programmer doesn't need to know the EDSAC codes).
   32 entries; entry is -1 if the EDSAC code does not represent a letter.]
            T   53 K [access table via B parameter]
            P   82 F

  [Subroutine to read string from input and
     store with char codes in high 5 bits.
   String is terminated by blank row of tape, which is stored.
   Input: 0F holds address of string in address field (bits 1..11).
   22 locations; workspace: 4D]
            T  114 K
   [email protected]@[email protected]@[email protected]@[email protected]@T5FEFUFK2048F

  [Subroutine to print string with character codes in high 5 bits.
   String is terminated by blank row of tape, which is not printed.
   Input: 0F holds address of string in address field (bits 1..11).
   18 locations; orkspace: 4F]
            T  136 K
   [email protected]@[email protected]@[email protected]@[email protected]@TFEFK2048F

  [Define start of user message]
            T   47 K  [access message via M parameter]
            P  350 F  [address of message]

            T  154 K
            G      K
  [Constants]
      [0]   P      M  [address of user message]
      [1]   A      B
      [2]   A      C
      [3]   T      B
      [4]   P   25 F
      [5]   P   26 F
      [6]   P   31 F
      [7]   K 2048 F  [(1) letter shift (2) used in test for
                        blank row of tape at end of message]
      [8]   @      F  [carriage return]
      [9]   &      F  [line feed]
     [10]   K 4096 F  [null char]

  [Constant messages. Each includes new line at the end.]
     [11]   TF EF SF TF IF NF GF @F &F K4096F
     [21]   P   11 @
     [22]   EF NF TF EF RF !F MF EF SF SF AF GF EF @F &F K4096F
     [38]   P   22 @
     [39]   MF UF SF TF !F SF TF AF RF TF !F WF IF TF HF !F BF !F TF OF !F ZF @F &F K4096F
     [64]   P   39 @

 [Subroutine to convert EDSAC code to alphabetic position.
  Input:  4F holds EDSAC code in high 5 bits
  Output: 4F holds alphabetic position (0..25, or -1 if not a letter).
  Workspace: 5F]
     [65]   A    3 F  [make jump for return]
            T   75 @  [plant in code]
            A    4 F  [load EDSAC code]
            R  512 F  [shift code into address field]
            T    5 F  [temp store]
            C    5 F  [acc := address bits only]
            A    1 @  [make order to load alphabetic position]
            T   73 @  [plant in code]
     [73]   A      B  [load alphabetic position]
            T    4 F  [store in 4F]
     [75]   E      F  [return]

 [Subroutine to encipher or decipher a message by Caesar shift.
  Input:  Message is accessed by the M parameter, and
          terminated by a blank row of tape.
  Output: 0F = error flag: 0 if OK, < 0 if error (bad message prefix)
  Workspace 4F.]
     [76]   A    3 F  [make jump for return]
            T  119 @  [plant in code]
            A   80 @  [load order to access first char]
            T   95 @  [plant in code]
     [80]   A      M  [load first char of message]
            T    4 F  [pass to subroutine]
     [82]   A   82 @  [get alphabetic position]
            G   65 @
            A    4 F  [load alphabetic position]
            U      F  [to 0F for use as shift]
            S    2 F  [check it's not 0 or -1]
            G  118 @  [error exit if it is]
            T    1 F  [clear acc]
            S      F  [load negative of shift]
            G  108 @  [jump to store first char
                       and convert rest of message]
           [Here after skipping non-letter]
     [91]   T    4 F  [clear acc]
           [Here after converting letter]
     [92]   A   95 @  [load order to read character]
            A    2 F  [inc address to next character]
            T   95 @  [store back]
     [95]   A      M  [load char from message (in top 5 bits)]
            E  100 @  [if >= 0 then not blank row]
            A    7 @  [if < 0, test for blank row]
            G  117 @  [jump out if so]
            S    7 @  [restore after test]
    [100]   T    4 F  [character to 4F for subroutine]
    [101]   A  101 @  [for return from subroutine]
            G   65 @  [sets 4F := alphabetic position]
            A    4 F  [to acc]
            G   91 @  [if < 0 then not a letter; don't change it]
            A      F  [apply Caesar shift]
           [Subtract 26 if required, so result is in range 0..25]
            S    5 @  [subtract 26]
            E  109 @  [skip next if result >= 0]
    [108]   A    5 @  [add 26]
    [109]   A    2 @  [make order to read EDSAC letter at that position]
            T  114 @  [plant in code]
            A   95 @  [load A order from above]
            A   14 C  [add 'O F' to make T order]
            T  115 @  [plant in code]
    [114]   A      C  [load enciphered letter]
    [115]   T      M  [overwrite original letter]
            E   92 @  [loop back]
    [117]   T      F  [flag = 0 for OK]
    [118]   T      F  [flag to 0F: 0 if OK, < 0 if error]
    [119]   E      F  [return with acc = 0]

 [Subroutine to print encipered or deciphered message, plus new line]
    [120]   A    3 F  [make jump order for return]
            T  128 @  [plant in code]
            A      @  [load address of message]
            T      F  [to 0F for print subroutine]
    [124]   A  124 @
            G  136 F  [print message, clears acc]
            O    8 @  [print new line]
            O    9 @
    [128]   E      F  [return with acc = 0]

 [Main routine]
    [129]   O    7 @  [set letter shift]
            H    6 @  [mult reg has this value throughout;
                       selects bits 1..5 of 17-bit value]
           [Build inverse table from direct table
            First initialize all 32 locations to -1]
            A    6 @  [work backwards]
    [132]   A    3 @  [make T order for inverse table]
            T  135 @  [plant in code]
            S    2 F  [make -1 in address field]
    [135]   T      B  [store in inverse table]
            A  135 @  [get T order]
            S    2 F  [dec address]
            S    3 @  [compare with start of table]
            E  132 @  [loop till done]
           [Now fill in entries by reversing direct table]
            T      F  [clear acc]
            A    4 @  [work backwards]
    [142]   U    5 F  [index in 5F]
            A    2 @  [make A order for direct table]
            T  145 @  [plant in code]
    [145]   A      C  [load entry from direct table, code in top 5 bits]
            R  512 F  [shift 11 right, 5-bit code to address field]
            T    4 F  [temp store]
            C    4 F  [pick out 5-bit code]
            A    3 @  [make T order for inverse table]
            T  152 @  [plant in code]
            A    5 F  [load index]
    [152]   T      B  [store in inverse table]
            A    5 F  [load index again]
            S    2 F  [update index]
            E  142 @  [loop back]
           [Here when inverse table is complete]
    [156]   T      F  [clear acc]
    [157]   A   21 @  [load address of "testing" message]
            T      F  [to 0F for print subroutine]
    [159]   A  159 @
            G  136 F  [print "testing message"]
            E  168 @  [jump to read from end of this file]
           [Loop back here to get message from user]
    [162]   A   38 @  [load address of prompt]
            T      F  [to 0F for print subroutine]
    [164]   A  164 @
            G  136 F  [print prompt]
            O   10 @  [print null to flush teleprinter buffer]
            Z      F  [stop]
           [First time here, read message from end of this file.
            Later times, read message from file chosen by the user.]
    [168]   A      @  [load address of message]
            T      F  [to 0F for input]
    [170]   A  170 @
            G  114 F  [read message]
    [172]   A  172 @
            G  120 @  [print message]
    [174]   A  174 @
            G   76 @  [call Caesar shift subroutine]
            A      F  [load error flag]
            E  184 @  [jump if OK]
            T      F  [error, clear acc]
            A   64 @  [load address of error message]
            T      F
    [181]   A  181 @
            G  136 F  [print error message]
            E  162 @  [back to try again]
           [Here if message was enciphered without error]
    [184]   A  184 @
            G  120 @  [print enciphered message]
    [186]   A  186 @
            G   76 @  [call Caesar shift subroutine]
    [188]   A  188 @
            G  120 @  [print deciphered message]
            E  162 @  [back for another message]
            E  129 Z  [define entry point]
            P      F  [acc = 0 on entry]
DGAZA!FREQUENS!LIBYCUM!DUXIT!KARTHAGO!TRIUMPHUM.


class
	APPLICATION

inherit
	ARGUMENTS

create
	make

feature {NONE} -- Initialization

	make
			-- Run application.
		local
			s: STRING_32
		do
			s := "The tiny tiger totally taunted the tall Till."
			print ("%NString to encode: " + s)
			print ("%NEncoded string: " + encode (s, 12))
			print ("%NDecoded string (after encoding and decoding): " + decode (encode (s, 12), 12))
		end

feature		-- Basic operations

	decode (to_be_decoded: STRING_32; offset: INTEGER): STRING_32
				-- Decode `to be decoded' according to `offset'.
		do
			Result := encode (to_be_decoded, 26 - offset)
		end

	encode (to_be_encoded: STRING_32; offset: INTEGER): STRING_32
				-- Encode `to be encoded' according to `offset'.
		local
			l_offset: INTEGER
			l_char_code: INTEGER
		do
			create Result.make_empty
			l_offset := (offset \\ 26) + 26
			across to_be_encoded as tbe loop
				if tbe.item.is_alpha then
					if tbe.item.is_upper then
						l_char_code := ('A').code + (tbe.item.code - ('A').code + l_offset) \\ 26
						Result.append_character (l_char_code.to_character_32)
					else
						l_char_code := ('a').code + (tbe.item.code - ('a').code + l_offset) \\ 26
						Result.append_character (l_char_code.to_character_32)
					end
				else
					Result.append_character (tbe.item)
				end
			end
		end
end


open number char monad io string

chars = "ABCDEFGHIJKLMOPQRSTUVWXYZ"

caesar _ _ [] = ""
caesar op key (x::xs) = check shifted ++ caesar op key xs
  where orig = indexOf (string.upper $ toString x) chars
        shifted = orig `op` key
        check val | orig == -1 = x
                  | val > 24 = trans $ val - 25
                  | val < 0 = trans $ 25 + val
                  | else = trans shifted
        trans idx = chars:idx

cypher = caesar (+)
decypher = caesar (-)

key = 2

do
  putStrLn "A string to encode:"
  str <- readStr
  putStr "Encoded string: "
  cstr <- return <| cypher key str
  put cstr
  putStrLn ""
  putStr "Decoded string: "
  put $ decypher key cstr


import system'routines;
import system'math;
import extensions;
import extensions'text;

const string Letters    = "abcdefghijklmnopqrstuvwxyz";
const string BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string TestText   = "Pack my box with five dozen liquor jugs.";
const int Key = 12;

class Encrypting : Enumerator
{
    int        theKey;
    Enumerator theEnumerator;

    constructor(int key, string text)
    {
        theKey := key;
        theEnumerator := text.enumerator();
    }

    bool next() => theEnumerator;

    reset() => theEnumerator;

    enumerable() => theEnumerator;

    get()
    {
        var ch := theEnumerator.get();

        var index := Letters.indexOf(0, ch);

        if (-1 < index)
        {
            ^ Letters[(theKey+index).mod:26]
        }
        else
        {
            index := BigLetters.indexOf(0, ch);
            if (-1 < index)
            {
                ^ BigLetters[(theKey+index).mod:26]
            }
            else
            {
                ^ ch
            }
        }
    }
}

extension encryptOp
{
    encrypt(key)
        = new Encrypting(key, self).summarize(new StringWriter());

    decrypt(key)
        = new Encrypting(26 - key, self).summarize(new StringWriter());
}

public program()
{
    console.printLine("Original text :",TestText);

    var encryptedText := TestText.encrypt:Key;

    console.printLine("Encrypted text:",encryptedText);

    var decryptedText := encryptedText.decrypt:Key;

    console.printLine("Decrypted text:",decryptedText);

    console.readChar()
}


defmodule Caesar_cipher do
  defp set_map(map, range, key) do
    org = Enum.map(range, &List.to_string [&1])
    {a, b} = Enum.split(org, key)
    Enum.zip(org, b ++ a) |> Enum.into(map)
  end

  def encode(text, key) do
    map = Map.new |> set_map(?a..?z, key) |> set_map(?A..?Z, key)
    String.graphemes(text) |> Enum.map_join(fn c -> Map.get(map, c, c) end)
  end
end

text = "The five boxing wizards jump quickly"
key = 3
IO.puts "Original:  #{text}"
IO.puts "Encrypted: #{enc = Caesar_cipher.encode(text, key)}"
IO.puts "Decrypted: #{Caesar_cipher.encode(enc, -key)}"


%% Ceasar cypher in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten

-module(ceasar).
-export([main/2]).

%% rot: rotate Char by Key places
rot(Char,Key) when (Char >= $A) and (Char =< $Z) or
                   (Char >= $a) and (Char =< $z) ->
  Offset = $A + Char band 32,
  N = Char - Offset,
  Offset + (N + Key) rem 26;
rot(Char, _Key) ->
  Char.

%% key: normalize key.
key(Key) when Key < 0 ->
  26 + Key rem 26;
key(Key) when Key > 25 ->
  Key rem 26;
key(Key) ->
  Key.

main(PlainText, Key) ->
  Encode = key(Key),
  Decode = key(-Key),

  io:format("Plaintext ----> ~s~n", [PlainText]),

  CypherText = lists:map(fun(Char) -> rot(Char, Encode) end, PlainText),
  io:format("Cyphertext ---> ~s~n", [CypherText]),

  PlainText = lists:map(fun(Char) -> rot(Char, Decode) end, CypherText).


PROGRAM CAESAR

!$INCLUDE="PC.LIB"

PROCEDURE CAESAR(TEXT$,KY%->CY$)
    LOCAL I%,C%
    FOR I%=1 TO LEN(TEXT$) DO
      C%=ASC(MID$(TEXT$,I%))
      IF (C% AND $1F)>=1 AND (C% AND $1F)<=26 THEN
        C%=(C% AND $E0) OR (((C% AND $1F)+KY%-1) MOD 26+1)
        CHANGE(TEXT$,I%,CHR$(C%)->TEXT$)
      END IF
    END FOR
    CY$=TEXT$
END PROCEDURE

BEGIN
    RANDOMIZE(TIMER)
    PLAINTEXT$="Pack my box with five dozen liquor jugs"
    PRINT(PLAINTEXT$)

    KY%=1+INT(25*RND(1))  ! generates random between 1 and 25
    CAESAR(PLAINTEXT$,KY%->CYPHERTEXT$)
    PRINT(CYPHERTEXT$)

    CAESAR(CYPHERTEXT$,26-KY%->DECYPHERED$)
    PRINT(DECYPHERED$)

END PROGRAM


--caesar cipher for Rosetta Code wiki
--User:Lnettnay

--usage eui caesar ->default text, key and encode flag
--usage eui caesar 'Text with spaces and punctuation!' 5 D
--If text has imbedded spaces must use apostophes instead of quotes so all punctuation works
--key = integer from 1 to 25, defaults to 13
--flag = E (Encode) or D (Decode), defaults to E
--no error checking is done on key or flag

include std/get.e
include std/types.e

sequence cmd = command_line()
sequence val
-- default text for encryption
sequence text = "The Quick Brown Fox Jumps Over The Lazy Dog."
atom key = 13 -- default to Rot-13
sequence flag = "E" -- default to Encrypt
atom offset
atom num_letters = 26 -- number of characters in alphabet

--get text
if length(cmd) >= 3 then
	text = cmd[3]
end if

--get key value
if length(cmd) >= 4 then
	val = value(cmd[4])
	key = val[2]
end if

--get Encrypt/Decrypt flag
if length(cmd) = 5 then
	flag = cmd[5]
	if compare(flag, "D") = 0 then
		key = 26 - key
	end if
end if

for i = 1 to length(text) do
	if t_alpha(text[i]) then
		if t_lower(text[i]) then
			offset = 'a'
		else
			offset = 'A'
		end if
		text[i] = remainder(text[i] - offset + key, num_letters) + offset
	end if
end for

printf(1,"%s\n",{text})


module caesar =
    open System

    let private cipher n s =
        let shift c =
            if Char.IsLetter c then
                let a = (if Char.IsLower c then 'a' else 'A') |> int
                (int c - a + n) % 26 + a |> char
            else c
        String.map shift s

    let encrypt n = cipher n
    let decrypt n = cipher (26 - n)


USING: io kernel locals math sequences unicode.categories ;
IN: rosetta-code.caesar-cipher

:: cipher ( n s -- s' )
    [| c |
        c Letter? [
            c letter? CHAR: a CHAR: A ? :> a
            c a - n + 26 mod a +
        ]
        [ c ] if
    ] :> shift
    s [ shift call ] map ;

: encrypt ( n s -- s' ) cipher ;
: decrypt ( n s -- s' ) [ 26 swap - ] dip cipher ;

11 "Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr." decrypt print
11 "The quick brown fox jumped over the lazy dog." encrypt print


class Main
{
  static Int shift (Int char, Int key)
  {
    newChar := char + key
    if (char >= 'a' && char <= 'z')
    {
      if (newChar - 'a' < 0)   { newChar += 26 }
      if (newChar - 'a' >= 26) { newChar -= 26 }
    }
    else if (char >= 'A' && char <= 'Z')
    {
      if (newChar - 'A' < 0)   { newChar += 26 }
      if (newChar - 'A' >= 26) { newChar -= 26 }
    }
    else // not alphabetic, so keep as is
    {
      newChar = char
    }
    return newChar
  }

  static Str shiftStr (Str msg, Int key)
  {
    res := StrBuf()
    msg.each { res.addChar (shift(it, key)) }
    return res.toStr
  }

  static Str encode (Str msg, Int key)
  {
    return shiftStr (msg, key)
  }

  static Str decode (Str msg, Int key)
  {
    return shiftStr (msg, -key)
  }

  static Void main (Str[] args)
  {
    if (args.size == 2)
    {
      msg := args[0]
      key := Int(args[1])

      echo ("$msg with key $key")
      echo ("Encode: ${encode(msg, key)}")
      echo ("Decode: ${decode(encode(msg, key), key)}")
    }
  }
}


lowers = ['a','z']
uppers = ['A','Z']
function void caesar_encode(message:ptr key:uint) {
  len = strlen$ message
  for uint [0u,len) with index {
    temp = deref_ubyte$ + message index
    if in temp lowers {
      temp = + temp key// shift lowercase letters
      if > temp 'z' {
        temp = - temp 26ub
      } ;
    } {
      if in temp uppers {
        temp = + temp key// shift uppercase letters
        if > temp 'Z' {
          temp = - temp 26ub
        } ;
      } ;//don't shift other characters
    }
    put_ubyte$ + message index temp
  }
}
function void caesar_decode(message:ptr key:uint) {
  caesar_encode$ message - 26u key
}

key = 1u
response = malloc$ 256u
puts$ "plaintext: "
getline$ response
caesar_encode$ response key
puts$ "cyphertext: "
puts$ response
putln$
caesar_decode$ response key
puts$ "decoded: "
puts$ response
free$ response
free$ lowers // ranges are objects and must be freed
free$ uppers

//this compiles with only 6 warnings!


: ceasar ( c n -- c )
  over 32 or [char] a -
  dup 0 26 within if
    over + 25 > if 26 - then +
  else 2drop then ;

: ceasar-string ( n str len -- )
  over + swap do i [email protected] over ceasar i c! loop drop ;

: ceasar-inverse ( n -- 'n ) 26 swap - 26 mod ;

2variable test
s" The five boxing wizards jump quickly!" test 2!

3 test [email protected] ceasar-string
test [email protected] cr type

3 ceasar-inverse test [email protected] ceasar-string
test [email protected] cr type


program Caesar_Cipher
  implicit none

  integer, parameter :: key = 3
  character(43) :: message = "The five boxing wizards jump quickly"

  write(*, "(2a)") "Original message  = ", message
  call encrypt(message)
  write(*, "(2a)") "Encrypted message = ", message
  call decrypt(message)
  write(*, "(2a)") "Decrypted message = ", message

contains

subroutine encrypt(text)
  character(*), intent(inout) :: text
  integer :: i

  do i = 1, len(text)
    select case(text(i:i))
      case ('A':'Z')
        text(i:i) = achar(modulo(iachar(text(i:i)) - 65 + key, 26) + 65)
      case ('a':'z')
        text(i:i) = achar(modulo(iachar(text(i:i)) - 97 + key, 26) + 97)
    end select
  end do
end subroutine

subroutine decrypt(text)
  character(*), intent(inout) :: text
  integer :: i

  do i = 1, len(text)
    select case(text(i:i))
      case ('A':'Z')
        text(i:i) = achar(modulo(iachar(text(i:i)) - 65 - key, 26) + 65)
      case ('a':'z')
        text(i:i) = achar(modulo(iachar(text(i:i)) - 97 - key, 26) + 97)
    end select
  end do
end subroutine

end program Caesar_Cipher


' FB 1.05.0 Win64

Sub Encrypt(s As String, key As Integer)
  Dim c As Integer
  For i As Integer = 0 To Len(s)
    Select Case As Const s[i]
      Case 65 To 90
        c = s[i] + key
        If c > 90 Then c -= 26
        s[i] = c
      Case 97 To 122
        c = s[i] + key
        If c > 122 Then c -= 26
        s[i] = c
    End Select
  Next
End Sub

Sub Decrypt(s As String, key As Integer)
  Dim c As Integer
  For i As Integer = 0 To Len(s)
    Select Case As Const s[i]
      Case 65 To 90
        c = s[i] - key
        If c < 65 Then c += 26
        s[i] = c
      Case 97 To 122
        c = s[i] - key
        If c < 97 Then c += 26
        s[i] = c
    End Select
  Next
End Sub

Dim As String s = "Bright vixens jump; dozy fowl quack."
Print "Plain text : "; s
Encrypt s, 8
Print "Encrypted  : "; s
Decrypt s, 8
Print "Decrypted  : "; s
Sleep


Public Sub Main()
Dim byKey As Byte = 3                                                                 'The key (Enter 26 to get the same output as input)
Dim byCount As Byte                                                                   'Counter
Dim sCeasar As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"        'Used to calculate the cipher
Dim sString As String = "The five boxing wizards jump quickly"                        'Phrase to encrypt
Dim sCoded, sTemp As String                                                           'Various strings

For byCount = 1 To Len(sString)                                                       'Count through each letter in the phrase
  If Mid(sString, byCount, 1) = " " Then                                              'If it's a space..
    sCoded &= " "                                                                     'Keep it a space
    Continue                                                                          'Jump to the next iteration of the loop
  Endif
  sTemp = Mid(sCeasar, InStr(sCeasar, Mid(UCase(sString), byCount, 1)) + byKey, 1)    'Get the new 'coded' letter
  If Asc(Mid(sString, byCount, 1)) > 96 Then sTemp = Chr(Asc(sTemp) + 32)             'If the original was lower case then make the new 'coded' letter lower case
  sCoded &= sTemp                                                                     'Add the result to the code string
Next

Print sString & gb.NewLine & sCoded                                                   'Print the result

End


CaesarCipher := function(s, n)
	local r, c, i, lower, upper;
	lower := "abcdefghijklmnopqrstuvwxyz";
	upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	r := "";
	for c in s do
		i := Position(lower, c);
		if i <> fail then
			Add(r, lower[RemInt(i + n - 1, 26) + 1]);
		else
			i := Position(upper, c);
			if i <> fail then
				Add(r, upper[RemInt(i + n - 1, 26) + 1]);
			else
				Add(r, c);
			fi;
		fi;
	od;
	return r;
end;

CaesarCipher("IBM", 25);
# "HAL"

CaesarCipher("Vgg cphvi wzdibn vmz wjmi amzz viy zlpvg di ydbidot viy mdbcon.", 5);
# "All human beings are born free and equal in dignity and rights."


'
' Caesar cypher
'
OPENW 1 ! Creates a window for handling input/output
CLEARW 1
INPUT "string to encrypt ";text$
INPUT "encryption key    ";key%
[email protected]$(UPPER$(text$),key%)
PRINT "Encrypted: ";encrypted$
PRINT "Decrypted: ";@decrypt$(encrypted$,key%)
'
PRINT "(Press any key to end program.)"
~INP(2)
CLOSEW 1
'
FUNCTION encrypt$(text$,key%)
  LOCAL result$,i%,c%
  result$=""
  FOR i%=1 TO LEN(text$)
    c%=ASC(MID$(text$,i%))
    IF c%<ASC("A") OR c%>ASC("Z") ! don't encrypt non A-Z
      result$=result$+CHR$(c%)
    ELSE
      c%=c%+key%
      IF c%>ASC("Z")
        c%=c%-26
      ENDIF
      result$=result$+CHR$(c%)
    ENDIF
  NEXT i%
  RETURN result$
ENDFUNC
'
FUNCTION decrypt$(text$,key%)
  RETURN @encrypt$(text$,26-key%)
ENDFUNC


package main

import (
    "fmt"
    "strings"
)

type ckey struct {
    enc, dec func(rune) rune
}

func newCaesar(k int) (*ckey, bool) {
    if k < 1 || k > 25 {
        return nil, false
    }
    rk := rune(k)
    return &ckey{
        enc: func(c rune) rune {
            if c >= 'a' && c <= 'z'-rk || c >= 'A' && c <= 'Z'-rk {
                return c + rk
            } else if c > 'z'-rk && c <= 'z' || c > 'Z'-rk && c <= 'Z' {
                return c + rk - 26
            }
            return c
        },
        dec: func(c rune) rune {
            if c >= 'a'+rk && c <= 'z' || c >= 'A'+rk && c <= 'Z' {
                return c - rk
            } else if c >= 'a' && c < 'a'+rk || c >= 'A' && c < 'A'+rk {
                return c - rk + 26
            }
            return c
        },
    }, true
}

func (ck ckey) encipher(pt string) string {
    return strings.Map(ck.enc, pt)
}

func (ck ckey) decipher(ct string) string {
    return strings.Map(ck.dec, ct)
}

func main() {
    pt := "The five boxing wizards jump quickly"
    fmt.Println("Plaintext:", pt)
    for _, key := range []int{0, 1, 7, 25, 26} {
        ck, ok := newCaesar(key)
        if !ok {
            fmt.Println("Key", key, "invalid")
            continue
        }
        ct := ck.encipher(pt)
        fmt.Println("Key", key)
        fmt.Println("  Enciphered:", ct)
        fmt.Println("  Deciphered:", ck.decipher(ct))
    }
}


def caesarEncode(cipherKey, text) {
    def builder = new StringBuilder()
    text.each { character ->
        int ch = character[0] as char
        switch(ch) {
            case 'a'..'z': ch = ((ch - 97 + cipherKey) % 26 + 97); break
            case 'A'..'Z': ch = ((ch - 65 + cipherKey) % 26 + 65); break
        }
        builder << (ch as char)
    }
    builder as String
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }


module Caesar (caesar, uncaesar) where

import Data.Char

caesar, uncaesar :: (Integral a) => a -> String -> String
caesar k = map f
    where f c = case generalCategory c of
              LowercaseLetter -> addChar 'a' k c
              UppercaseLetter -> addChar 'A' k c
              _               -> c
uncaesar k = caesar (-k)

addChar :: (Integral a) => Char -> a -> Char -> Char
addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26)
    where b' = fromIntegral $ ord b
          c' = fromIntegral $ ord c


|%
  ++  enc
    |=  [msg=tape [email protected]]
    ^-  tape
    (turn `(list @)`msg |=([email protected] (add (mod (add (sub n 'A') key) 26) 'A')))
  ++  dec
    |=  [msg=tape [email protected]]
    (enc msg (sub 26 key))
  --


procedure main()
ctext := caesar(ptext := map("The quick brown fox jumped over the lazy dog"))
dtext := caesar(ctext,,"decrypt")
write("Plain text  = ",image(ptext))
write("Encphered text = ",image(ctext))
write("Decphered text = ",image(dtext))
end

procedure caesar(text,k,mode)   #: mono-alphabetic shift cipher
/k := 3
k := (((k % *&lcase) + *&lcase) % *&lcase) + 1
case mode of {
  &null|"e"|"encrypt": return map(text,&lcase,(&lcase||&lcase)[k+:*&lcase])
  "d"|"decrypt"      : return map(text,(&lcase||&lcase)[k+:*&lcase],&lcase)
  }
end


100 PROGRAM "CaesarCi.bas"
110 STRING M$*254
120 INPUT PROMPT "String: ":M$
130 DO
140   INPUT PROMPT "Key (1-25): ":KEY
150 LOOP UNTIL KEY>0 AND KEY<26
160 PRINT "Original message:  ";M$
170 CALL ENCRYPT(M$,KEY)
180 PRINT "Encrypted message: ";M$
190 CALL DECRYPT(M$,KEY)
200 PRINT "Decrypted message: ";M$
210 DEF ENCRYPT(REF M$,KEY)
220   STRING T$*254
230   LET T$=""
240   FOR I=1 TO LEN(M$)
250     SELECT CASE M$(I)
260     CASE "A" TO "Z"
270       LET T$=T$&CHR$(65+MOD(ORD(M$(I))-65+KEY,26))
280     CASE "a" TO "z"
290       LET T$=T$&CHR$(97+MOD(ORD(M$(I))-97+KEY,26))
300     CASE ELSE
310       LET T$=T$&M$(I)
320     END SELECT
330   NEXT
340   LET M$=T$
350 END DEF
360 DEF DECRYPT(REF M$,KEY)
370   STRING T$*254
380   LET T$=""
390   FOR I=1 TO LEN(M$)
400     SELECT CASE M$(I)
410     CASE "A" TO "Z"
420       LET T$=T$&CHR$(65+MOD(ORD(M$(I))-39-KEY,26))
430     CASE "a" TO "z"
440       LET T$=T$&CHR$(97+MOD(ORD(M$(I))-71-KEY,26))
450     CASE ELSE
460       LET T$=T$&M$(I)
470     END SELECT
480   NEXT
490   LET M$=T$
500 END DEF


cndx=: [: , 65 97 +/ 26 | (i.26)&+
caesar=: (cndx 0)}&[email protected]:@[email protected][ {~ a.i.]


(def alphabet "abcdefghijklmnopqrstuvwxyz")

(defn rotate
  "shift bytes given x"
  [str x]
  (let [r (% x (length alphabet))
        b (string/bytes str)
        abyte (get (string/bytes "a") 0)
        zbyte (get (string/bytes "z") 0)]
    (var result @[])
    (for i 0 (length b)
      (let [ch (bor (get b i) 0x20)]  # convert uppercase to lowercase
        (when (and (<= abyte ch) (<= ch zbyte))
          (array/push result (get alphabet (% (+ (+ (+ (- zbyte abyte) 1) (- ch abyte)) r) (length alphabet)))))))
    (string/from-bytes ;result)))

(defn code
  "encodes and decodes str given argument type"
  [str rot type]
  (case type
    :encode (rotate str rot)
    :decode (rotate str (* rot -1))))

(defn main [& args]
  (let [cipher (code "The quick brown fox jumps over the lazy dog" 23 :encode)
        str (code cipher 23 :decode)]
    (print cipher)
    (print str)))


public class Cipher {
    public static void main(String[] args) {

        String str = "The quick brown fox Jumped over the lazy Dog";

        System.out.println( Cipher.encode( str, 12 ));
        System.out.println( Cipher.decode( Cipher.encode( str, 12), 12 ));
    }

    public static String decode(String enc, int offset) {
        return encode(enc, 26-offset);
    }

    public static String encode(String enc, int offset) {
        offset = offset % 26 + 26;
        StringBuilder encoded = new StringBuilder();
        for (char i : enc.toCharArray()) {
            if (Character.isLetter(i)) {
                if (Character.isUpperCase(i)) {
                    encoded.append((char) ('A' + (i - 'A' + offset) % 26 ));
                } else {
                    encoded.append((char) ('a' + (i - 'a' + offset) % 26 ));
                }
            } else {
                encoded.append(i);
            }
        }
        return encoded.toString();
    }
}


function caesar (text, shift) {
  return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/./g, function(a) {
    return String.fromCharCode(65+(a.charCodeAt(0)-65+shift)%26);
  });
}

// Tests
var text = 'veni, vidi, vici';
for (var i = 0; i<26; i++) {
  console.log(i+': '+caesar(text,i));
}


def encrypt(key):
  . as $s
  | explode as $xs
  | (key % 26) as $offset
  | if $offset == 0 then .
    else reduce range(0; length) as $i ( {chars: []};
           $xs[$i] as $c
           | .d = $c
           | if ($c >= 65 and $c <= 90) # 'A' to 'Z'
             then .d = $c + $offset
             | if (.d > 90) then .d += -26 else . end
             else if ($c >= 97 and $c <= 122) # 'a' to 'z'
                  then .d = $c + $offset
                  | if (.d > 122)
		    then .d += -26
		    else .
		    end
		  else .
		  end
             end
           | .chars[$i] = .d )
        | .chars | implode
    end ;

def decrypt(key): encrypt(26 - key);

"Bright vixens jump; dozy fowl quack."
| .,
  (encrypt(8)
   | ., decrypt(8) )


/* Caesar cipher, in Jsish */
"use strict";

function caesarCipher(input:string, key:number):string {
        return input.replace(/([a-z])/g,
            function(mat, p1, ofs, str) {
                return Util.fromCharCode((p1.charCodeAt(0) + key + 26 - 97) % 26 + 97);
            }).replace(/([A-Z])/g,
                function(mat, p1, ofs, str) {
                    return Util.fromCharCode((p1.charCodeAt(0) + key + 26 - 65) % 26 + 65);
                });
}

provide('caesarCipher', 1);

if (Interp.conf('unitTest')) {
    var str = 'The five boxing wizards jump quickly';
;    str;
;    'Enciphered:';
;    caesarCipher(str, 3);
;    'Enciphered then deciphered';
;    caesarCipher(caesarCipher(str, 3), -3);
}

/*
=!EXPECTSTART!=
str ==> The five boxing wizards jump quickly
'Enciphered:'
caesarCipher(str, 3) ==> Wkh ilyh eralqj zlcdugv mxps txlfnob
'Enciphered then deciphered'
caesarCipher(caesarCipher(str, 3), -3) ==> The five boxing wizards jump quickly
=!EXPECTEND!=
*/


# Caeser cipher
# Julia 1.5.4
# author: manuelcaeiro | https://github.com/manuelcaeiro

function csrcipher(text, key)
    ciphtext = ""
    for l in text
        numl = Int(l)
        ciphnuml = numl + key
        if numl in 65:90
            if ciphnuml > 90
                rotciphnuml = ciphnuml - 26
                ciphtext = ciphtext * Char(rotciphnuml)
            else
                ciphtext = ciphtext * Char(ciphnuml)
            end
        elseif numl in 97:122
            if ciphnuml > 122
                rotciphnuml = ciphnuml - 26
                ciphtext = ciphtext * Char(rotciphnuml)
            else
                ciphtext = ciphtext * Char(ciphnuml)
            end
        else
            ciphtext = ciphtext * Char(numl)
        end
    end
    return ciphtext
end

text = "Magic Encryption"; key = 13
csrcipher(text, key)


  s:"there is a tide in the affairs of men"
  caesar:{ :[" "=x; x; {x!_ci 97+!26}[y]@_ic[x]-97]}'
  caesar[s;1]
"uifsf jt b ujef jo uif bggbjst pg nfo"


// version 1.0.5-2

object Caesar {
    fun encrypt(s: String, key: Int): String {
        val offset = key % 26
        if (offset == 0) return s
        var d: Char
        val chars = CharArray(s.length)
        for ((index, c) in s.withIndex()) {
            if (c in 'A'..'Z') {
                d = c + offset
                if (d > 'Z') d -= 26
            }
            else if (c in 'a'..'z') {
                d = c + offset
                if (d > 'z') d -= 26
            }
            else
                d = c
            chars[index] = d
        }
        return chars.joinToString("")
    }

    fun decrypt(s: String, key: Int): String {
        return encrypt(s, 26 - key)
    }
}

fun main(args: Array<String>) {
    val encoded = Caesar.encrypt("Bright vixens jump; dozy fowl quack.", 8)
    println(encoded)
    val decoded = Caesar.decrypt(encoded, 8)
    println(decoded)
}


{def caesar

 {def caesar.alphabet {A.split ABCDEFGHIJKLMNOPQRSTUVWXYZ}}

 {def caesar.delta
  {lambda {:s :i :a}
   {A.get {% {+ {A.in? {A.get :i :a} {caesar.alphabet}} 26 :s} 26}
          {caesar.alphabet}}}}

{def caesar.loop
  {lambda {:s :a :b :n :i}
   {if {> :i :n}
    then :b
    else {caesar.r :s
                   :a
                   {A.set! :i {caesar.delta :s :i :a} :b}
                   :n
                   {+ :i 1}} }}}

 {lambda {:shift :txt}
  {let { {:s :shift}
         {:t {S.replace [^A-Z] by in :txt}} }
    {A.join {caesar.loop :s
                         {A.split :t}
                         {A.new}
                         {- {W.length :t} 1}
                         0 }}}}}
-> caesar

{def text VENI, VIDI, VICI}
-> text
{S.map {lambda {:i} {br}:i: {caesar :i {text}}}
       {S.serie 0 26}}
->

0: VENIVIDIVICI
1: WFOJWJEJWJDJ
2: XGPKXKFKXKEK
3: YHQLYLGLYLFL
...
23: SBKFSFAFSFZF
24: TCLGTGBGTGAG
25: UDMHUHCHUHBH
26: VENIVIDIVICI

As a shorter alternative:

{def CAESAR
 {def CAESAR.rot
  {lambda {:shift :txt :alpha :i}
   {A.get {% {+ {A.in? {A.get :i :txt} :alpha} 26 :shift} 26}
          :alpha}}}
 {def CAESAR.loop
  {lambda {:shift :txt :alpha}
   {S.map {CAESAR.rot :shift :txt :alpha}
          {S.serie 0 {- {A.length :txt} 1}}} }}
 {lambda {:shift :txt}
  {S.replace \s by in
   {CAESAR.loop :shift
                {A.split {S.replace \s by in :txt}}
                {A.split ABCDEFGHIJKLMNOPQRSTUVWXYZ}} }}}
-> CAESAR

{CAESAR 1 VENI VIDI VICI}
-> WFOJWJEJWJDJ
{CAESAR 25 WFOJWJEJWJDJ}
-> VENIVIDIVICI


val .rot = f(.s, .key) {
    cp2s map(f(.c) rotate(rotate(.c, .key, 'a'..'z'), .key, 'A'..'Z'), s2cp .s)
}

val .s = "A quick brown fox jumped over something."
val .key = 3

writeln " original: ", .s
writeln "encrypted: ", .rot(.s, .key)
writeln "decrypted: ", .rot(.rot(.s, .key), -.key)


key = 7

Print "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

'Encrypt the text
Print CaesarCypher$("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", key)

'Decrypt the text by changing the key to (26 - key)
Print CaesarCypher$(CaesarCypher$("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", key), (26 - key))

Function CaesarCypher$(string$, key)
    If (key < 0) Or (key > 25) Then _
    CaesarCypher$ = "Key is Ouside of Bounds" : Exit Function
    For i = 1 To Len(string$)
        rotate = Asc(Mid$(string$, i, 1))
        rotate = (rotate + key)
        If Asc(Mid$(string$, i, 1)) > Asc("Z") Then
            If rotate > Asc("z") Then rotate = (Asc("a") + (rotate - Asc("z")) - 1)
        Else
            If rotate > Asc("Z") Then rotate = (Asc("A") + (rotate - Asc("Z")) - 1)
        End If
        CaesarCypher$ = (CaesarCypher$ + Chr$(rotate))
    Next i
End Function


function caesarCipher rot phrase
    local rotPhrase, lowerLetters, upperLetters
    put "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" into lowerLetters
    put "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" into upperLetters
    repeat for each char letter in phrase
        get charTonum(letter)
        if it >= 65 and it <= 90 then
            put char ((it + rot) - 64) of upperLetters after rotPhrase
        else if it >= 97 and it <= 122 then
            put char ((it + rot) - 96) of lowerLetters after rotPhrase
        else
            put letter after rotPhrase
        end if
    end repeat
    return rotPhrase
end caesarCipher


; some useful constants
make "lower_a ascii "a
make "lower_z ascii "z
make "upper_a ascii "A
make "upper_z ascii "Z

; encipher a single character
to encipher_char :char :key
 local "code make "code ascii :char
 local "base make "base 0
 ifelse [and (:code >= :lower_a) (:code <= :lower_z)] [make "base :lower_a] [
     if [and (:code >= :upper_a) (:code <= :upper_z)] [make "base :upper_a] ]
 ifelse [:base > 0] [
   output char (:base + (modulo ( :code - :base + :key ) 26 ))
 ] [
   output :char
 ]
end

; encipher a whole string
to caesar_cipher :string :key
  output map [encipher_char ? :key] :string
end

; Demo
make "plaintext "|The five boxing wizards jump quickly|
make "key 3
make "ciphertext caesar_cipher :plaintext :key
make "recovered  caesar_cipher :ciphertext -:key

print sentence "| Original:| :plaintext
print sentence "|Encrypted:| :ciphertext
print sentence "|Recovered:| :recovered
bye


local function encrypt(text, key)
	return text:gsub("%a", function(t)
			local base = (t:lower() == t and string.byte('a') or string.byte('A'))

			local r = t:byte() - base
			r = r + key
			r = r%26 -- works correctly even if r is negative
			r = r + base
			return string.char(r)
		end)
end

local function decrypt(text, key)
	return encrypt(text, -key)
end

caesar = {
	encrypt = encrypt,
	decrypt = decrypt,
}

-- test
do
	local text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
	local encrypted = caesar.encrypt(text, 7)
	local decrypted = caesar.decrypt(encrypted, 7)
	print("Original text:  ", text)
	print("Encrypted text: ", encrypted)
	print("Decrypted text: ", decrypted)
end


a$="THIS IS MY TEXT TO ENCODE WITH CAESAR CIPHER"
Function Cipher$(a$, N) {
      If Len(a$)=0 Then Exit
      a$=Ucase$(a$)
      N=N mod 25 +1
      \\ Integer in Mem is unsigned number
      Buffer Mem as Integer*Len(a$)
      Return Mem, 0:=a$
      For i=0 to Len(a$)-1 {
            If Eval(mem, i)>=65 and Eval(mem, i)<=90 then Return Mem, i:=(Eval(mem, i)-65+N) mod 26+65
       }
       =Eval$(Mem)
}
B$=Cipher$(a$, 12)
Print B$
Print Cipher$(B$,12)


> StringTools:-Encode( "The five boxing wizards jump quickly", encoding = alpharot[3] );
                       "Wkh ilyh eralqj zlcdugv mxps txlfnob"

> StringTools:-Encode( %, encoding = alpharot[ 23 ] );
                       "The five boxing wizards jump quickly"


   function s = cipherCaesar(s, key)
          s = char( mod(s - 'A' + key, 25 ) + 'A');
   end;
   function s = decipherCaesar(s, key)
          s = char( mod(s - 'A' - key, 25 ) + 'A');
   end;


TextWindow.Write("Enter a 1-25 number key (-ve number to decode): ")
key = TextWindow.ReadNumber()
TextWindow.Write("Enter message: ")
message = text.ConvertToUpperCase(TextWindow.Read())
caeser = ""
For n = 1 To Text.GetLength(message)
  letter = Text.GetSubText(message,n,1)
  code = Text.GetCharacterCode(letter)
  If code = 32 Then
    newCode = 32
  Else
    newCode = code + key
    If newCode > 90 Then
      newCode = newCode - 26
    ElseIf newCode < 65 then
      newCode = newCode + 26
    EndIf
  EndIf
  codeLetter = Text.GetCharacter(newCode)
  caeser = Text.Append(caeser,codeLetter)
EndFor
TextWindow.WriteLine(message)
TextWindow.WriteLine(caeser)


caesar = function(s, key)
    chars = s.values
    for i in chars.indexes
        c = chars[i]
        if c >= "a" and c <= "z" then chars[i] = char(97 + (code(c)-97+key)%26)
        if c >= "A" and c <= "Z" then chars[i] = char(65 + (code(c)-65+key)%26)
    end for
    return chars.join("")
end function

print caesar("Hello world!", 7)
print caesar("Olssv dvysk!", 26-7)


fun readfile () = readfile []
           | x = let val ln = readln ()
                 in if eof ln then
                      rev x
                    else
                      readfile ` ln :: x
                 end

local
	val lower_a = ord #"a";
	val lower_z = ord #"z";
	val upper_a = ord #"A";
	val upper_z = ord #"Z";

	fun which
			(c_upper c) = (upper_a, upper_z)
		|	_	    = (lower_a, lower_z)
		;

	fun scale
			(c, az) where (c > #1 az) = scale( (#0 az + (c - #1 az - 1)), az)
		|	(c, az) 		  = c

in
	fun encipher
			([], offset, t)                             = implode ` rev t
		|	(x :: xs, offset, t) where (c_alphabetic x) = encipher (xs, offset, (chr ` scale (ord x + offset, which x)) :: t)
		|	(x :: xs, offset, t)                        = encipher (xs, offset, x :: t)
		|	(s, offset) 				    = if (offset < 0) then
									encipher (explode s, 26 + (offset rem 26), [])
								      else
									encipher (explode s, offset rem 26, [])
end

fun default
		(false, y) = y
	|	(x,     _) = x

;
map println ` map (fn s = encipher (s,ston ` default (argv 0, "1"))) ` readfile ();


MODULE CaesarCipher;
FROM Conversions IMPORT IntToStr;
FROM Terminal IMPORT WriteString, WriteLn, ReadChar;

TYPE String = ARRAY[0..64] OF CHAR;

PROCEDURE Encrypt(p : String; key : CARDINAL) : String;
VAR e : String;
VAR i,t : CARDINAL;
VAR c : CHAR;
BEGIN
    FOR i:=0 TO HIGH(p) DO
        IF p[i]=0C THEN BREAK; END;

        t := ORD(p[i]);
        IF (p[i]>='A') AND (p[i]<='Z') THEN
            t := t + key;
            IF t>ORD('Z') THEN
                t := t - 26;
            END;
        ELSIF (p[i]>='a') AND (p[i]<='z') THEN
            t := t + key;
            IF t>ORD('z') THEN
                t := t - 26;
            END;
        END;
        e[i] := CHR(t);
    END;
    RETURN e;
END Encrypt;

PROCEDURE Decrypt(p : String; key : CARDINAL) : String;
VAR e : String;
VAR i,t : CARDINAL;
VAR c : CHAR;
BEGIN
    FOR i:=0 TO HIGH(p) DO
        IF p[i]=0C THEN BREAK; END;

        t := ORD(p[i]);
        IF (p[i]>='A') AND (p[i]<='Z') THEN
            t := t - key;
            IF t<ORD('A') THEN
                t := t + 26;
            END;
        ELSIF (p[i]>='a') AND (p[i]<='z') THEN
            t := t - key;
            IF t<ORD('a') THEN
                t := t + 26;
            END;
        END;
        e[i] := CHR(t);
    END;
    RETURN e;
END Decrypt;

VAR txt,enc : String;
VAR key : CARDINAL;
BEGIN
    txt := "The five boxing wizards jump quickly";
    key := 3;

    WriteString("Original:  ");
    WriteString(txt);
    WriteLn;

    enc := Encrypt(txt, key);
    WriteString("Encrypted: ");
    WriteString(enc);
    WriteLn;

    WriteString("Decrypted: ");
    WriteString(Decrypt(enc, key));
    WriteLn;

    ReadChar;
END CaesarCipher.


MODULE Caesar EXPORTS Main;

IMPORT IO, IntSeq, Text;

EXCEPTION BadCharacter;
(* Used whenever message contains a non-alphabetic character. *)

PROCEDURE Encode(READONLY message: TEXT; numbers: IntSeq.T) RAISES { BadCharacter } =
(*
Converts upper or lower case letter to 0..25.
Raises a "BadCharacter" exception for non-alphabetic characters.
*)
VAR
  c: CHAR;
  v: INTEGER;
BEGIN
  FOR i := 0 TO Text.Length(message) - 1 DO
    c := Text.GetChar(message, i);
    CASE c OF
    | 'A'..'Z' => v := ORD(c) - ORD('A');
    | 'a'..'z' => v := ORD(c) - ORD('a');
    ELSE
      RAISE BadCharacter;
    END;
    numbers.addhi(v);
  END;
END Encode;

PROCEDURE Decode(READONLY numbers: IntSeq.T; VAR message: TEXT) =
(* converts numbers in 0..26 to lower case characters *)
BEGIN
  FOR i := 0 TO numbers.size() - 1 DO
    message := message & Text.FromChar(VAL(numbers.get(i) + ORD('a'), CHAR));
  END;
END Decode;

PROCEDURE Crypt(numbers: IntSeq.T; key: INTEGER) =
(*
In the Caesar cipher, encryption and decryption are really the same;
one adds the key, the other subtracts it. We can view this as adding a positive
or nevative integer; the common task is adding an integer. We call this "Crypt".
*)
BEGIN
  FOR i := 0 TO numbers.size() - 1 DO
    numbers.put(i, (numbers.get(i) + key) MOD 26);
  END;
END Crypt;

PROCEDURE Encrypt(numbers: IntSeq.T; key := 4) =
(*
Encrypts a message of numbers using the designated key.
The result is also stored in "numbers".
*)
BEGIN
  Crypt(numbers, key);
END Encrypt;

PROCEDURE Decrypt(numbers: IntSeq.T; key := 4) =
(*
Decrypts a message of numbers using the designated key.
The result is also stored in "numbers".
*)
BEGIN
  Crypt(numbers, -key);
END Decrypt;

VAR

  message := "";
  buffer := NEW(IntSeq.T).init(22); (* sequence of 22 int's *)

BEGIN
  TRY
    Encode("WhenCaesarSetOffToGaul", buffer);
  EXCEPT BadCharacter =>
    (*
      This should never occur.
      Try adding spaces to the above to see what happens.
    *)
    IO.Put("Encountered a bad character in the input; completing partial task\n");
  END;
  Encrypt(buffer);
  Decrypt(buffer);
  Decode(buffer, message);
  IO.Put(message); IO.PutChar('\n');
END Caesar.


def caesar_encode(plaintext, shift)
	uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	lowercase = "abcdefghijklmnopqrstuvwxyz"

	cipher = ""
	for char in plaintext
		if char in uppercase
			cipher += uppercase[uppercase[char] - (26 - shift)]
		else if char in lowercase
			cipher += lowercase[lowercase[char] - (26 - shift)]
		else
			cipher += char
		end
	end

	return cipher
end

def caesar_decode(cipher, shift)
	uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	lowercase = "abcdefghijklmnopqrstuvwxyz"

	plaintext = ""
	for char in cipher
		if char in uppercase
			plaintext += uppercase[uppercase[char] - shift]
		else if char in lowercase
			plaintext += lowercase[lowercase[char] - shift]
		else
			plaintext += char
		end
	end

	return plaintext
end


/* NetRexx */

options replace format comments java crossref savelog symbols nobinary

messages = [ -
  'The five boxing wizards jump quickly', -
  'Attack at dawn!', -
  'HI']
keys = [1, 2, 20, 25, 13]

loop m_ = 0 to messages.length - 1
  in = messages[m_]
  loop k_ = 0 to keys.length - 1
    say 'Caesar cipher, key:' keys[k_].right(3)
    ec = caesar_encipher(in, keys[k_])
    dc = caesar_decipher(ec, keys[k_])
    say in
    say ec
    say dc
    say
    end k_
  say 'Rot-13:'
  ec = rot13(in)
  dc = rot13(ec)
  say in
  say ec
  say dc
  say
  end m_

return

method rot13(input) public static signals IllegalArgumentException

  return caesar(input, 13, isFalse)

method caesar(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException

  if idx < 1 | idx > 25 then signal IllegalArgumentException()

  --      12345678901234567890123456
  itab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  shift = itab.length - idx
  parse itab tl +(shift) tr
  otab = tr || tl

  if caps then input = input.upper

  cipher = input.translate(itab || itab.lower, otab || otab.lower)

  return cipher

method caesar_encipher(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException

  return caesar(input, idx, caps)

method caesar_decipher(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException

  return caesar(input, int(26) - idx, isFalse)

method caesar_encipher(input = Rexx, idx = int) public static signals IllegalArgumentException

  return caesar(input, idx, isFalse)

method caesar_decipher(input = Rexx, idx = int) public static signals IllegalArgumentException

  return caesar(input, int(26) - idx, isFalse)

method caesar_encipher(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException

  return caesar(input, idx, opt)

method caesar_decipher(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException

  return caesar(input, int(26) - idx, opt)

method caesar(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException

  if opt.upper.abbrev('U') >= 1 then caps = isTrue
  else                               caps = isFalse

  return caesar(input, idx, caps)

method caesar(input = Rexx, idx = int) public static signals IllegalArgumentException

  return caesar(input, idx, isFalse)

method isTrue public static returns boolean
  return (1 == 1)

method isFalse public static returns boolean
  return \isTrue


import strutils

proc caesar(s: string, k: int, decode = false): string =
  var k = if decode: 26 - k else: k
  result = ""
  for i in toUpper(s):
    if ord(i) >= 65 and ord(i) <= 90:
      result.add(chr((ord(i) - 65 + k) mod 26 + 65))

let msg = "The quick brown fox jumped over the lazy dogs"
echo msg
let enc = caesar(msg, 11)
echo enc
echo caesar(enc, 11, decode = true)


MODULE Caesar;
IMPORT
  Out;
CONST
  encode* = 1;
  decode* = -1;

VAR
  text,cipher: POINTER TO ARRAY OF CHAR;

  PROCEDURE Cipher*(txt: ARRAY OF CHAR; key: INTEGER; op: INTEGER; VAR cipher: ARRAY OF CHAR);
  VAR
    i: LONGINT;
  BEGIN
    i := 0;
    WHILE i < LEN(txt) - 1 DO
      IF (txt[i] >= 'A') & (txt[i] <= 'Z') THEN
        cipher[i] := CHR(ORD('A') + ((ORD(txt[i]) - ORD('A') + (key * op))) MOD 26)
      ELSIF (txt[i] >= 'a') & (txt[i] <= 'z') THEN
        cipher[i] := CHR(ORD('a') + ((ORD(txt[i]) - ORD('a') + (key * op))) MOD 26)
      ELSE
        cipher[i] := txt[i]
      END;
      INC(i)
    END;
    cipher[i] := 0X
  END Cipher;

BEGIN
  NEW(text,3);NEW(cipher,3);
  COPY("HI",text^);
  Out.String(text^);Out.String(" =e=> ");
  Cipher(text^,2,encode,cipher^);
  Out.String(cipher^);

  COPY(cipher^,text^);
  Cipher(text^,2,decode,cipher^);
  Out.String(" =d=> ");Out.String(cipher^);Out.Ln;

  COPY("ZA",text^);
  Out.String(text^);Out.String(" =e=> ");
  Cipher(text^,2,encode,cipher^);
  Out.String(cipher^);

  COPY(cipher^,text^);
  Cipher(text^,2,decode,cipher^);
  Out.String(" =d=> ");Out.String(cipher^);Out.Ln;

  NEW(text,37);NEW(cipher,37);
  COPY("The five boxing wizards jump quickly",text^);
  Out.String(text^);Out.String(" =e=> ");
  Cipher(text^,3,encode,cipher^);
  Out.String(cipher^);

  COPY(cipher^,text^);
  Cipher(text^,3,decode,cipher^);
  Out.String(" =d=> ");Out.String(cipher^);Out.Ln;

END Caesar.


class Caesar {
  function : native : Encode(enc : String, offset : Int) ~ String {
    offset := offset % 26 + 26;
    encoded := "";
    enc := enc->ToLower();
    each(i : enc) {
      c := enc->Get(i);
      if(c->IsChar()) {
        j := (c - 'a' + offset) % 26;
        encoded->Append(j + 'a');
      }
      else {
        encoded->Append(c);
      };
    };

    return encoded;
  }

  function : Decode(enc : String, offset : Int) ~ String {
    return Encode(enc, offset * -1);
  }

  function : Main(args : String[]) ~ Nil {
    enc := Encode("The quick brown fox Jumped over the lazy Dog", 12);
    enc->PrintLine();
    Decode(enc, 12)->PrintLine();
  }
}


let islower c =
  c >= 'a' && c <= 'z'

let isupper c =
  c >= 'A' && c <= 'Z'

let rot x str =
  let upchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  and lowchars = "abcdefghijklmnopqrstuvwxyz" in
  let rec decal x =
    if x < 0 then decal (x + 26) else x
  in
  let x = (decal x) mod 26 in
  let decal_up = x - (int_of_char 'A')
  and decal_low = x - (int_of_char 'a') in
  String.map (fun c ->
    if islower c then
      let j = ((int_of_char c) + decal_low) mod 26 in
      lowchars.[j]
    else if isupper c then
      let j = ((int_of_char c) + decal_up) mod 26 in
      upchars.[j]
    else
      c
  ) str


: ceasar(c, key)
   c dup isLetter ifFalse: [ return ]
   isUpper ifTrue: [ 'A' ] else: [ 'a' ] c key + over - 26 mod + ;

: cipherE(s, key)  s map(#[ key ceasar ]) charsAsString ;
: cipherD(s, key)  cipherE(s, 26 key - ) ;


main: func (args: String[]) {
        shift := args[1] toInt()
        if (args length != 3) {
                "Usage: #{args[0]} [number] [sentence]" println()
                "Incorrect number of arguments." println()
        } else if (!shift && args[1] != "0"){
                "Usage: #{args[0]} [number] [sentence]" println()
                "Number is not a valid number." println()
        } else {
                str := ""
                for (c in args[2]) {
                        if (c alpha?()) {
                                c = (c lower?() ? 'a' : 'A') + (26 + c toLower() - 'a' + shift) % 26
                        }
                        str += c
                }
                str println()
        }
}


Program CaesarCipher(output);

procedure encrypt(var message: string; key: integer);
  var
    i: integer;
  begin
    for i := 1 to length(message) do
      case message[i] of
        'A'..'Z': message[i] := chr(ord('A') + (ord(message[i]) - ord('A') + key) mod 26);
        'a'..'z': message[i] := chr(ord('a') + (ord(message[i]) - ord('a') + key) mod 26);
      end;
  end;

procedure decrypt(var message: string; key: integer);
  var
    i: integer;
  begin
    for i := 1 to length(message) do
      case message[i] of
       'A'..'Z': message[i] := chr(ord('A') + (ord(message[i]) - ord('A') - key + 26) mod 26);
       'a'..'z': message[i] := chr(ord('a') + (ord(message[i]) - ord('a') - key + 26) mod 26);
      end;
  end;

var
  key: integer;
  message: string;

begin
  key := 3;
  message := 'The five boxing wizards jump quickly';
  writeln ('Original message: ', message);
  encrypt(message, key);
  writeln ('Encrypted message: ', message);
  decrypt(message, key);
  writeln ('Decrypted message: ', message);
  readln;
end.


sub caesar {
        my ($message, $key, $decode) = @_;
        $key = 26 - $key if $decode;
        $message =~ s/([A-Z])/chr(((ord(uc $1) - 65 + $key) % 26) + 65)/geir;
}

my $msg = 'THE FIVE BOXING WIZARDS JUMP QUICKLY';
my $enc = caesar($msg, 10);
my $dec = caesar($enc, 10, 'decode');

print "msg: $msg\nenc: $enc\ndec: $dec\n";


with javascript_semantics
sequence alpha_b = repeat(0,255)
         alpha_b['A'..'Z'] = 'A'
         alpha_b['a'..'z'] = 'a'

function caesar(string s, integer key)
integer ch, base
    for i=1 to length(s) do
        ch = s[i]
        base = alpha_b[ch]
        if base then
            s[i] = base+remainder(ch-base+key,26)
        end if
    end for
    return s
end function
string s = "One fine day in the middle of the night, two dead men got up to fight. \n"&
           "Back to back they faced each other, drew their swords and shot each other. %^&*()[",
       e = caesar(s,5),
       r = caesar(e,26-5)  ?e ?r


<?php
function caesarEncode( $message, $key ){
    $plaintext = strtolower( $message );
    $ciphertext = "";
    $ascii_a = ord( 'a' );
    $ascii_z = ord( 'z' );
    while( strlen( $plaintext ) ){
        $char = ord( $plaintext );
        if( $char >= $ascii_a && $char <= $ascii_z ){
            $char = ( ( $key + $char - $ascii_a ) % 26 ) + $ascii_a;
        }
        $plaintext = substr( $plaintext, 1 );
        $ciphertext .= chr( $char );
    }
    return $ciphertext;
}

echo caesarEncode( "The quick brown fox Jumped over the lazy Dog", 12 ), "\n";
?>


main =>
  S = "All human beings are born free and equal in dignity and rights.",
  println(S),
  println(caesar(S,5)),
  println(caesar(caesar(S,5),-5)),
  nl.

caesar(String, N) = Cipher =>
  Lower = [chr(I): I in 97..122],
  Upper = [chr(I): I in 65..90],
  M = create_map(Lower, Upper, N),
  % If a char is not in a..zA..z then show it as it is.
  Cipher := [M.get(C,C) : C in String].

create_map(Lower,Upper, N) = M =>
  M = new_map(),
  Len = Lower.length,
  foreach(I in 1..Len)
    II = (N+I) mod Len,
    if II == 0 then II := Len end, % Adjust for 1 based
    M.put(Upper[I],Upper[II]),
    M.put(Lower[I],Lower[II])
  end.


(setq *Letters (apply circ (mapcar char (range 65 90))))

(de caesar (Str Key)
   (pack
      (mapcar '((C) (cadr (nth (member C *Letters) Key)))
         (chop (uppc Str)) ) ) )


object c = Crypto.Substitution()->set_rot_key(2);
string msg     = "The quick brown fox jumped over the lazy dogs";
string msg_s2  = c->encrypt(msg);
c->set_rot_key(11);
string msg_s11 = c->encrypt(msg);
string decoded = c->decrypt(msg_s11);

write("%s\n%s\n%s\n%s\n", msg, msg_s2, msg_s11, decoded);


caesar: procedure options (main);
   declare cypher_string character (52) static initial
      ((2)'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
   declare (text, encyphered_text) character (100) varying,
      offset fixed binary;

   get edit (text) (L); /* Read in one line of text */
   get list (offset);
   if offset < 1 | offset > 25 then signal error;
   put skip list ('Plain text=', text);

   encyphered_text = translate(text, substr(cypher_string, offset+1, 26),
      'ABCDEFGHIJKLMNOPQRSTUVWXYZ' );
   put skip list ('Encyphered text=', encyphered_text);

   text = translate(encyphered_text, substr(cypher_string, 27-offset, 26),
      'ABCDEFGHIJKLMNOPQRSTUVWXYZ' );
   put skip list ('Decyphered text=', text);

end caesar;


# Author: M. McNabb
function Get-CaesarCipher
{
Param
(
[Parameter(
Mandatory=$true,ValueFromPipeline=$true)]
[string]
$Text,

[ValidateRange(1,25)]
[int]
$Key = 1,

[switch]
$Decode
)

begin
{
    $LowerAlpha = [char]'a'..[char]'z'
    $UpperAlpha = [char]'A'..[char]'Z'
}

process
{
    $Chars = $Text.ToCharArray()

    function encode
    {
        param
        (
        $Char,
        $Alpha = [char]'a'..[char]'z'
        )
        $Index = $Alpha.IndexOf([int]$Char)
        $NewIndex = ($Index + $Key) - $Alpha.Length
        $Alpha[$NewIndex]
    }

    function decode
    {
        param
        (
        $Char,
        $Alpha = [char]'a'..[char]'z'
        )
        $Index = $Alpha.IndexOf([int]$Char)
        $int = $Index - $Key
        if ($int -lt 0) {$NewIndex = $int + $Alpha.Length}
        else {$NewIndex = $int}
        $Alpha[$NewIndex]
    }

    foreach ($Char in $Chars)
    {
        if ([int]$Char -in $LowerAlpha)
        {
            if ($Decode) {$Char = decode $Char}
            else {$Char = encode $Char}
        }
        elseif ([int]$Char -in $UpperAlpha)
        {
            if ($Decode) {$Char = decode $Char $UpperAlpha}
            else {$Char = encode $Char $UpperAlpha}
        }

        $Char = [char]$Char
        [string]$OutText += $Char
    }

    $OutText
    $OutText = $null
}
}


:- use_module(library(clpfd)).

caesar :-
	L1 = "The five boxing wizards jump quickly",
	writef("Original : %s\n", [L1]),

	% encryption of the sentence
	encoding(3, L1, L2) ,
	writef("Encoding : %s\n", [L2]),

	% deciphering on the encoded sentence
	encoding(3, L3, L2),
	writef("Decoding : %s\n", [L3]).

% encoding/decoding of a sentence
encoding(Key, L1, L2) :-
	maplist(caesar_cipher(Key), L1, L2).

caesar_cipher(_, 32, 32) :- !.

caesar_cipher(Key, V1, V2) :-
	V #= Key + V1,

	% we verify that we are in the limits of A-Z and a-z.
	((V1 #=< 0'Z #/\ V #> 0'Z) #\/ (V1 #=< 0'z #/\ V #> 0'z)
	#\/
	(V1 #< 0'A #/\ V2 #>= 0'A)#\/ (V1 #< 0'a #/\ V2 #>= 0'a)) #==> A,

	% if we are not in these limits A is 1, otherwise 0.
	V2 #= V - A * 26,

	% compute values of V1 and V2
	label([A, V1, V2]).


Procedure.s CC_encrypt(plainText.s, key, reverse = 0)
  ;if reverse <> 0 then reverse the encryption (decrypt)
  If reverse: reverse = 26: key = 26 - key: EndIf

  Static alphabet$ = "ABCEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"

  Protected result.s, i, length = Len(plainText), letter.s, legal
  If key < 1 Or key > 25: ProcedureReturn: EndIf  ;keep key in range

  For i = 1 To length
    letter = Mid(plainText, i, 1)
    legal = FindString(alphabet$, letter, 1 + reverse)
    If legal
      result + Mid(alphabet$, legal + key, 1)
    Else
      result + letter
    EndIf
  Next
  ProcedureReturn result
EndProcedure

Procedure.s CC_decrypt(cypherText.s, key)
  ProcedureReturn CC_encrypt(cypherText, key, 1)
EndProcedure

If OpenConsole()
  Define key, plainText.s, encryptedText.s, decryptedText.s

  key = Random(24) + 1 ;get a random key in the range 1 -> 25

  plainText = "The quick brown fox jumped over the lazy dogs.": PrintN(RSet("Plain text = ", 17) + #DQUOTE$ + plainText + #DQUOTE$)
  encryptedText = CC_encrypt(plainText, key): PrintN(RSet("Encrypted text = ", 17) + #DQUOTE$ + encryptedText + #DQUOTE$)
  decryptedText = CC_decrypt(encryptedText, key): PrintN(RSet("Decrypted text = ", 17) + #DQUOTE$ + decryptedText + #DQUOTE$)

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf


def caesar(s, k, decode = False):
	if decode: k = 26 - k
	return "".join([chr((ord(i) - 65 + k) % 26 + 65)
				for i in s.upper()
				if ord(i) >= 65 and ord(i) <= 90 ])

msg = "The quick brown fox jumped over the lazy dogs"
print msg
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True)


LET dec$ = ""
LET tipo$ = "cleartext "

PRINT "If decrypting enter 'd' -- else press enter ";
INPUT dec$
PRINT "Enter offset ";
INPUT llave

IF dec$ = "d" THEN
    LET llave = 26 - llave
    LET tipo$ = "ciphertext "
END IF

PRINT "Enter "; tipo$;
INPUT cadena$

LET cadena$ = UCASE$(cadena$)
LET longitud = LEN(cadena$)

FOR i = 1 TO longitud
    LET iTemp =  ASC(MID$(cadena$,i,1))      'QBasic
    'LET itemp = ORD((cadena$)[i:i+1-1][1:1]) 'True BASIC

    IF iTemp > 64 AND iTemp < 91 THEN
        LET iTemp = ((iTemp - 65) + llave) MOD 26   'QBasic
        'LET iTemp = MOD(((iTemp - 65) + llave), 26) 'True BASIC
        PRINT CHR$(iTemp + 65);
    ELSE
        PRINT CHR$(iTemp);
    END IF
NEXT i
END


  [ dup upper != ]              is lower? ( c --> b )

  [ dup lower != ]              is upper? ( c --> b )

  [ swap $ "" unrot witheach
      [ dup lower? iff
          [ over +
            dup lower? not if
              [ 26 - ] ]
        else
          [ dup upper? if
            [ over +
              dup upper? not if
                [ 26 - ] ] ]
        rot swap join swap ]
    drop ]                      is caesar ( $ --> $ )

  [ 26 swap - ]                 is decode ( n --> n )

  $ "Fere libenter homines id quod volunt credunt."
  dup              echo$ cr
  23 caesar dup    echo$ cr
  23 decode caesar echo$ cr


# based on Rot-13 solution: http://rosettacode.org/wiki/Rot-13#R
ceasar <- function(x, key)
{
  # if key is negative, wrap to be positive
  if (key < 0) {
    key <- 26 + key
  }

  old <- paste(letters, LETTERS, collapse="", sep="")
  new <- paste(substr(old, key * 2 + 1, 52), substr(old, 1, key * 2), sep="")
  chartr(old, new, x)
}

# simple examples from description
print(ceasar("hi",2))
print(ceasar("hi",20))

# more advanced example
key <- 3
plaintext <- "The five boxing wizards jump quickly."
cyphertext <- ceasar(plaintext, key)
decrypted <- ceasar(cyphertext, -key)

print(paste("    Plain Text: ", plaintext, sep=""))
print(paste("   Cypher Text: ", cyphertext, sep=""))
print(paste("Decrypted Text: ", decrypted, sep=""))


#lang racket

(define A (char->integer #\A))
(define Z (char->integer #\Z))
(define a (char->integer #\a))
(define z (char->integer #\z))

(define (rotate c n)
  (define cnum (char->integer c))
  (define (shift base) (integer->char (+ base (modulo (+ n (- cnum base)) 26))))
  (cond [(<= A cnum Z) (shift A)]
        [(<= a cnum z) (shift a)]
        [else c]))

(define (caesar s n)
  (list->string (for/list ([c (in-string s)]) (rotate c n))))

(define (encrypt s) (caesar s 1))
(define (decrypt s) (caesar s -1))


my @alpha = 'A' .. 'Z';
sub encrypt ( $key where 1..25, $plaintext ) {
    $plaintext.trans( @alpha Z=> @alpha.rotate($key) );
}
sub decrypt ( $key where 1..25, $cyphertext ) {
    $cyphertext.trans( @alpha.rotate($key) Z=> @alpha );
}

my $original = 'THE FIVE BOXING WIZARDS JUMP QUICKLY';
my $en = encrypt( 13, $original );
my $de = decrypt( 13, $en );

.say for $original, $en, $de;

say 'OK' if $original eq all( map { .&decrypt(.&encrypt($original)) }, 1..25 );


Red ["Ceasar Cipher"]

rot: func [
    char [char!]
    key  [number!]
    ofs  [char!]
][
    to-char key + char - ofs // 26 + ofs
]

caesar: function [
    src [string!]
    key [integer!]
][
    lower: charset [#"a" - #"z"]
    upper: charset [#"A" - #"Z"]
    parse src [
        any [
            change s: [lower (o: #"a") | upper (o: #"A")] (rot s/1 key o)
          | skip
        ]
    ]
    src
]

encrypt: :caesar
decrypt: func spec-of :caesar [caesar src negate key]


{{
  variable offset
  : rotate  ( cb-c ) tuck - @offset + 26 mod + ;
  : rotate? (  c-c )
    dup 'a 'z within [ 'a rotate ] ifTrue
    dup 'A 'Z within [ 'A rotate ] ifTrue ;
---reveal---
  : ceaser  (  $n-$ )
    !offset dup [ [ @ rotate? ] sip ! ] ^types'STRING [email protected] ;
}}

( Example )
"THEYBROKEOURCIPHEREVERYONECANREADTHIS" 3 ceaser   ( returns encrypted string )
23 ceaser   ( returns decrypted string )


/*REXX program supports the  Caesar cypher for the Latin alphabet only,  no punctuation */
/*──────────── or blanks allowed,  all lowercase Latin letters are treated as uppercase.*/
parse arg key .;    arg . p                      /*get key & uppercased text to be used.*/
p= space(p, 0)                                   /*elide any and all spaces (blanks).   */
                    say 'Caesar cypher key:' key /*echo the Caesar cypher key to console*/
                    say '       plain text:' p   /*  "   "       plain text    "    "   */
y= Caesar(p, key);  say '         cyphered:' y   /*  "   "    cyphered text    "    "   */
z= Caesar(y,-key);  say '       uncyphered:' z   /*  "   "  uncyphered text    "    "   */
if z\==p  then say  "plain text doesn't match uncyphered cyphered text."
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Caesar: procedure; arg s,k;  @= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        ak= abs(k)                               /*obtain the absolute value of the key.*/
        L= length(@)                             /*obtain the length of the  @  string. */
        if ak>length(@)-1  |  k==0  then  call err k  'key is invalid.'
        _= verify(s, @)                          /*any illegal characters specified ?   */
        if _\==0  then call err 'unsupported character:'   substr(s, _, 1)
        if k>0    then ky= k + 1                 /*either cypher it,  or ···            */
                  else ky= L + 1 - ak            /*     decypher it.                    */
        return translate(s, substr(@ || @,  ky,  L),   @)   /*return the processed text.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
err:    say;      say '***error***';       say;          say arg(1);      say;     exit 13


# Project : Caesar cipher

cipher = "pack my box with five dozen liquor jugs"
abc = "abcdefghijklmnopqrstuvwxyz"
see "text is to be encrypted:" + nl
see cipher+ nl + nl
str = ""
key = random(24) + 1
see "key = " + key + nl + nl
see "encrypted:" + nl
caesarencode(cipher, key)
see str + nl + nl
cipher = str
see "decrypted again:" + nl
caesardecode(cipher, key)
see str + nl

func caesarencode(cipher, key)
       str = ""
       for n = 1 to len(cipher)
            if cipher[n] != " "
               pos = substr(abc, cipher[n])
               if pos + key < len(abc)
                  str = str + abc[pos + key]
               else
                  if (pos+key)-len(abc) != 0
                     str = str + abc[(pos+key)%len(abc)]
                  else
                      str = str +abc[key+pos]
                  ok
                    ok
               else
                  str = str + " "
               ok
       next
     return str

func caesardecode(cipher, key)
       str = ""
       for n= 1 to len(cipher)
            if cipher[n] != " "
               pos = substr(abc, cipher[n])
               if (pos - key) > 0 and pos != key
                   str = str + abc[pos - key]
                   loop
               else
                   if pos = key
                      str = str + char(122)
                   else
                     str = str + abc[len(abc)-(key-pos)]
                   ok
               ok
            else
               str = str + " "
            ok
       next
       return str


class String
  ALFABET = ("A".."Z").to_a

  def caesar_cipher(num)
    self.tr(ALFABET.join, ALFABET.rotate(num).join)
  end

end

#demo:
encypted  = "THEYBROKEOURCIPHEREVERYONECANREADTHIS".caesar_cipher(3)
decrypted = encypted.caesar_cipher(-3)


input "Gimme a ofset:";ofst       ' set any offset you like

a$ = "Pack my box with five dozen liquor jugs"
print " Original: ";a$
a$ = cipher$(a$,ofst)
print "Encrypted: ";a$
print "Decrypted: ";cipher$(a$,ofst+6)

FUNCTION cipher$(a$,ofst)
for i = 1 to len(a$)
  aa$   = mid$(a$,i,1)
  code$ = " "
  if aa$ <> " " then
    ua$   = upper$(aa$)
    a     = asc(ua$) - 64
    code$ = chr$((((a mod 26) + ofst) mod 26) + 65)
    if ua$ <> aa$ then code$ = lower$(code$)
  end if
  cipher$ = cipher$;code$
next i
END FUNCTION


use std::io::{self, Write};
use std::fmt::Display;
use std::{env, process};

fn main() {
    let shift: u8 = env::args().nth(1)
        .unwrap_or_else(|| exit_err("No shift provided", 2))
        .parse()
        .unwrap_or_else(|e| exit_err(e, 3));

    let plain = get_input()
        .unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));

    let cipher = plain.chars()
        .map(|c| {
            let case = if c.is_uppercase() {'A'} else {'a'} as u8;
            if c.is_alphabetic() { (((c as u8 - case + shift) % 26) + case) as char } else { c }
        }).collect::<String>();

    println!("Cipher text: {}", cipher.trim());
}

fn get_input() -> io::Result<String> {
    print!("Plain text:  ");
    try!(io::stdout().flush());

    let mut buf = String::new();
    try!(io::stdin().read_line(&mut buf));
    Ok(buf)
}

fn exit_err<T: Display>(msg: T, code: i32) -> ! {
    let _ = writeln!(&mut io::stderr(), "ERROR: {}", msg);
    process::exit(code);
}


object Caesar {
  private val alphaU='A' to 'Z'
  private val alphaL='a' to 'z'

  def encode(text:String, key:Int)=text.map{
    case c if alphaU.contains(c) => rot(alphaU, c, key)
    case c if alphaL.contains(c) => rot(alphaL, c, key)
    case c => c
  }
  def decode(text:String, key:Int)=encode(text,-key)
  private def rot(a:IndexedSeq[Char], c:Char, key:Int)=a((c-a.head+key+a.size)%a.size)
}


;
; Works with R7RS-compatible Schemes (e.g. Chibi).
; Also current versions of Chicken, Gauche and Kawa.
;
(cond-expand
  (chicken (use srfi-13))
  (gauche  (use srfi-13))
  (kawa    (import (srfi :13)))
  (else    (import (scheme base) (scheme write)))) ; R7RS

(define msg "The quick brown fox jumps over the lazy dog.")
(define key 13)

(define (caesar char)
  (define A (char->integer #\A))
  (define Z (char->integer #\Z))
  (define a (char->integer #\a))
  (define z (char->integer #\z))
  (define c (char->integer char))
  (integer->char
    (cond ((<= A c Z) (+ A (modulo (+ key (- c A)) 26)))
          ((<= a c z) (+ a (modulo (+ key (- c a)) 26)))
          (else c)))) ; Return other characters verbatim.

(display (string-map caesar msg))
(newline)


#!/bin/sed -rf
# Input: <number 0..25>\ntext to encode

/^[0-9]+$/ {
	# validate a number and translate it to analog form
	s/$/;9876543210dddddddddd/
	s/([0-9]);.*\1.{10}(.?)/\2/
	s/2/11/
	s/1/dddddddddd/g
	/[3-9]|d{25}d+/ {
	s/.*/Error: Key must be <= 25/
	q
	}
	# append from-table
	s/$/\nabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/
	# .. and to-table
	s/$/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/
	# rotate to-table, lower and uppercase independently, removing one `d' at a time
	: rotate
	s/^d(.*\n[^Z]+Z)(.)(.{25})(.)(.{25})/\1\3\2\5\4/
	t rotate
	s/\n//
	h
	d
}

# use \n to mark character to convert
s/^/\n/
# append conversion table to pattern space
G
: loop
	# look up converted character and place it instead of old one
	s/\n(.)(.*\n.*\1.{51}(.))/\n\3\2/
	# advance \n even if prev. command fails, thus skip non-alphabetical characters
	/\n\n/! s/\n([^\n])/\1\n/
t loop
s/\n\n.*//


$ include "seed7_05.s7i";

const func string: rot (in string: stri, in integer: encodingKey) is func
  result
    var string: encodedStri is "";
  local
    var char: ch is ' ';
    var integer: index is 0;
  begin
    encodedStri := stri;
    for ch key index range stri do
      if ch >= 'a' and ch <= 'z' then
        ch := chr((ord(ch) - ord('a') + encodingKey) rem 26 + ord('a'));
      elsif ch >= 'A' and ch <= 'Z' then
        ch := chr((ord(ch) - ord('A') + encodingKey) rem 26 + ord('A'));
      end if;
      encodedStri @:= [index] ch;
    end for;
  end func;

const proc: main is func
  local
    const integer: exampleKey is 3;
    const string: testText is "The five boxing wizards jump quickly";
  begin
    writeln("Original:  " <& testText);
    writeln("Encrypted: " <& rot(testText, exampleKey));
    writeln("Decrypted: " <& rot(rot(testText, exampleKey), 26 - exampleKey));
  end func;


import <Utilities/Sequence.sl>;
import <Utilities/Conversion.sl>;

lowerAlphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
upperAlphabet := "abcdefghijklmnopqrstuvwxyz";

caesarEncrypt(ch, key) :=
	let
		correctAlphabet :=
				lowerAlphabet when some(ch = lowerAlphabet)
			else
				upperAlphabet;

		index := Sequence::firstIndexOf(correctAlphabet, ch);

		newIndex := (index + key - 1) mod 26 + 1;
	in
		ch when not(some(ch = lowerAlphabet) or some(ch = upperAlphabet))
	else
		correctAlphabet[newIndex];

caesarDecrypt(ch, key) := caesarEncrypt(ch, 26 - key);

main(args(2)) :=
	let
		key := Conversion::stringToInt(args[2]);
		encrypted := caesarEncrypt(args[1], key);
		decrypted := caesarDecrypt(encrypted, key);
	in
		"Input: \t" ++ args[1] ++ "\n" ++
		"Encrypted:\t" ++ encrypted ++ "\n" ++
		"Decrypted:\t" ++ decrypted;


func caesar(msg, key, decode=false) {
    decode && (key = (26 - key));
    msg.gsub(/([A-Z])/i, {|c| ((c.uc.ord - 65 + key) % 26) + 65 -> chr});
};

var msg = 'THE FIVE BOXING WIZARDS JUMP QUICKLY';

var enc = caesar(msg, 10);
var dec = caesar(enc, 10, true);

say "msg: #{msg}";
say "enc: #{enc}";
say "dec: #{dec}";


 10 INPUT KEY
 20 INPUT T$
 30 LET C$=""
 40 FOR I=1 TO LEN T$
 50 LET L$=T$(I)
 60 IF L$<"A" OR L$>"Z" THEN GOTO 100
 70 LET L$=CHR$ (CODE L$+KEY)
 80 IF L$>"Z" THEN LET L$=CHR$ (CODE L$-26)
 90 IF L$<"A" THEN LET L$=CHR$ (CODE L$+26)
100 LET C$=C$+L$
110 NEXT I
120 PRINT C$


'THE QUICK BROWN FOX' rot:3 -> 'WKH TXLFN EURZQ IRA'


function caesar(s, k) {
	u = ascii(s)
	i = selectindex(u:>=65 :& u:<=90)
	if (length(i)>0) u[i] = mod(u[i]:+(k-65), 26):+65
	i = selectindex(u:>=97 :& u:<=122)
	if (length(i)>0) u[i] = mod(u[i]:+(k-97), 26):+97
	return(char(u))
}

caesar("layout", 20)
  fusion


func usage(_ e:String) {
  print("error: \(e)")
  print("./caeser -e 19 a-secret-string")
  print("./caeser -d 19 tskxvjxlskljafz")
}

func charIsValid(_ c:Character) -> Bool {
  return c.isASCII && ( c.isLowercase || 45 == c.asciiValue ) // '-' = 45
}

func charRotate(_ c:Character, _ by:Int) -> Character {
  var cv:UInt8! = c.asciiValue
  if 45 == cv { cv = 96 }  // if '-', set it to 'a'-1
  cv += UInt8(by)
  if 122 < cv { cv -= 27 } // if larget than 'z', reduce by 27
  if 96 == cv { cv = 45 }  // restore '-'
  return Character(UnicodeScalar(cv))
}

func caesar(_ enc:Bool, _ key:Int, _ word:String) -> String {
  let r = enc ? key : 27 - key
  func charRotateWithKey(_ c:Character) -> Character {
    return charRotate(c,r)
  }
  return String(word.map(charRotateWithKey))
}

func main() {
  var encrypt = true

  if 4 != CommandLine.arguments.count {
    return usage("caesar expects exactly three arguments")
  }

  switch ( CommandLine.arguments[1] ) {
  case "-e":
    encrypt = true
  case "-d":
    encrypt = false
  default:
    return usage("first argument must be -e (encrypt) or -d (decrypt)")
  }

  guard let key = Int(CommandLine.arguments[2]) else {
    return usage("second argument not a number (must be in range 0-26)")
  }

  if key < 0 || 26 < key {
    return usage("second argument not in range 0-26")
  }

  if !CommandLine.arguments[3].allSatisfy(charIsValid) {
    return usage("third argument must only be lowercase ascii characters, or -")
  }

  let ans = caesar(encrypt,key,CommandLine.arguments[3])
  print("\(ans)")
}

func test() {
  if ( Character("a") != charRotate(Character("a"),0) ) {
    print("Test Fail 1")
  }
  if ( Character("-") != charRotate(Character("-"),0) ) {
    print("Test Fail 2")
  }
  if ( Character("-") != charRotate(Character("z"),1) ) {
    print("Test Fail 3")
  }
  if ( Character("z") != charRotate(Character("-"),26)) {
    print("Test Fail 4")
  }
  if ( "ihgmkzma" != caesar(true,8,"a-zecret") ) {
    print("Test Fail 5")
  }
  if ( "a-zecret" != caesar(false,8,"ihgmkzma") ) {
    print("Test Fail 6")
  }
}

test()
main()


package require Tcl 8.6;    # Or TclOO package for 8.5

oo::class create Caesar {
    variable encryptMap decryptMap
    constructor shift {
	for {set i 0} {$i < 26} {incr i} {
	    # Play fast and loose with string/list duality for shorter code
	    append encryptMap [format "%c %c %c %c " \
		    [expr {$i+65}] [expr {($i+$shift)%26+65}] \
		    [expr {$i+97}] [expr {($i+$shift)%26+97}]]
	    append decryptMap [format "%c %c %c %c " \
		    [expr {$i+65}] [expr {($i-$shift)%26+65}] \
		    [expr {$i+97}] [expr {($i-$shift)%26+97}]]
	}
    }

    method encrypt text {
	string map $encryptMap $text
    }
    method decrypt text {
	string map $decryptMap $text
    }
}


$$ MODE TUSCRIPT
text="THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
PRINT "text orginal    ",text

abc="ABCDEFGHIJKLMNOPQRSTUVWXYZ",key=3,caesarskey=key+1
secretbeg=EXTRACT (abc,#caesarskey,0)
secretend=EXTRACT (abc,0,#caesarskey)
secretabc=CONCAT (secretbeg,secretend)

abc=STRINGS (abc,":</:"),secretabc=STRINGS (secretabc,":</:")
abc=SPLIT (abc),         secretabc=SPLIT (secretabc)
abc2secret=JOIN(abc," ",secretabc),secret2abc=JOIN(secretabc," ",abc)

BUILD X_TABLE abc2secret=*
DATA  {abc2secret}

BUILD X_TABLE secret2abc=*
DATA  {secret2abc}

ENCODED = EXCHANGE (text,abc2secret)
PRINT "text encoded    ",encoded

DECODED = EXCHANGE (encoded,secret2abc)
PRINT "encoded decoded ",decoded


@(next :args)
@(cases)
@{key /[0-9]+/}
@text
@(or)
@  (throw error "specify <key-num> <text>")
@(end)
@(do
   (defvar k (int-str key 10)))
@(bind enc-dec
       @(collect-each ((i (range 0 25)))
          (let* ((p (tostringp (+ #\a i)))
                 (e (tostringp (+ #\a (mod (+ i k) 26))))
                 (P (upcase-str p))
                 (E (upcase-str e)))
            ^(((,p ,e) (,P ,E))
              ((,e ,p) (,E ,P))))))
@(deffilter enc . @(mappend (fun first) enc-dec))
@(deffilter dec . @(mappend (fun second) enc-dec))
@(output)
encoded: @{text :filter enc}
decoded: @{text :filter dec}
@(end)


function replace(input: string, key: number) : string {
	return input.replace(/([a-z])/g,
		($1) => String.fromCharCode(($1.charCodeAt(0) + key + 26 - 97) % 26 + 97)
		).replace(/([A-Z])/g,
		($1) => String.fromCharCode(($1.charCodeAt(0) + key + 26 - 65) % 26 + 65));
}

// test
var str = 'The five boxing wizards jump quickly';
var encoded = replace(str, 3);
var decoded = replace(encoded, -3);

console.log('Enciphered: ' + encoded);
console.log('Deciphered: ' + decoded);


caesar() {
    local OPTIND
    local encrypt n=0
    while getopts :edn: option; do
        case $option in
            e) encrypt=true ;;
            d) encrypt=false ;;
            n) n=$OPTARG ;;
            :) echo "error: missing argument for -$OPTARG" >&2
               return 1 ;;
            ?) echo "error: unknown option -$OPTARG" >&2
               return 1 ;;
        esac
    done
    shift $((OPTIND-1))
    if [[ -z $encrypt ]]; then
        echo "error: specify one of -e or -d" >&2
        return 1
    fi

    local upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ
    local lower=abcdefghijklmnopqrstuvwxyz
    if $encrypt; then
        tr "$upper$lower" "${upper:n}${upper:0:n}${lower:n}${lower:0:n}" <<< "$1"
    else
        tr "${upper:n}${upper:0:n}${lower:n}${lower:0:n}" "$upper$lower" <<< "$1"
    fi
}

tr() {
    local -A charmap
    local i trans line char
    for ((i=0; i<${#1}; i++)); do
        charmap[${1:i:1}]=${2:i:1}
    done
    while IFS= read -r line; do
        trans=""
        for ((i=0; i<${#line}; i++)); do
            char=${line:i:1}
            if [[ -n ${charmap[$char]} ]]; then
                trans+=${charmap[$char]}
            else
                trans+=$char
            fi
        done
        echo "$trans"
    done
}

txt="The five boxing wizards jump quickly."
enc=$(caesar -e -n 5 "$txt")
dec=$(caesar -d -n 5 "$enc")

echo "original:  $txt"
echo "encrypted: $enc"
echo "decrypted: $dec"


decl string mode
while (not (or (= mode "encode") (= mode "decode")))
	out "encode/decode: " console
	set mode (lower (in string console))
end while

decl string message
out "message:       " console
set message (upper (in string console))

decl int key
out "key:           " console
set key (in int console)
if (or (> key 26) (< key 0))
	out endl "invalid key" endl console
	stop
end if

if (= mode "decode")
	set key (int (- 26 key))
end if

for (decl int i) (< i (size message)) (inc i)
	if (and (> (ord message<i>) 64) (< (ord message<i>) 91))
		out (chr (int (+ (mod (int (+ (- (ord message<i>) 65) key)) 26) 65))) console
	end if
end for
out endl console


#import std
#import nat

enc "n" = * -:~&@T ^p(rep"n" ~&zyC,~&)~~K30K31X letters    # encryption function
dec "n" = * -:~&@T ^p(~&,rep"n" ~&zyC)~~K30K31X letters    # decryption function

plaintext = 'the five boxing wizards jump quickly THE FIVE BOXING WIZARDS JUMP QUICKLY'

#show+ # exhaustive test

test = ("n". <.enc"n",dec"n"+ enc"n"> plaintext)*= nrange/1 25


static void println(string str) {
    stdout.printf("%s\r\n", str);
}

static unichar encrypt_char(unichar ch, int code) {
    if (!ch.isalpha()) return ch;

    unichar offset = ch.isupper() ? 'A' : 'a';
    return (unichar)((ch + code - offset) % 26 + offset);
}

static string encrypt(string input, int code) {
    var builder = new StringBuilder();

    unichar c;
    for (int i = 0; input.get_next_char(ref i, out c);) {
        builder.append_unichar(encrypt_char(c, code));
    }

    return builder.str;
}

static string decrypt(string input, int code) {
    return encrypt(input, 26 - code);
}

const string test_case = "The quick brown fox jumped over the lazy dog";

void main() {
    println(test_case);
    println(encrypt(test_case, -1));
    println(decrypt(encrypt(test_case, -1), -1));
}


Option Explicit

Sub Main_Caesar()
Dim ch As String
    ch = Caesar_Cipher("CAESAR: Who is it in the press that calls on me? I hear a tongue, shriller than all the music, Cry 'Caesar!' Speak; Caesar is turn'd to hear.", 14)
    Debug.Print ch
    Debug.Print Caesar_Cipher(ch, -14)
End Sub

Function Caesar_Cipher(sText As String, lngNumber As Long) As String
Dim Tbl, strGlob As String, strTemp As String, i As Long, bytAscii As Byte
  Const MAJ As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Const NB_LETTERS As Byte = 26
      Const DIFFASCIIMAJ As Byte = 65 - NB_LETTERS
        Const DIFFASCIIMIN As Byte = 97 - NB_LETTERS

    strTemp = sText
    If lngNumber < NB_LETTERS And lngNumber > NB_LETTERS * -1 Then
        strGlob = String(NB_LETTERS * 4, " ")
        LSet strGlob = MAJ & MAJ & MAJ
        Tbl = Split(StrConv(strGlob, vbUnicode), Chr(0))
        For i = 1 To Len(strTemp)
            If Mid(strTemp, i, 1) Like "[a-zA-Z]" Then
                bytAscii = Asc(Mid(strTemp, i, 1))
                If Mid(strTemp, i, 1) = Tbl(bytAscii - DIFFASCIIMAJ) Then
                    Mid(strTemp, i) = Tbl(bytAscii - DIFFASCIIMAJ + lngNumber)
                Else
                    Mid(strTemp, i) = LCase(Tbl(bytAscii - DIFFASCIIMIN + lngNumber))
                End If
            End If
        Next i
    End If
    Caesar_Cipher = strTemp
End Function


	str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES."

	Wscript.Echo str
	Wscript.Echo Rotate(str,5)
	Wscript.Echo Rotate(Rotate(str,5),-5)

	'Rotate (Caesar encrypt/decrypt) test <numpos> positions.
	'  numpos < 0 - rotate left
	'  numpos > 0 - rotate right
	'Left rotation is converted to equivalent right rotation

	Function Rotate (text, numpos)

		dim dic: set dic = CreateObject("Scripting.Dictionary")
		dim ltr: ltr = Split("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z")
		dim rot: rot = (26 + numpos Mod 26) Mod 26 'convert all to right rotation
		dim ch
		dim i

		for i = 0 to ubound(ltr)
			dic(ltr(i)) = ltr((rot+i) Mod 26)
		next

		Rotate = ""

		for i = 1 to Len(text)
			ch = Mid(text,i,1)
			if dic.Exists(ch) Then
				Rotate = Rotate & dic(ch)
			else
				Rotate = Rotate & ch
			end if
		next

	End Function


#10 = Get_Num("Enter the key: positive to cipher, negative to de-cipher: ", STATLINE)

Goto_Pos(Block_Begin)
while(Cur_Pos < Block_End) {
    #11 = Cur_Char & 0x60 + 1
    if (Cur_Char >= 'A') {
        Ins_Char((Cur_Char - #11 + 26 + #10) % 26 + #11, OVERWRITE)
    } else {
	Char(1)
    }
}


Module Module1

    Function Encrypt(ch As Char, code As Integer) As Char
        If Not Char.IsLetter(ch) Then
            Return ch
        End If

        Dim offset = AscW(If(Char.IsUpper(ch), "A"c, "a"c))
        Dim test = (AscW(ch) + code - offset) Mod 26 + offset
        Return ChrW(test)
    End Function

    Function Encrypt(input As String, code As Integer) As String
        Return New String(input.Select(Function(ch) Encrypt(ch, code)).ToArray())
    End Function

    Function Decrypt(input As String, code As Integer) As String
        Return Encrypt(input, 26 - code)
    End Function

    Sub Main()
        Dim str = "Pack my box with five dozen liquor jugs."

        Console.WriteLine(str)
        str = Encrypt(str, 5)
        Console.WriteLine("Encrypted: {0}", str)
        str = Decrypt(str, 5)
        Console.WriteLine("Decrypted: {0}", str)
    End Sub

End Module


@let {
  ; this function only replaces letters and keeps case
  ceasar &[s n] !!s.replace &"[a-z]"gi &[x] [
    @vars {
      t x.charCodeAt.
      l ?{
        && > t 96 < t 123 97
        && > t 64 < t 91 65
        0
      }
    }
    !String.fromCharCode ?{
      l +l ~% 26 -+ n t l
      t
    }
  ]
  !!ceasar "abc $%^ ABC" 10
}


class Caesar {
    static encrypt(s, key) {
        var offset = key % 26
        if (offset == 0) return s
        var chars = List.filled(s.count, 0)
        for (i in 0...s.count) {
            var c = s[i].bytes[0]
            var d = c
            if (c >= 65 && c <= 90) { // 'A' to 'Z'
                d = c + offset
                if (d > 90) d = d - 26
            } else if (c >= 97 && c <= 122) {  // 'a' to 'z'
                d = c + offset
                if (d > 122) d = d - 26
            }
            chars[i] = d
        }
        return chars.reduce("") { |acc, c| acc + String.fromByte(c) }
    }

    static decrypt(s, key) { encrypt(s, 26 - key) }
}

var encoded = Caesar.encrypt("Bright vixens jump; dozy fowl quack.", 8)
System.print(encoded)
System.print(Caesar.decrypt(encoded, 8))


                                        # Author: Ettore Forigo - Hexwell

.intel_syntax noprefix

.text
.globl main
main:
.PROLOGUE:
    push    rbp
    mov rbp, rsp
    sub rsp, 32
    mov QWORD PTR [rbp-32], rsi         # argv

.BODY:
    mov BYTE PTR [rbp-1], 0             # shift = 0

    .I_LOOP_INIT:
        mov BYTE PTR [rbp-2], 0         # i = 0
        jmp .I_LOOP_CONDITION           # I_LOOP_CONDITION
    .I_LOOP_BODY:
        movzx edx, BYTE PTR[rbp-1]      # shift
        mov eax, edx                    # shift
        sal eax, 2                      # shift << 2 == i * 4
        add eax, edx                    # shift * 4 + shift = shift * 5
        add eax, eax                    # shift * 5 + shift * 5 = shift * 10
        mov ecx, eax                    # shift * 10
        mov rax, QWORD PTR [rbp-32]     # argv
        add rax, 8                      # argv + 1
        mov rdx, QWORD PTR [rax]        # argv[1]
        movzx eax, BYTE PTR [rbp-2]     # i
        add rax, rdx                    # argv[1] + i
        movzx eax, BYTE PTR [rax]       # argv[1][i]
        add eax, ecx                    # shift * 10 + argv[1][i]
        sub eax, 48                     # shift * 10 + argv[1][i] - '0'
        mov BYTE PTR [rbp-1], al        # shift = shift * 10 + argv[1][i] - '0'
    .I_LOOP_INCREMENT:
        movzx eax, BYTE PTR [rbp-2]     # i
        add eax, 1                      # i + 1
        mov BYTE PTR [rbp-2], al        # i++
    .I_LOOP_CONDITION:
        mov rax, QWORD PTR [rbp-32]     # argv
        add rax, 8                      # argv + 1
        mov rax, QWORD PTR [rax]        # argv[1]
        movzx edx, BYTE PTR [rbp-2]     # i
        add rax, rdx                    # argv[1] + i
        movzx rax, BYTE PTR [rax]       # argv[1][i]
        test al, al                     # argv[1][i]?
        jne .I_LOOP_BODY                # I_LOOP_BODY

    .CAESAR_LOOP_INIT:
        mov BYTE PTR [rbp-2], 0         # i = 0
        jmp .CAESAR_LOOP_CONDITION      # CAESAR_LOOP_CONDITION
    .CAESAR_LOOP_BODY:
        mov rax, QWORD PTR [rbp-32]     # argv
        add rax, 16                     # argv + 2
        mov rdx, QWORD PTR [rax]        # argv[2]
        movzx eax, BYTE PTR [rbp-2]     # i
        add rax, rdx                    # argv[2] + i
        mov rbx, rax                    # argv[2] + i
        movzx eax, BYTE PTR [rax]       # argv[2][i]
        cmp al, 32                      # argv[2][i] == ' '
        je .CAESAR_LOOP_INCREMENT       # CAESAR_LOOP_INCREMENT
        movzx edx, BYTE PTR [rbx]       # argv[2][i]
        mov ecx, edx                    # argv[2][i]
        movzx edx, BYTE PTR [rbp-1]     # shift
        add edx, ecx                    # argv[2][i] + shift
        sub edx, 97                     # argv[2][i] + shift - 'a'
        mov BYTE PTR [rbx], dl          # argv[2][i] = argv[2][i] + shift - 'a'
        movzx eax, BYTE PTR [rbx]       # argv[2][i]
        cmp al, 25                      # argv[2][i] <=> 25
        jle .CAESAR_RESTORE_ASCII       # <= CAESAR_RESTORE_ASCII
        movzx edx, BYTE PTR [rbx]       # argv[2][i]
        sub edx, 26                     # argv[2][i] - 26
        mov BYTE PTR [rbx], dl          # argv[2][i] = argv[2][i] - 26
    .CAESAR_RESTORE_ASCII:
        movzx edx, BYTE PTR [rbx]       # argv[2][i]
        add edx, 97                     # argv[2][i] + 'a'
        mov BYTE PTR [rbx], dl          # argv[2][i] = argv[2][i] + 'a'
    .CAESAR_LOOP_INCREMENT:
        movzx eax, BYTE PTR [rbp-2]     # i
        add eax, 1                      # i + 1
        mov BYTE PTR [rbp-2], al        # i++
    .CAESAR_LOOP_CONDITION:
        mov rax, QWORD PTR [rbp-32]     # argv
        add rax, 16                     # argv + 2
        mov rdx, QWORD PTR [rax]        # argv[2]
        movzx eax, BYTE PTR [rbp-2]     # i
        add rax, rdx                    # argv[2] + i
        movzx eax, BYTE PTR [rax]       # argv[2][i]
        test al, al                     # argv[2][i]?
        jne .CAESAR_LOOP_BODY           # CAESAR_LOOP_BODY

    mov rax, QWORD PTR [rbp-32]         # argv
    add rax, 16                         # argv + 2
    mov rax, QWORD PTR [rax]            # argv[2]
    mov rdi, rax                        # argv[2]
    call    puts                        # puts(argv[2])

.RETURN:
    mov eax, 0                          # 0
    leave
    ret                                 # return 0


PROGRAM "caesarcipher"
VERSION "0.0001"

DECLARE FUNCTION Entry()
INTERNAL FUNCTION Encrypt$(p$, key%%)
INTERNAL FUNCTION Decrypt$(p$, key%%)

FUNCTION Entry()
  txt$ = "The five boxing wizards jump quickly"
  key%% = 3
  PRINT "Original:  "; txt$
  enc$ = Encrypt$(txt$, key%%)
  PRINT "Encrypted: "; enc$
  PRINT "Decrypted: "; Decrypt$(enc$, key%%)
END FUNCTION

FUNCTION Encrypt$(p$, key%%)
  e$ = p$ ' In order to avoid iterative concatenations
  FOR i = 0 TO LEN(p$) - 1
    t@@ = p${i} ' or (slower) [email protected]@ = ASC(p$, i + 1)
    SELECT CASE TRUE
      CASE (t@@ >= 'A') AND ([email protected]@ <= 'Z'):
        t@@ = t@@ + key@@
        IF t&& > 'Z' THEN
          t@@ = t@@ - 26
        END IF
      CASE (t@@ >= 'a') AND ([email protected]@ <= 'z'):
        t@@ = t@@ + key%%
        IF t@@ > 'z' THEN
          t@@ = t@@ - 26
        END IF
    END SELECT
    e${i} = t@@
  NEXT i
END FUNCTION e$

FUNCTION Decrypt$(p$, key%%)
  e$ = p$ ' In order to avoid iterative concatenations
  FOR i = 0 TO LEN(p$) - 1
    t@@ = p${i} ' or (slower) [email protected]@ = ASC(p$, i + 1)
    SELECT CASE TRUE
      CASE (t@@ >= 'A') AND ([email protected]@ <= 'Z'):
        t@@ = t@@ - key%%
        IF t@@ < 'A' THEN
          t@@ = t@@ + 26
        END IF
      CASE (t@@ >= 'a') AND ([email protected]@ <= 'z'):
        t@@ = t@@ - key%%
        IF t@@ < 'a' THEN
          t@@ = t@@ + 26
        END IF
    END SELECT
    e${i} = t@@
  NEXT i
END FUNCTION e$
END PROGRAM


set letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"::split();

func caesar(text,shift:number=1){
	set res:string="";
	for(i=0;?text-1;1){
		set t=text::at(i);
		set n=(letters::find(t::upper())+shift)%?letters;
		while(n<0){
			n=?letters+n;
		}
		set l=letters[n];
		(t::upper()==t)|=>l=l::lower()
		res+=l;
	}
	send res;
}

func decode(text,shift:number=1){
	set res:string="";
	for(i=0;?text-1;1){
		set t=text::at(i);
		set n=(letters::find(t::upper())-shift)%?letters;
		while(n<0){
			n=?letters+n;
		}
		set l=letters[n];
		(t::upper()==t)|=>l=l::lower()
		res+=l;
	}
	send res;
}

set e=caesar("Hi",20);
set d=decode(e,20);

log(e);
log(d);


(defun caesar-encode (text key)
    (defun encode (ascii-code)
        (defun rotate (character alphabet)
            (define code (+ character key))
            (cond
                ((> code (+ alphabet 25)) (- code 26))
                ((< code alphabet) (+ code 26))
                (t code)))
        (cond
            ((and (>= ascii-code 65) (<= ascii-code 90)) (rotate ascii-code 65))
            ((and (>= ascii-code 97) (<= ascii-code 122)) (rotate ascii-code 97))
            (t ascii-code)))
        (list->string (mapcar integer->char (mapcar encode (mapcar char->integer (string->list text))))))

(defun caesar-decode (text key)
    (caesar-encode text (- 26 key)))


code ChIn=7, ChOut=8, IntIn=10;
int  Key, C;
[Key:= IntIn(8);
repeat  C:= ChIn(1);
        if C>=^a & C<=^z then C:= C-$20;
        if C>=^A & C<=^Z then
            [C:= C+Key;
            if C>^Z then C:= C-26
            else if C<^A then C:= C+26;
            ];
        ChOut(0, C);
until   C=$1A; \EOF
]


REM *** By changing the key and pattern, an encryption system that is difficult to break can be achieved. ***

text$ = "You are encouraged to solve this task according to the task description, using any language you may know."
key$ = "desoxirribonucleic acid" // With a single character you get a Caesar encryption. With more characters the key is much more difficult to discover.
CIPHER = 1 : DECIPHER = -1

print text$ : print
encrypted$ = criptex$(text$, key$, CIPHER)
a = open("cryptedText.txt", "w") : if a then print #a encrypted$ : close #a end if
print encrypted$ : print
print criptex$(encrypted$, key$, DECIPHER)

sub criptex$(text$, key$, mode)
	local i, k, delta, longtext, longPattern, longkey, pattern$, res$

	pattern$ = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 .,;:()-"

	longPattern = len(pattern$)
	longtext = len(text$)
	longkey = len(key$)

	for i = 1 to longtext
		k = k + 1 : if k > longkey k = 1
		delta = instr(pattern$, mid$(text$, i, 1))
		delta = delta + (mode * instr(pattern$, mid$(key$, k, 1)))
		if delta > longPattern then
			delta = delta - longPattern
		elseif delta < 1 then
			delta = longPattern + delta
		end if
		res$ = res$ + mid$(pattern$, delta, 1)
	next i

	return res$
end sub


fcn caesarCodec(str,n,encode=True){
   var [const] letters=["a".."z"].chain(["A".."Z"]).pump(String);  // static
   if(not encode) n=26 - n;
   m,sz := n + 26, 26 - n;
   ltrs:=String(letters[n,sz],letters[0,n],letters[m,sz],letters[26,n]);
   str.translate(letters,ltrs)
}


module Caesar;
const
	size = 25;

type
	Operation = (code,decode);

procedure C_D(s:string;k:integer;op: Operation): string;
var
	i,key: integer;
	resp: string;
	n,c: char;
begin
	resp := "";
	if op = Operation.decode then key := k else key := (26 - k) end;
	for i := 0 to len(s) - 1 do
		c := cap(s[i]);
		if (c >= 'A') & (c <= 'Z') then
			resp := resp +
				string(char(integer('A') + ((integer(c) - integer('A') + key )) mod 26));
		else
			resp := resp + string(c)
		end;
	end;
	return  resp
end C_D;

procedure {public} Cipher(s:string;k:integer):string;
var
	i: integer;
	resp: string;
	n,c: char;
begin
	return C_D(s,k,Operation.code)
end Cipher;

procedure {public} Decipher(s:string;k:integer):string;
var
	i: integer;
	resp: string;
	n,c: char;
begin
	return C_D(s,k,Operation.decode)
end Decipher;

var
	txt,cipher,decipher: string;

begin
	txt := "HI";cipher := Caesar.Cipher(txt,2);decipher := Caesar.Decipher(cipher,2);
	writeln(txt," -c-> ",cipher," -d-> ",decipher);
	txt := "ZA";cipher := Caesar.Cipher(txt,2);decipher := Caesar.Decipher(cipher,2);
	writeln(txt," -c-> ",cipher," -d-> ",decipher);
	txt := "The five boxing wizards jump quickly";
	cipher := Caesar.Cipher(txt,2);decipher := Caesar.Decipher(cipher,2);
	writeln(txt," -c-> ",cipher," -d-> ",decipher)
end Caesar.


10 LET t$="PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS"
20 PRINT t$''
30 LET key=RND*25+1
40 LET k=key: GO SUB 1000: PRINT t$''
50 LET k=26-key: GO SUB 1000: PRINT t$
60 STOP
1000 FOR i=1 TO LEN t$
1010 LET c= CODE t$(i)
1020 IF c<65 OR c>90 THEN GO TO 1050
1030 LET c=c+k: IF c>90 THEN LET c=c-90+64
1040 LET t$(i)=CHR$ c
1050 NEXT i
1060 RETURN