Vigenère cipher: Difference between revisions

m
(added Ceylon)
m (→‎{{header|Wren}}: Minor tidy)
 
(57 intermediate revisions by 32 users not shown)
Line 19:
<br><br>
 
=={{header|Ada11l}}==
{{trans|C++}}
 
<syntaxhighlight lang="11l">F encrypt(key, text)
<lang Ada>with Ada.Text_IO;
V out = ‘’
V j = 0
L(c) text
I !c.is_alpha()
L.continue
out ‘’= Char(code' (c.uppercase().code + key[j].code - 2 * ‘A’.code) % 26 + ‘A’.code)
j = (j + 1) % key.len
R out
 
F decrypt(key, text)
procedure Vignere_Cipher is
V out = ‘’
V j = 0
L(c) text
I !c.is_alpha()
L.continue
out ‘’= Char(code' (c.code - key[j].code + 26) % 26 + ‘A’.code)
j = (j + 1) % key.len
R out
 
V key = ‘VIGENERECIPHER’
subtype Letter is Character range 'A' .. 'Z';
V original = ‘Beware the Jabberwock, my son! The jaws that bite, the claws that catch!’
subtype Lowercase is Character range 'a' .. 'z';
V encrypted = encrypt(key, original)
V decrypted = decrypt(key, encrypted)
 
print(original)
function "+"(X, Y: Letter) return Letter is
print(‘Encrypted: ’encrypted)
begin
print(‘Decrypted: ’decrypted)</syntaxhighlight>
return Character'Val( ( (Character'Pos(X)-Character'Pos('A'))
+ (Character'Pos(Y)-Character'Pos('A')) ) mod 26
+ Character'Pos('A'));
end;
 
{{out}}
function Normalize(S: String) return String is
<pre>
-- removes all characters except for uppercase and lowercase letters
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
-- replaces lowercase by uppercase letters
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Offset: Integer := Character'Pos('A') - Character'Pos('a');
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
begin
</pre>
if S="" then
return "";
elsif S(S'First) in Letter then
return S(S'First) & Normalize(S(S'First+1 .. S'Last));
elsif S(S'First) in Lowercase then
return (Character'Val(Character'Pos(S(S'First)) + Offset)
& Normalize(S(S'First+1 .. S'Last)));
else
return Normalize(S(S'First+1 .. S'Last));
end if;
end Normalize;
 
=={{header|Action!}}==
function Encrypt(Key: String; Text: String) return String is
<syntaxhighlight lang="action!">PROC Fix(CHAR ARRAY in,fixed)
Ciphertext: String(Text'Range);
INT begini
CHAR c
for I in Text'Range loop
Ciphertext(I) := Text(I)
+ Key(Key'First + ((I-Text'First) mod Key'Length));
end loop;
return Ciphertext;
end Encrypt;
 
fixed(0)=0
function Invert(Key: String) return String is
FOR i=1 TO in(0)
Result: String(Key'Range);
beginDO
for I c=in Key'Range loop(i)
IF c>='a AND c<='z Result(I)THEN
c==-('a-'A)
:= Character'Val( 26 - (Character'Pos(Key(I))-Character'Pos('A'))
FI
+ Character'Pos('A') );
IF c>='A endAND loop;c<='Z THEN
return Result;fixed(0)==+1
fixed(fixed(0))=c
end Invert;
FI
OD
RETURN
 
PROC Process(CHAR ARRAY in,key,out INT dir)
use Ada.Text_IO;
CHAR ARRAY inFixed(256),keyFixed(256)
Input: String := Get_Line;
INT keyI,tmp,i
Key: String := Normalize(Get_Line);
CHAR c
Ciph: String := Encrypt(Key => Key, Text => Normalize(Input));
 
out(0)=0
begin
Fix(in,inFixed)
Put_Line("Input =" & Input);
Fix(key,keyFixed)
Put_Line("Key =" & Key);
IF inFixed(0)=0 OR keyFixed(0)=0 THEN
Put_Line("Ciphertext =" & Ciph);
RETURN
Put_Line("Decryption =" & Encrypt(Key => Invert(Key), Text => Ciph));
FI
end Vignere_Cipher;</lang>
 
keyI=1
FOR i=1 TO inFixed(0)
DO
c=inFixed(i)
tmp=c-'A+dir*(keyFixed(keyI)-'A)
IF tmp<0 THEN
tmp==+26
FI
out(0)==+1
out(out(0))='A+tmp MOD 26
keyI==+1
IF keyI>keyFixed(0) THEN
keyI=1
FI
OD
RETURN
 
PROC Encrypt(CHAR ARRAY in,key,out)
Process(in,key,out,1)
RETURN
 
PROC Decrypt(CHAR ARRAY in,key,out)
Process(in,key,out,-1)
RETURN
 
PROC Test(CHAR ARRAY in,key)
CHAR ARRAY enc(256),dec(256)
 
PrintE("Original:") PrintE(in)
Encrypt(in,key,enc)
PrintF("Encrypted key=%S:%E",key) PrintE(enc)
Decrypt(enc,key,dec)
PrintF("Decrypted key=%S:%E",key) PrintE(dec)
PutE()
RETURN
 
PROC Main()
Test("Attack at dawn!","LEMONLEMONLE")
 
Test("Crypto is short for cryptography.","ABCDABCDABCDABCDABCDABCDABCD")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Vigen%C3%A8re_cipher.png Screenshot from Atari 8-bit computer]
<pre>./vignere_cipher < input.txt
<pre>
Input =Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Original:
Key =VIGENERECIPHER
Attack at dawn!
Ciphertext =WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Encrypted key=LEMONLEMONLE:
Decryption =BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
LXFOPVEFRNHR
Decrypted key=LEMONLEMONLE:
ATTACKATDAWN
 
Original:
Crypto is short for cryptography.
Encrypted key=ABCDABCDABCDABCDABCDABCDABCD:
CSASTPKVSIQUTGQUCSASTPIUAQJB
Decrypted key=ABCDABCDABCDABCDABCDABCDABCD:
CRYPTOISSHORTFORCRYPTOGRAPHY
</pre>
 
=={{header|Ada}}==
 
<syntaxhighlight lang="ada">WITH Ada.Text_IO, Ada.Characters.Handling;
USE Ada.Text_IO, Ada.Characters.Handling;
 
PROCEDURE Main IS
SUBTYPE Alpha IS Character RANGE 'A' .. 'Z';
TYPE Ring IS MOD (Alpha'Range_length);
TYPE Seq IS ARRAY (Integer RANGE <>) OF Ring;
FUNCTION "+" (S, Key : Seq) RETURN Seq IS
R : Seq (S'Range);
BEGIN
FOR I IN R'Range LOOP
R (I) := S (I) + Key (Key'First + (I - R'First) MOD Key'Length);
END LOOP;
RETURN R;
END "+";
FUNCTION "-" (S : Seq) RETURN Seq IS
R : Seq (S'Range);
BEGIN
FOR I IN R'Range LOOP
R (I) := - S (I);
END LOOP;
RETURN R;
END "-";
FUNCTION To_Seq (S : String) RETURN Seq IS
R : Seq (S'Range);
I : Integer := R'First;
BEGIN
FOR C OF To_Upper (S) LOOP
IF C IN Alpha THEN
R (I) := Ring'Mod (Alpha'Pos (C) - Alpha'Pos (Alpha'First));
I := I + 1;
END IF;
END LOOP;
RETURN R (R'First .. I - 1);
END To_Seq;
FUNCTION To_String (S : Seq ) RETURN String IS
R : String (S'Range);
BEGIN
FOR I IN R'Range LOOP
R (I) := Alpha'Val ( Integer (S (I)) + Alpha'Pos (Alpha'First));
END LOOP;
RETURN R;
END To_String;
Input : Seq := To_Seq (Get_Line);
Key : Seq := To_Seq (Get_Line);
Crypt : Seq := Input + Key;
BEGIN
Put_Line ("Encrypted: " & To_String (Crypt));
Put_Line ("Decrypted: " & To_String (Crypt + (-Key)));
END Main;
 
</syntaxhighlight>
 
{{out}}
<pre>Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
VIGENERECIPHER
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
=={{header|ALGOL 68}}==
Line 97 ⟶ 219:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d].}}
<langsyntaxhighlight lang="algol68">STRING key := "";
 
PROC vigenere cipher = (REF STRING key)VOID:
Line 158 ⟶ 280:
print(("Encrypted: ", encrypted, new line));
print(("Decrypted: ", decrypted, new line))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 169 ⟶ 291:
Lines <code>340,350,430,440</code> could probably been put into some DEF FN, but it would probably have made it harder to read. The maximum length for a string in AppleSoft BASIC is 255 characters.
I have not used the DEF FN MOD(A) function in line <code>450</code> on purpose, as I still would have had to correct for a possible negative value.
<syntaxhighlight lang="applesoft basic">
<lang Applesoft BASIC>
100 :
110 REM VIGENERE CIPHER
Line 197 ⟶ 319:
470 K = K + 1: IF K > LEN (K$) THEN K = 1
480 NEXT I
490 PRINT "DECRYPTED TEXT: ";DT$ </langsyntaxhighlight>
{{out}}
KEY: LEMON
Line 203 ⟶ 325:
CIPHER TEXT: LXFOPVEFRNHR
DECRYPTED TEXT: ATTACKATDAWN
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">Letters: append `A`..`Z` `a`..`z`
encrypt: function [msg, key][
pos: 0
result: new ""
loop msg 'c ->
if in? c Letters [
'result ++ to :char (((to :integer key\[pos]) + to :integer upper c) % 26) + to :integer `A`
pos: (pos + 1) % size key
]
return result
]
 
decrypt: function [msg, key][
pos: 0
result: new ""
loop msg 'c [
'result ++ to :char ((26 + (to :integer c) - to :integer key\[pos]) % 26) + to :integer `A`
pos: (pos + 1) % size key
]
return result
]
 
text: "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
key: "VIGENERECIPHER"
 
encr: encrypt text key
decr: decrypt encr key
 
print text
print encr
print decr</syntaxhighlight>
 
{{out}}
 
<pre>Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Key = VIGENERECIPHER
Text= Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
 
Line 227 ⟶ 389:
decoderKey .= Chr(26-(Asc(A_LoopField)-65)+65)
return VigenereCipher(Text, decoderKey)
}</langsyntaxhighlight>
{{out}}
<pre>Input =Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 233 ⟶ 395:
Ciphertext =WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted =BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
 
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
function Filtrar(cadorigen)
filtrado = ""
for i = 1 to length(cadorigen)
letra = upper(mid(cadorigen, i, 1))
if instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", letra) then filtrado += letra
next i
return filtrado
end function
 
function Encriptar(texto, llave)
texto = Filtrar(texto)
cifrado = ""
j = 1
for i = 1 to length(texto)
mSS = mid(texto, i, 1)
m = asc(mSS) - asc("A")
kSS = mid(llave, j, 1)
k = asc(kSS) - asc("A")
j = (j mod length(llave)) + 1
c = (m + k) mod 26
letra = chr(asc("A") + c)
cifrado += letra
next i
return cifrado
end function
 
function DesEncriptar(texto, llave)
descifrado = ""
j = 1
for i = 1 to length(texto)
mSS = mid(texto, i, 1)
m = asc(mSS) - asc("A")
kSS = mid(llave, j, 1)
k = asc(kSS) - asc("A")
j = (j mod length(llave)) + 1
c = (m - k + 26) mod 26
letra = chr(asc("A")+c)
descifrado += letra
next i
return descifrado
end function
 
llave = Filtrar("vigenerecipher")
cadorigen = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
print cadorigen
print llave
 
cadcifrada = Encriptar(cadorigen, llave)
print " Cifrado: "; cadcifrada
print "Descifrado: "; DesEncriptar(cadcifrada, llave)
end
</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
 
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> key$ = "LEMON"
plaintext$ = "ATTACK AT DAWN"
ciphertext$ = FNencrypt(plaintext$, key$)
Line 274 ⟶ 498:
IF C% >= 97 IF C% <= 122 MID$(A$,A%,1) = CHR$(C%-32)
NEXT
= A$</langsyntaxhighlight>
{{out}}
<pre>
Line 286 ⟶ 510:
The text to encrypt is read from stdin. The key is the string literal at the start of the program.
 
<langsyntaxhighlight lang="befunge">"VIGENERECIPHER">>>>1\:!v>"A"-\:00p0v
>>!#:0#-0#1g#,*#<+:v:-1$_^#!:\+1g00p<
\"{"\v>9+2*%"A"+^>$>~>:48*\`#@_::"`"`
*84*`<^4+"4"+g0\_^#!+`*55\`\0::-"A"-*</langsyntaxhighlight>
 
{{out}}
Line 297 ⟶ 521:
The decrypter is essentially identical, except for a change of sign on the last line.
 
<langsyntaxhighlight lang="befunge">"VIGENERECIPHER">>>>1\:!v>"A"-\:00p0v
>>!#:0#-0#1g#,*#<+:v:-1$_^#!:\+1g00p<
\"{"\v>9+2*%"A"+^>$>~>:48*\`#@_::"`"`
*84*`<^4+"4"-g0\_^#!+`*55\`\0::-"A"-*</langsyntaxhighlight>
 
{{out}}
Line 308 ⟶ 532:
=={{header|C}}==
This program skips non-alphabetical characters, preserves case, and when run with the <code>-d</code> command line flag, decrypts the message rather than encrypting.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 420 ⟶ 644:
 
return buf;
}</langsyntaxhighlight>
 
{{out}}
Line 430 ⟶ 654:
Cipher text: Wmceei klg Rpifvmeugx, qp wqv! Ioi avey xuek fkbt, alv xtgaf xyev kpagy!
Plain text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">
using System;
 
namespace VigenereCipher
{
class VCipher
{
public string encrypt(string txt, string pw, int d)
{
int pwi = 0, tmp;
string ns = "";
txt = txt.ToUpper();
pw = pw.ToUpper();
foreach (char t in txt)
{
if (t < 65) continue;
tmp = t - 65 + d * (pw[pwi] - 65);
if (tmp < 0) tmp += 26;
ns += Convert.ToChar(65 + ( tmp % 26) );
if (++pwi == pw.Length) pwi = 0;
}
 
return ns;
}
};
 
class Program
{
static void Main(string[] args)
{
VCipher v = new VCipher();
 
string s0 = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!",
pw = "VIGENERECIPHER";
 
Console.WriteLine(s0 + "\n" + pw + "\n");
string s1 = v.encrypt(s0, pw, 1);
Console.WriteLine("Encrypted: " + s1);
s1 = v.encrypt(s1, "VIGENERECIPHER", -1);
Console.WriteLine("Decrypted: " + s1);
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}
</syntaxhighlight>
{{out}}
<pre>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
VIGENERECIPHER
 
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
using namespace std;
Line 504 ⟶ 784:
cout << "Encrypted: " << encrypted << endl;
cout << "Decrypted: " << decrypted << endl;
}</langsyntaxhighlight>
 
{{out}}
<pre>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
 
=={{header|C sharp|C#}}==
<lang csharp>
using System;
 
namespace VigenereCipher
{
class VCipher
{
public string encrypt(string txt, string pw, int d)
{
int pwi = 0, tmp;
string ns = "";
txt = txt.ToUpper();
pw = pw.ToUpper();
foreach (char t in txt)
{
if (t < 65) continue;
tmp = t - 65 + d * (pw[pwi] - 65);
if (tmp < 0) tmp += 26;
ns += Convert.ToChar(65 + ( tmp % 26) );
if (++pwi == pw.Length) pwi = 0;
}
 
return ns;
}
};
 
class Program
{
static void Main(string[] args)
{
VCipher v = new VCipher();
 
string s0 = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!",
pw = "VIGENERECIPHER";
 
Console.WriteLine(s0 + "\n" + pw + "\n");
string s1 = v.encrypt(s0, pw, 1);
Console.WriteLine("Encrypted: " + s1);
s1 = v.encrypt(s1, "VIGENERECIPHER", -1);
Console.WriteLine("Decrypted: " + s1);
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}
</lang>
{{out}}
<pre>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
VIGENERECIPHER
 
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
Line 570 ⟶ 794:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
function normalize(String text) => text.uppercased.filter(Character.letter);
Line 594 ⟶ 818:
print(encrypted);
print(decrypted);
}</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
This doesn't assume anything about character codes other than A-Z being a contiguous block (but still, we could be using EBCDIC. Who knows.)
<lang lisp>(defun strip (s)
(remove-if-not
(lambda (c) (char<= #\A c #\Z))
(string-upcase s)))
 
(defun vigenère (s key &key decipher
&aux (A (char-code #\A))
(op (if decipher #'- #'+)))
(labels
((to-char (c) (code-char (+ c A)))
(to-code (c) (- (char-code c) A)))
(let ((k (map 'list #'to-code (strip key))))
(setf (cdr (last k)) k)
(map 'string
(lambda (c)
(prog1
(to-char
(mod (funcall op (to-code c) (car k)) 26))
(setf k (cdr k))))
(strip s)))))
 
(let* ((msg "Beware the Jabberwock... The jaws that... the claws that catch!")
(key "vigenere cipher")
(enc (vigenère msg key))
(dec (vigenère enc key :decipher t)))
(format t "msg: ~a~%enc: ~a~%dec: ~a~%" msg enc dec))</lang>
{{out}}
<pre>msg: Beware the Jabberwock... The jaws that... the claws that catch!
enc: WMCEEIKLGRPIFVMEUGXXYILILZXYVBZLRGCEYAIOEKXIZGU
dec: BEWARETHEJABBERWOCKTHEJAWSTHATTHECLAWSTHATCATCH</pre>
 
=={{header|Clojure}}==
Requires Clojure 1.2.
<langsyntaxhighlight lang="clojure">(ns org.rosettacode.clojure.vigenere
(:require [clojure.string :as string]))
 
Line 659 ⟶ 850:
; decipher a text
(defn decrypt [ciphertext key] (crypt #'- ciphertext key))</langsyntaxhighlight>
 
Demonstration code:
<langsyntaxhighlight lang="clojure">(ns org.rosettacode.clojure.test-vigenere
(:require [org.rosettacode.clojure.vigenere :as vigenere]))
 
Line 673 ⟶ 864:
(doall (map (fn [[k v]] (printf "%9s: %s\n" k v))
[ ["Original" plaintext] ["Key" key] ["Encrypted" ciphertext] ["Decrypted" recovered] ])))
</syntaxhighlight>
</lang>
 
{{out}}
Line 683 ⟶ 874:
=={{header|CoffeeScript}}==
{{trans|D}}
<langsyntaxhighlight lang="coffeescript"># Simple helper since charCodeAt is quite long to write.
code = (char) -> char.charCodeAt()
 
Line 717 ⟶ 908:
console.log "Original : #{original}"
console.log "Encrypted : #{encrypted}"
console.log "Decrypted : #{decrypt encrypted, key}"</langsyntaxhighlight>
<pre>Original : Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Encrypted : WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted : BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
=={{header|Common Lisp}}==
====Main version====
This doesn't assume anything about character codes other than A-Z being a contiguous block (but still, we could be using EBCDIC. Who knows.)
<syntaxhighlight lang="lisp">(defun strip (s)
(remove-if-not
(lambda (c) (char<= #\A c #\Z))
(string-upcase s)))
 
(defun vigenère (s key &key decipher
&aux (A (char-code #\A))
(op (if decipher #'- #'+)))
(labels
((to-char (c) (code-char (+ c A)))
(to-code (c) (- (char-code c) A)))
(let ((k (map 'list #'to-code (strip key))))
(setf (cdr (last k)) k)
(map 'string
(lambda (c)
(prog1
(to-char
(mod (funcall op (to-code c) (car k)) 26))
(setf k (cdr k))))
(strip s)))))
 
(let* ((msg "Beware the Jabberwock... The jaws that... the claws that catch!")
(key "vigenere cipher")
(enc (vigenère msg key))
(dec (vigenère enc key :decipher t)))
(format t "msg: ~a~%enc: ~a~%dec: ~a~%" msg enc dec))</syntaxhighlight>
{{out}}
<pre>msg: Beware the Jabberwock... The jaws that... the claws that catch!
enc: WMCEEIKLGRPIFVMEUGXXYILILZXYVBZLRGCEYAIOEKXIZGU
dec: BEWARETHEJABBERWOCKTHEJAWSTHATTHECLAWSTHATCATCH</pre>
 
====Alternate version====
No string to circular list conversion here.
 
1. Program
 
<syntaxhighlight lang="lisp">(defconstant +a+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
 
(defun strip (s)
(string-upcase (remove-if-not 'alpha-char-p s)))
 
(defun vigenere (txt key &key plain &aux (p (if plain -1 1)))
(let ((txt (strip txt)) (key (strip key)) (i -1))
(map 'string
(lambda (c)
(setf i (mod (1+ i) (length key)))
(char +a+ (mod (+ (position c +a+) (* p (position (elt key i) +a+))) 26)))
txt)))</syntaxhighlight>
 
2. Execution
 
<pre>(vigenere "« Through the Looking-Glass »" "Lewis Carroll")
(vigenere "ELNWMIHKYSWZZOEVYILRJG" "Lewis Carroll" :plain t)</pre>
{{out}}
<pre>
"ELNWMIHKYSWZZOEVYILRJG"
"THROUGHTHELOOKINGGLASS"</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.string;
 
string encrypt(in string txt, in string key) pure @safe
Line 751 ⟶ 1,003:
immutable encoded = original.encrypt(key);
writeln(encoded, "\n", encoded.decrypt(key));
}</langsyntaxhighlight>
{{out}}
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Line 757 ⟶ 1,009:
 
===Alternative Version===
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.ascii, std.string, std.algorithm,
std.conv;
 
Line 783 ⟶ 1,035:
immutable encoded = original.encrypt(key);
writeln(encoded, "\n", encoded.decrypt(key));
}</langsyntaxhighlight>
The output is the same.
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
function UpperAlphaOnly(S: string): string;
{Remove all }
var I: integer;
begin
Result:='';
S:=UpperCase(S);
for I:=1 to Length(S) do
if S[I] in ['A'..'Z'] then Result:=Result+S[I];
end;
 
 
function VigenereEncrypt(Text, Key: string): string;
{Encrypt Text using specified key}
var KInx,TInx,I: integer;
var TC: byte;
begin
Result:='';
{Force Text and Key upper case}
Text:=UpperAlphaOnly(Text);
Key:=UpperAlphaOnly(Key);
{Point to first Key-character}
KInx:=1;
for I:=1 to Length(Text) do
begin
{Offset Text-char by key-char amount}
TC:=byte(Text[I])-byte('A')+Byte(Key[KInx]);
{if it is shifted past "Z", wrap back around past "A"}
if TC>Byte('Z') then TC:=byte('@')+(TC-Byte('Z'));
{Store in output string}
Result:=Result+Char(TC);
{Point to next Key-char}
Inc(Kinx);
{If index post end of key, start over}
if KInx>Length(Key) then KInx:=1;
end;
end;
 
 
function VigenereDecrypt(Text, Key: string): string;
{Encrypt Text using specified key}
var KInx,TInx,I: integer;
var TC: byte;
begin
Result:='';
{For Key and text uppercase}
Text:=UpperAlphaOnly(Text);
Key:=UpperAlphaOnly(Key);
KInx:=1;
for I:=1 to Length(Text) do
begin
{subtrack key-char from text-char}
TC:=byte(Text[I])-Byte(Key[Kinx])+Byte('A');
{if result below "A" wrap back around to "Z"}
if TC<Byte('A') then TC:=(byte('Z')-((Byte('A')-TC)))+1;
{store in result}
Result:=Result+Char(TC);
{Point to next key char}
Inc(Kinx);
{Past the end, start over}
if KInx>Length(Key) then KInx:=1;
end;
end;
 
const TestKey = 'VIGENERECIPHER';
const TestStr = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!';
 
 
procedure VigenereCipher(Memo: TMemo);
var S: string;
begin
{Show plain text}
Memo.Lines.Add(TestStr);
S:=VigenereEncrypt(TestStr, TestKey);
{Show encrypted text}
Memo.Lines.Add(S);
S:=VigenereDecrypt(S, TestKey);
{Show decrypted text}
Memo.Lines.Add(S);
end;
 
 
 
 
</syntaxhighlight>
{{out}}
<pre>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
 
Elapsed Time: 4.549 ms.
 
</pre>
 
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="easylang">
func$ encr txt$ pw$ d .
txt$[] = strchars txt$
for c$ in strchars pw$
pw[] &= strcode c$ - 65
.
for c$ in txt$[]
c = strcode c$
if c >= 97
c -= 32
.
if c >= 65 and c <= 97
pwi = (pwi + 1) mod1 len pw[]
c = (c - 65 + d * pw[pwi]) mod 26 + 65
r$ &= strchar c
.
.
return r$
.
s$ = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
pw$ = "VIGENERECIPHER"
r$ = encr s$ pw$ 1
print r$
print encr r$ pw$ -1
</syntaxhighlight>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 36.2.1x :
<langsyntaxhighlight lang="elena">import system'text.;
import system'math.culture;
import system'routines.math;
import extensions.system'routines;
import extensions;
 
class VCipher
{
literalstring encrypt(LiteralValuestring txt, LiteralValuestring pw, IntNumberint d)
[{
varauto output := new TextBuilder new.();
int pwi := 0.;
string literal $pwPW := pw upperCase.toUpper();
var TXT := txt.toUpper();
txt upperCase; forEach(:t)
[
if(t >= $65)
[
int tmp := t toInt - 65 + d * ($pw[pwi] toInt - 65).
if (tmp < 0)
[
tmp += 26
].
output write((65 + tmp mod:26) toChar).
pwi += 1.
if (pwi == $pw length) [ pwi := 0 ]
]
].
^ output literal
]
}
 
foreach(char t; in TXT)
program =
{
[
if (t < $65) $continue;
var v := VCipher new.
 
int tmp := t - 65 + d * (pw[pwi] - 65);
var s0 := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!".
if (tmp < 0) tmp += 26;
var pw := "VIGENERECIPHER".
output.write((65 + tmp.mod(26)).toChar());
pwi++;
console printLine(s0,'newLine,pw,'newLine).
var s1 := v encrypt if (s0,pwi pw,== 1)PW.Length) { pwi := 0 }
};
console printLine("Encrypted:",s1).
 
s1 := v encrypt(s1, "VIGENERECIPHER", -1).
^ output.Value
console printLine("Decrypted:",s1).
}
console printLine("Press any key to continue..").
}
console readKey.
].</lang>
public program()
{
var v := new VCipher();
var s0 := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
var pw := "VIGENERECIPHER";
console.printLine(s0,newLineConstant,pw,newLineConstant);
var s1 := v.encrypt(s0, pw, 1);
console.printLine("Encrypted:",s1);
s1 := v.encrypt(s1, "VIGENERECIPHER", -1);
console.printLine("Decrypted:",s1);
console.printLine("Press any key to continue..");
console.readChar()
}</syntaxhighlight>
{{out}}
<pre>
Line 849 ⟶ 1,229:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule VigenereCipher do
@base ?A
@size ?Z - @base + 1
Line 876 ⟶ 1,256:
IO.puts "Original: #{plaintext}"
IO.puts "Encrypted: #{ciphertext}"
IO.puts "Decrypted: #{recovered}"</langsyntaxhighlight>
 
{{out}}
Line 887 ⟶ 1,267:
=={{header|Erlang}}==
Erlang is not ideal for string manipulation, but with some utility function definitions it can express this fairly elegantly:
<langsyntaxhighlight lang="erlang">% Erlang implementation of Vigenère cipher
-module(vigenere).
-export([encrypt/2, decrypt/2]).
Line 933 ⟶ 1,313:
 
encrypt(Text, Key) -> crypt(Text, Key, fun encipher/2).
decrypt(Text, Key) -> crypt(Text, Key, fun decipher/2).</langsyntaxhighlight>
 
Demonstration code:
<langsyntaxhighlight lang="erlang">-module(testvigenere).
-import(vigenere,[encrypt/2, decrypt/2]).
main(_) ->
Line 942 ⟶ 1,322:
CipherText = encrypt("Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", Key),
RecoveredText = decrypt(CipherText, Key),
io:fwrite("Ciphertext: ~s~nDecrypted: ~s~n", [CipherText, RecoveredText]).</langsyntaxhighlight>
 
{{out}}
<pre>Ciphertext: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
module vigenere =
let keyschedule (key:string) =
let s = key.ToUpper().ToCharArray() |> Array.filter System.Char.IsLetter
let l = Array.length s
(fun n -> int s.[n % l])
 
let enc k c = ((c + k - 130) % 26) + 65
let dec k c = ((c - k + 130) % 26) + 65
let crypt f key = Array.mapi (fun n c -> f (key n) c |> char)
 
let encrypt key (plaintext:string) =
plaintext.ToUpper().ToCharArray()
|> Array.filter System.Char.IsLetter
|> Array.map int
|> crypt enc (keyschedule key)
|> (fun a -> new string(a))
 
let decrypt key (ciphertext:string) =
ciphertext.ToUpper().ToCharArray()
|> Array.map int
|> crypt dec (keyschedule key)
|> (fun a -> new string(a))
 
let passwd = "Vigenere Cipher"
let cipher = vigenere.encrypt passwd "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
let plain = vigenere.decrypt passwd cipher
printfn "%s\n%s" cipher plain
</syntaxhighlight>
 
<pre>C:\src\fsharp>fsi vigenere.fsx
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="text">USING: arrays ascii formatting kernel math math.functions
math.order sequences ;
IN: rosetta-code.vigenere-cipher
Line 978 ⟶ 1,394:
vigenere-decrypt "Decrypted: %s\n" printf ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 989 ⟶ 1,405:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program vigenere_cipher
implicit none
Line 1,050 ⟶ 1,466:
end do
end subroutine
end program</langsyntaxhighlight>
{{out}}
<pre> Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 1,056 ⟶ 1,472:
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
=={{header|F_Sharp|F#}}==
<lang fsharp>
module vigenere =
let keyschedule (key:string) =
let s = key.ToUpper().ToCharArray() |> Array.filter System.Char.IsLetter
let l = Array.length s
(fun n -> int s.[n % l])
 
=={{header|FreeBASIC}}==
let enc k c = ((c + k - 130) % 26) + 65
{{trans|Liberty BASIC}}
let dec k c = ((c - k + 130) % 26) + 65
<syntaxhighlight lang="freebasic">
let crypt f key = Array.mapi (fun n c -> f (key n) c |> char)
Function Filtrar(cadorigen As String) As String
Dim As String letra
Dim As String filtrado = ""
For i As Integer = 1 To Len(cadorigen)
letra = Ucase(Mid(cadorigen, i, 1))
If Instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", letra) Then filtrado += letra
Next i
Return filtrado
End Function
 
Function Encriptar(texto As String, llave As String) As String
let encrypt key (plaintext:string) =
texto = Filtrar(texto)
plaintext.ToUpper().ToCharArray()
Dim As String mSS, kSS, letra, cifrado = ""
|> Array.filter System.Char.IsLetter
Dim As Integer m, |>k, Array.mapc, intj = 1
For i As Integer |>= crypt1 encTo Len(keyschedule keytexto)
|>mSS = Mid(funtexto, ai, -> new string(a)1)
m = Asc(mSS) - Asc("A")
kSS = Mid(llave, j, 1)
k = Asc(kSS) - Asc("A")
j = (j Mod Len(llave)) + 1
c = (m + k) Mod 26
letra = Chr(Asc("A") + c)
cifrado += letra
Next i
Return cifrado
End Function
 
Function DesEncriptar(texto As String, llave As String) As String
let decrypt key (ciphertext:string) =
Dim As String mSS, kSS, letra, descifrado = ""
ciphertext.ToUpper().ToCharArray()
Dim As Integer m, |>k, Array.mapc, intj = 1
For i As Integer |>= crypt1 decTo Len(keyschedule keytexto)
|>mSS = Mid(funtexto, ai, -> new string(a)1)
m = Asc(mSS) - Asc("A")
kSS = Mid(llave, j, 1)
k = Asc(kSS) - Asc("A")
j = (j Mod Len(llave)) + 1
c = (m - k + 26) Mod 26
letra = Chr(Asc("A")+c)
descifrado += letra
Next i
Return descifrado
End Function
 
Dim Shared As String llave
let passwd = "Vigenere Cipher"
llave = Filtrar("vigenerecipher")
let cipher = vigenere.encrypt passwd "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
let plain = vigenere.decrypt passwd cipher
printfn "%s\n%s" cipher plain
</lang>
 
Dim As String cadorigen = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
<pre>C:\src\fsharp>fsi vigenere.fsx
Print cadorigen
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Print llave
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
 
Dim As String cadcifrada = Encriptar(cadorigen, llave)
Print " Cifrado: "; cadcifrada
Print "Descifrado: "; DesEncriptar(cadcifrada, llave)
Sleep
</syntaxhighlight>
{{out}}
<pre>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
VIGENERECIPHER
Cifrado: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Descifrado: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
 
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,161 ⟶ 1,609:
}
fmt.Println("Deciphered:", dt)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,173 ⟶ 1,621:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Char
import Text.Printf
 
Line 1,191 ⟶ 1,639:
convert = map toUpper . filter isLetter
 
main :: IO ()
main = do
let key = "VIGENERECIPHER"
Line 1,198 ⟶ 1,647:
decr = decrypt key encr
printf " Input: %s\n Key: %s\nEncrypted: %s\nDecrypted: %s\n"
text key encr decr</langsyntaxhighlight>
{{out}}
<pre>
Line 1,208 ⟶ 1,657:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
ptext := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
write("Key = ",ekey := "VIGENERECIPHER")
Line 1,231 ⟶ 1,680:
}
return ctext
end</langsyntaxhighlight>
 
The following helper procedures will be of general use with classical cryptography tasks.
<syntaxhighlight lang="icon">
<lang Icon>
link strings
 
Line 1,247 ⟶ 1,696:
text ? (s := "", until pos(0) do s ||:= " " || move(5)|tab(0))
return s[2:0]
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,261 ⟶ 1,710:
=={{header|J}}==
'''Solution:'''<br>
Using [https://github.com/jsoftware/convert_misc/blob/master/vig.ijs <code>vig</code>] from the [[j:Addons/convert/misc/vig|convert/misc/vig addon]]:
<syntaxhighlight lang="j">ALPHA=: (65,:26) ];.0 a. NB. Character Set
<lang j>NB.*vig c Vigenère cipher
NB. cipher=. key 0 vig charset plain
NB. plain=. key 1 vig charset cipher
vig=: conjunction define
:
r=. (#y) $ n i.x
n {~ (#n) | (r*_1^m) + n i.y
)
 
ALPHA=: (65,:26) ];.0 a. NB. Character Set
preprocess=: (#~ e.&ALPHA)@toupper NB. force uppercase and discard non-alpha chars
vigEncryptRC=: 0 vig ALPHA preprocess
vigDecryptRC=: 1 vig ALPHA preprocess</langsyntaxhighlight>
'''Example Use:'''
<langsyntaxhighlight lang="j"> 'VIGENERECIPHER' vigEncryptRC 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
'VIGENERECIPHER' vigDecryptRC 'WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY'
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|D}}
<langsyntaxhighlight lang="java">public class VigenereCipher {
public static void main(String[] args) {
String key = "VIGENERECIPHER";
Line 1,316 ⟶ 1,756:
return res;
}
}</langsyntaxhighlight>
 
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
===Alternative Version===
<syntaxhighlight lang="java">
import com.google.common.collect.Streams;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.nio.charset.StandardCharsets.US_ASCII;
 
public class VigenereCipher {
private final static int LOWER = 'A';
private final static int UPPER = 'Z';
private final static int SIZE = UPPER - LOWER + 1;
private final Supplier<Stream<Character>> maskStream;
 
public VigenereCipher(final String key) {
final String mask = new String(key.getBytes(US_ASCII)).toUpperCase();
maskStream = () ->
Stream.iterate(0, i -> (i+1) % mask.length()).map(mask::charAt);
}
 
private String transform(final String text, final boolean encode) {
final Stream<Integer> textStream = text.toUpperCase().chars().boxed()
.filter(i -> i >= LOWER && i <= UPPER);
return Streams.zip(textStream, maskStream.get(), (c, m) ->
encode ? c + m - 2 * LOWER : c - m + SIZE)
.map(c -> Character.toString(c % SIZE + LOWER))
.collect(Collectors.joining());
}
 
public String encrypt(final String plaintext) {
return transform(plaintext,true);
}
 
public String decrypt(final String ciphertext) {
return transform(ciphertext,false);
}
}
 
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
 
class VigenereCipherTest {
private static final VigenereCipher Vigenere = new VigenereCipher("VIGENERECIPHER");
 
@Test
@DisplayName("encipher/decipher round-trip succeeds")
void vigenereCipherTest() {
final String input = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
final String expectEncrypted = "WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY";
final String expectDecrypted = "BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH";
 
final String ciphertext = Vigenere.encrypt(input);
assertEquals(expectEncrypted, ciphertext);
 
final String plaintext = Vigenere.decrypt(ciphertext);
assertEquals(expectDecrypted, plaintext);
}
 
}
</syntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">// helpers
// helper
function ordA(a) {
Line 1,345 ⟶ 1,846:
 
console.log(enc);
console.log(dec);</langsyntaxhighlight>
 
=={{header|Juliajq}}==
{{works with|Julia|0.6jq}}
'''Works with gojq, the Go implementation of jq'''
<lang Julia>function encrypt(msg::AbstractString, key::AbstractString)
<syntaxhighlight lang="jq">def vigenere(text; key; encryptp):
msg = uppercase(join(filter(isalpha, collect(msg))))
# retain alphabetic characters only
key = uppercase(join(filter(isalpha, collect(key))))
def n:
msglen = length(msg)
ascii_upcase | explode | map(select(65 <= . and . <= 90)) | [., length];
keylen = length(key)
(text | n) as [$xtext, $length]
| (key | n) as [$xkey, $keylength]
| reduce range(0; $length) as $i (null;
($i % $keylength) as $ki
| . + [if encryptp
then (($xtext[$i] + $xkey[$ki] - 130) % 26) + 65
else (($xtext[$i] - $xkey[$ki] + 26) % 26) + 65
end] )
| implode;
 
# Input: sample text
if keylen < msglen
def example($key):
key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen]
vigenere(.; $key; true)
end
| . as $encoded
| ., vigenere($encoded; $key; false) ;
 
"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
enc = Vector{Char}(msglen)
| (., example("VIGENERECIPHER")),
"",
(., example("ROSETTACODE"))</syntaxhighlight>
{{out}}
<pre>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
 
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
@inbounds for i in 1:length(msg)
SSOEKXTJSMESPWVPHCMABWFBLLXCAYGWLRHTMMXTJSFPRKKXATTEOWGY
enc[i] = Char((Int(msg[i]) + Int(key[i]) - 130) % 26 + 65)
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
end
 
=={{header|Jsish}}==
return join(enc)
From Javascript entry.
end
<syntaxhighlight lang="javascript">/* Vigenère cipher, in Jsish */
"use strict";
 
function ordA(a:string):number {
function decrypt(enc::AbstractString, key::AbstractString)
return a.charCodeAt(0) - 65;
enc = uppercase(join(filter(isalpha, collect(enc))))
}
key = uppercase(join(filter(isalpha, collect(key))))
msglen = length(enc)
// vigenere
keylen = length(key)
function vigenereCipher(text:string, key:string, decode:boolean=false):string {
var i = 0, b;
key = key.toUpperCase().replace(/[^A-Z]/g, '');
return text.toUpperCase().replace(/[^A-Z]/g, '').replace(/[A-Z]/g,
function(a:string, idx:number, str:string) {
b = key[i++ % key.length];
return String.fromCharCode(((ordA(a) + (decode ? 26 - ordA(b) : ordA(b))) % 26 + 65));
});
}
 
provide('vigenereCipher', 1);
if keylen < msglen
key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen]
end
 
if (Interp.conf('unitTest')) {
msg = Vector{Char}(msglen)
var text = "The quick brown fox Jumped over the lazy Dog the lazy dog lazy dog dog";
var key = 'jsish';
var enc = vigenereCipher(text, key);
; text;
; enc;
; vigenereCipher(enc, key, true);
}
 
/*
@inbounds for i in 1:length(enc)
=!EXPECTSTART!=
msg[i] = Char((Int(enc[i]) - Int(key[i]) + 26) % 26 + 65)
text ==> The quick brown fox Jumped over the lazy Dog the lazy dog lazy dog dog
end
enc ==> CZMIBRUSTYXOVXVGBCEWNVWNLALPWSJRGVVPLPWSJRGVVPDIRFMGOVVP
vigenere(enc, key, true) ==> THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGTHELAZYDOGLAZYDOGDOG
=!EXPECTEND!=
*/</syntaxhighlight>
 
{{out}}
return join(msg)
<pre>prompt$ jsish -u vigenereCipher.jsi
end
[PASS] vigenereCipher.jsi</pre>
 
const messages = ("Attack at dawn.", "Don't attack.", "The war is over.")
const key = "LEMON"
 
=={{header|Julia}}==
for msg in messages
{{works with|Julia|1.5}}
enc = encrypt(msg, key)
<syntaxhighlight lang="julia">
dec = decrypt(enc, key)
→(a::Char, b::Char, ± = +) = 'A'+((a-'A')±(b-'A')+26)%26
println("Original: $msg\n -> encrypted: $enc\n -> decrypted: $dec")
←(a::Char, b::Char) = →(a,b,-)
end</lang>
 
cleanup(str) = filter(a-> a in 'A':'Z', collect(uppercase.(str)))
match_length(word, len) = repeat(word,len)[1:len]
 
function →(message::String, codeword::String, ↔ = →)
plaintext = cleanup(message)
key = match_length(cleanup(codeword),length(plaintext))
return String(plaintext .↔ key)
end
←(message::String, codeword::String) = →(message,codeword,←)
 
cyphertext = "I want spearmint gum" → "Gimme!"
println(cyphertext)
println(cyphertext ← "Gimme!")
</syntaxhighlight>
 
{{out}}
 
<pre>
<pre>Original: Attack at dawn.
"OEMZXYXQMVSQZFKAU"
-> encrypted: LXFOPVEFRNHR
"IWANTSPEARMINTGUM"
-> decrypted: ATTACKATDAWN
</pre>
Original: Don't attack.
-> encrypted: OSZHNEXMQX
-> decrypted: DONTATTACK
Original: The war is over.
-> encrypted: ELQKNCMECIPV
-> decrypted: THEWARISOVER</pre>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
fun vigenere(text: String, key: String, encrypt: Boolean = true): String {
Line 1,434 ⟶ 1,983:
val decoded = vigenere(encoded, key, false)
println(decoded)
}</langsyntaxhighlight>
 
{{out}}
Line 1,441 ⟶ 1,990:
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
 
=={{header|Lambdatalk}}==
Only texts in uppercases [A-Z] and spaces.
<syntaxhighlight lang="scheme">
{def vigenere
{def vigenere.map
{lambda {:code :key :txt}
{S.map
{{lambda {:code :txt :key :i}
{W.code2char
{+ {% {+ {W.char2code {W.get :i :txt}}
{if :code
then {W.char2code {W.get {% :i {W.length :key}} :key}}
else {- 26 {W.char2code {W.get {% :i {W.length :key}} :key}}} }}
26}
65}} } :code :txt :key}
{S.serie 0 {- {W.length :txt} 1}}} }}
{lambda {:code :key :txt}
{S.replace \s by in {vigenere.map :code :key {S.replace \s by in :txt}}} }}
-> vigenere
 
1) encode: {vigenere true LEMON ATTACK AT DAWN}
-> LXFOPVEFRNHR
 
2) decode: {vigenere false LEMON LXFOPVEFRNHR}
-> ATTACKATDAWN
 
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
ori$ = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
key$ = filter$("vigenerecipher")
Line 1,494 ⟶ 2,071:
next
end function
</syntaxhighlight>
</lang>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
VIGENERECIPHER
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function Encrypt( _msg, _key )
local msg = { _msg:upper():byte( 1, -1 ) }
local key = { _key:upper():byte( 1, -1 ) }
Line 1,543 ⟶ 2,120:
 
print( encrypted )
print( decrypted )</langsyntaxhighlight>
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">encode[text_String, key_String] :=
Module[{textCode, keyCode},
textCode =
Line 1,578 ⟶ 2,155:
keyCode[[;; Length@textCode]],
PadRight[keyCode, Length@textCode, keyCode]];
FromCharacterCode[Mod[textCode - keyCode, 26] + 65]]</langsyntaxhighlight>
 
<pre>key = "Vigenere Cipher";
Line 1,594 ⟶ 2,171:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 1,746 ⟶ 2,323:
return melancholy_dane
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,820 ⟶ 2,397:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
proc encrypt(msg, key: string): string =
proc isAlpha(c): bool = c in 'a'..'z' or c in 'A'..'Z'
 
proc encrypt(msg, key): string =
result = ""
var pos = 0
for c in msg:
if isAlpha c in Letters:
result.add chr(((ord(key[pos]) + ord(toUpper c.toUpperAscii)) mod 26) + ord('A'))
pos = (pos + 1) mod key.len
 
proc decrypt(msg, key: string): string =
result = ""
var pos = 0
for c in msg:
Line 1,847 ⟶ 2,420:
echo text
echo encr
echo decr</langsyntaxhighlight>
 
{{out}}
<pre>Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 1,855 ⟶ 2,429:
=={{header|Objeck}}==
{{trans|D}}
<langsyntaxhighlight lang="objeck">
bundle Default {
class VigenereCipher {
Line 1,901 ⟶ 2,475:
}
}
</syntaxhighlight>
</lang>
<pre>
encrypt: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Line 1,910 ⟶ 2,484:
{{trans|C}}
 
<langsyntaxhighlight lang="ocaml">let cipher src key crypt =
let str = String.uppercase src in
let key = String.uppercase key in
Line 1,950 ⟶ 2,524:
Printf.printf "Code: %s\n" cod;
Printf.printf "Back: %s\n" dec;
;;</langsyntaxhighlight>
 
Run:
Line 1,959 ⟶ 2,533:
Code: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Back: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
----
 
Updated version by [http://rosettacode.org/wiki/User:Vanyamil User:Vanyamil]
 
This is a custom, more functional version of the existing solution, due to
'''[https://ocaml.org/api/String.html OCaml 4.05's unsafe-string compatibility mode]'''
 
{{works with|OCaml|4.05 or above}}
<syntaxhighlight lang="ocaml">
(* Task : Vigenère_cipher *)
 
(* This is a custom, more functional version of an existing solution,
due to OCaml 4.05's unsafe-string compatibility mode:
https://ocaml.org/api/String.html
*)
 
(*** Helpers ***)
 
(* Verbose type abbreviation *)
type key = string
 
(* Rotate a single uppercase letter *)
let ascii_caesar_shift : bool -> char -> char -> char =
let min_range = Char.code 'A' in
let max_range = Char.code 'Z' in
(* aka 26 but this code can be adapted to larger ranges, such as the ASCII printable range (codes 32 to 126). *)
let range_len = max_range - min_range + 1 in
let actual_fun (dir : bool) (c1 : char) (c2 : char) : char =
let n1 = Char.code c1 in
let n2 = Char.code c2 - min_range in
let sum = (if dir then (+) else (-)) n1 n2 in
( (* Effectively mod function, but simplified and works on negatives. *)
if sum > max_range
then sum - range_len
else if sum < min_range
then sum + range_len
else sum
) |> Char.chr
in
actual_fun
 
(* Remove non-letters and uppercase *)
let ascii_upper_letters_only (s : string) : string =
let slen = String.length s in
(* Make a list of escaped uppercase letter chars *)
let rec toLetterList sidx acc =
if sidx >= slen
then List.rev acc
else
let c = s.[sidx] in
if c >= 'A' && c <= 'Z'
then toLetterList (sidx + 1) ((c |> Char.escaped) :: acc)
else if c >= 'a' && c <= 'z'
then toLetterList (sidx + 1) ((c |> Char.uppercase_ascii |> Char.escaped) :: acc)
else toLetterList (sidx + 1) acc
in
toLetterList 0 [] |> String.concat ""
 
(*** Actual task at hand ***)
 
let vig_crypt (dir : bool) (key : key) (message : string) : string =
let message = ascii_upper_letters_only message in
let key = ascii_upper_letters_only key in
let klen = String.length key in
let aux idx c =
let kidx = idx mod klen in
let e = ascii_caesar_shift dir c key.[kidx] in
e
in
String.mapi aux message
 
let encrypt : key -> string -> string = vig_crypt true
let decrypt : key -> string -> string = vig_crypt false
 
(*** Output ***)
 
let () =
let str = "Beware the Jabberwock, my son! The jaws that bite, \
the claws that catch!" in
let key = "VIGENERECIPHER" in
let ct = encrypt key str in
let pt = decrypt key ct in
Printf.printf "Text: %s\n" str;
Printf.printf "Key: %s\n" key;
Printf.printf "Code: %s\n" ct;
Printf.printf "Back: %s\n" pt
;;
</syntaxhighlight>
{{out}}
<pre>
Text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Key: VIGENERECIPHER
Code: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Back: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
 
=={{header|ooRexx}}==
{{trans|NetRexx}}
A reworking of the [[#NetRexx|NetRexx]] version using Open Object Rexx but shouldn't take much to translate to Classic Rexx.
<langsyntaxhighlight REXXlang="rexx">/* Rexx */
Do
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Line 2,157 ⟶ 2,827:
End
Exit
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,231 ⟶ 2,901:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">
// The Vigenere cipher in reasonably standard Pascal
// <no library functions: all conversions hand-coded>
Line 2,336 ⟶ 3,006:
END.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,348 ⟶ 3,018:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">if( @ARGV != 3 ){
printHelp();
}
Line 2,387 ⟶ 3,057:
}
return $cipher;
}</langsyntaxhighlight>
 
Demonstration:
Line 2,407 ⟶ 3,077:
Decrypting:
perl cipher.pl DEC (cipher text) (key)</pre>
 
=={{header|Perl 6}}==
{{Works with|rakudo|2015-11-14}}
<lang perl6>sub s2v ($s) { $s.uc.comb(/ <[ A..Z ]> /)».ord »-» 65 }
sub v2s (@v) { (@v »%» 26 »+» 65)».chr.join }
 
sub blacken ($red, $key) { v2s(s2v($red) »+» s2v($key)) }
sub redden ($blk, $key) { v2s(s2v($blk) »-» s2v($key)) }
 
my $red = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
my $key = "Vigenere Cipher!!!";
 
say $red;
say my $black = blacken($red, $key);
say redden($black, $key);</lang>
{{out}}
<pre>Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
This is a natural job for hyperoperators, which can vectorize any operator.
For infix operators the pointy end indicates which side to "dwim", repeating
elements on that side until the other side runs out. In particular, repeating
the key naturally falls out of this cyclic dwimmery, as does repeating the various constants to be applied with any of several operations to every element of the list. Factoring out the canonicalization and decanonicalization lets us see quite clearly that the only difference between encryption and decryptions is the sign of the vector addition/subtraction. Since hyperops are inherently parallelizable, this algorithm might run well in your GPU.
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>enum type mode ENCRYPT = +1, DECRYPT = -1 end type
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
<span style="color: #008080;">constant</span> <span style="color: #000000;">ENCRYPT</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span>
function Vigenere(string s, string key, mode m)
<span style="color: #000000;">DECRYPT</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
string res = ""
integer k = 1, ch
<span style="color: #008080;">function</span> <span style="color: #000000;">Vigenere</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">mode</span><span style="color: #0000FF;">)</span>
s = upper(s)
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
for i=1 to length(s) do
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ch</span>
ch = s[i]
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
if ch>='A' and ch<='Z' then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
res &= 'A'+mod(ch+m*(key[k]+26),26)
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
k = mod(k,length(key))+1
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">'A'</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">'Z'</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">'A'</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">+</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">key</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">26</span><span style="color: #0000FF;">),</span><span style="color: #000000;">26</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">key</span><span style="color: #0000FF;">))+</span><span style="color: #000000;">1</span>
return res
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
constant key = "LEMON",
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
s = "ATTACK AT DAWN",
e = Vigenere(s,key,ENCRYPT),
<span style="color: #008080;">constant</span> <span style="color: #000000;">key</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"LEMON"</span><span style="color: #0000FF;">,</span>
d = Vigenere(e,key,DECRYPT)
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"ATTACK AT DAWN"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">Vigenere</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ENCRYPT</span><span style="color: #0000FF;">),</span>
printf(1,"Original: %s\nEncrypted: %s\nDecrypted: %s\n",{s,e,d})</lang>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">Vigenere</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">DECRYPT</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Original: %s\nEncrypted: %s\nDecrypted: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 2,463 ⟶ 3,114:
=={{header|PHP}}==
{{trans|C}}
<langsyntaxhighlight PHPlang="php"><?php
 
$str = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
Line 2,508 ⟶ 3,159:
 
?>
</syntaxhighlight>
</lang>
{{out}}
<pre>Text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 2,516 ⟶ 3,167:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de vigenereKey (Str)
(extract
'((C)
Line 2,537 ⟶ 3,188:
(char (+ 65 (% (+ 26 (- C K)) 26))) )
(vigenereKey Str)
(apply circ (vigenereKey Key)) ) ) )</langsyntaxhighlight>
Test:
<pre>: (vigenereEncrypt
Line 2,548 ⟶ 3,199:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
cypher: procedure options (main); /* 21 September 2012 */
declare t(26) character (26);
Line 2,593 ⟶ 3,244:
end;
end cypher;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,602 ⟶ 3,253:
 
=={{header|PowerShell}}==
<langsyntaxhighlight Powershelllang="powershell"># Author: D. Cudnohufsky
function Get-VigenereCipher
{
Line 2,686 ⟶ 3,337:
$OutText = $null
}
}</langsyntaxhighlight>
Usage examples:
<pre>
Line 2,699 ⟶ 3,350:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure prepString(text.s, Array letters(1))
;convert characters to an ordinal (0-25) and remove non-alphabetic characters,
;returns dimension size of result array letters()
Line 2,759 ⟶ 3,410:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre> Plain text = "The quick brown fox jumped over the lazy dogs."
Line 2,766 ⟶ 3,417:
 
=={{header|Python}}==
{{Works with|Python|3}}
{{trans|Haskell}}
<syntaxhighlight lang="python">'''Vigenere encryption and decryption'''
<lang python>
 
from itertools import starmap, cycle
 
 
def encrypt(message, key):
'''Vigenere encryption of message using key.'''
 
# convertConverted to uppercase.
# strip out nonNon-alpha characters stripped out.
message = filter(str.isalpha, message.upper())
 
def enc(c, k):
# single letter encrpytion.
'''Single letter encryption.'''
def enc(c,k): return chr(((ord(k) + ord(c) - 2*ord('A')) % 26) + ord('A'))
 
return chr(((ord(k) + ord(c) - 2 * ord('A')) % 26) + ord('A'))
 
return ''.join(starmap(enc, zip(message, cycle(key))))
 
return "".join(starmap(enc, zip(message, cycle(key))))
 
def decrypt(message, key):
'''Vigenere decryption of message using key.'''
 
def dec(c, k):
# single letter decryption.
'''Single letter decryption.'''
def dec(c,k): return chr(((ord(c) - ord(k) - 2*ord('A')) % 26) + ord('A'))
 
return "".joinchr(starmap(dec,(ord(c) zip- ord(message,k) cycle- 2 * ord(key'A')) % 26) + ord('A'))
</lang>
Demonstrating:
<lang python>
text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
key = "VIGENERECIPHER"
 
return ''.join(starmap(dec, zip(message, cycle(key))))
encr = encrypt(text, key)
decr = decrypt(encr, key)
 
 
print text
def main():
print encr
'''Demonstration'''
print decr
 
</lang>
text = 'Beware the Jabberwock, my son! The jaws that bite, ' + (
'the claws that catch!'
)
key = 'VIGENERECIPHER'
 
encr = encrypt(text, key)
decr = decrypt(encr, key)
 
print(text)
print(encr)
print(decr)
 
 
if __name__ == '__main__':
main()
</syntaxhighlight>
{{out}}
<pre>Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
<pre>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ [] swap witheach
[ upper
dup char A char Z 1+ within
iff join else drop ] ] is onlycaps ( $ --> $ )
 
[ onlycaps
[] swap witheach
[ char A - join ] ] is cipherdisk ( $ --> [ )
 
[ [] swap witheach
[ 26 swap - join ] ] is deciphering ( [ --> [ )
 
[ behead tuck join swap ] is nextkey ( [ --> [ n )
 
[ dip nextkey + dup
char Z > if [ 26 - ] ] is encryptchar ( [ c --> [ c )
[ $ "" swap rot
onlycaps witheach
[ encryptchar
swap dip join ]
drop ] is vigenere ( $ [ --> $ )
 
[ cipherdisk vigenere ] is encrypt ( $ $ --> $ )
 
[ cipherdisk deciphering vigenere ] is decrypt ( $ $ --> $ )
 
$ "If you reveal your secrets to the wind, you should "
$ "not blame the wind for revealing them to the trees." join
say "Encrypted: " $ "Kahlil Gibran" encrypt dup echo$ cr
say "Decrypted: " $ "Kahlil Gibran" decrypt echo$</syntaxhighlight>
 
{{out}}
 
<pre>Encrypted: SFFZCCKDFRLLYUYDMNXMUJTBDHLHQYJGPLSUYUSOVZZJMRMRDHLHQYJNPIRRFEHWQYMBIVMGYTOPBCKMT
Decrypted: IFYOUREVEALYOURSECRETSTOTHEWINDYOUSHOULDNOTBLAMETHEWINDFORREVEALINGTHEMTOTHETREES</pre>
 
=={{header|R}}==
<langsyntaxhighlight lang="r">mod1 = function(v, n)
# mod1(1:20, 6) => 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2
((v - 1) %% n) + 1
Line 2,825 ⟶ 3,533:
# WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
message(vigen("WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY", "vigenerecipher", decrypt = T))
# BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define chr integer->char)
Line 2,850 ⟶ 3,558:
"VIGENERECIPHER")
"VIGENERECIPHER")
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="racket">
"BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH"
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2015-11-14}}
<syntaxhighlight lang="raku" line>sub s2v ($s) { $s.uc.comb(/ <[ A..Z ]> /)».ord »-» 65 }
sub v2s (@v) { (@v »%» 26 »+» 65)».chr.join }
 
sub blacken ($red, $key) { v2s(s2v($red) »+» s2v($key)) }
sub redden ($blk, $key) { v2s(s2v($blk) »-» s2v($key)) }
 
my $red = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
my $key = "Vigenere Cipher!!!";
 
say $red;
say my $black = blacken($red, $key);
say redden($black, $key);</syntaxhighlight>
{{out}}
<pre>Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
This is a natural job for hyperoperators, which can vectorize any operator.
For infix operators the pointy end indicates which side to "dwim", repeating
elements on that side until the other side runs out. In particular, repeating
the key naturally falls out of this cyclic dwimmery, as does repeating the various constants to be applied with any of several operations to every element of the list. Factoring out the canonicalization and decanonicalization lets us see quite clearly that the only difference between encryption and decryptions is the sign of the vector addition/subtraction. Since hyperops are inherently parallelizable, this algorithm might run well in your GPU.
 
=={{header|Red}}==
note: this program is much longer than it needed to be - because i couldn't resist
to add some more features to make it actually "useful" :-) So not only can u encrypt any character (because the crypted message will be base 64 encoded), but it also includes a Gui.
the Gui window has buttons to access the clipboard too - so u can get the original text from clipboard and put the crypted message back again. To execute it,simply download the latest red.exe (about 1,1 MB size! ) from red-lang.org. This program can also be compiled to an .exe (+ red runtime.dll ) by simply execute <pre>red.exe -c vign1.red</pre> or <pre>red.exe -r vign1.red</pre> which creates a single .exe file whithout the need for any .dll . should be working on windows , linux ( under wine ) and mac OS.
<langsyntaxhighlight Redlang="red">Red [needs: 'view]
 
CRLF: copy "^M^/" ;; constant for 0D 0A line feed
Line 2,936 ⟶ 3,669:
pad 270x1 button "Quit " [quit]
]
</syntaxhighlight>
</lang>
{{output}}
the message <pre>Beware the Jabberwock, my son! The jaws that bite, the claws that catch!</pre> with key "VIGENERECIPHER" translates to <pre>i6y8r7e3ZbextWiPs7irrLfFtLWwb2m9wWXFxbdo
Line 2,944 ⟶ 3,677:
=={{header|REXX}}==
===uppercase text only===
<langsyntaxhighlight lang="rexx">/*REXX program encrypts (and displays) uppercased text using the Vigenère cypher.*/
@.1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
L=length(@.1)
Line 2,970 ⟶ 3,703:
dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1 )
end /*j*/
return dMsg</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default internal fields:}}
<pre>
Line 2,983 ⟶ 3,716:
Additional characters can be added by simply appending them to the &nbsp; <big>'''@.1'''</big> &nbsp; variable.
<langsyntaxhighlight lang="rexx">/*REXX program encrypts (and displays) most text using the Vigenère cypher. */
@abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU
@.1 = @abcU || @abc'0123456789~`!@#$%^&*()_-+={}|[]\:;<>?,./" '''
Line 3,009 ⟶ 3,742:
dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1 )
end /*j*/
return dMsg</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default internal fields:}}
<pre>
Line 3,018 ⟶ 3,751:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Vigenère cipher
 
Line 3,064 ⟶ 3,797:
next
return a
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,071 ⟶ 3,804:
ciphertext = LXFOPVEFRNHR
decrypted = ATTACKATDAWN
</pre>
 
=={{header|RPL}}==
As the encoding and decoding programs would differ by only one instruction (plus instead of minus), they have been merged into a single function that decodes if the input text is in uppercase only, and encodes otherwise. To encode a uppercase-only text, a space (or any punctuation sign) must be put somwehere.
≪ → key
≪ 1 CF { }
1 3 PICK SIZE '''FOR''' j
OVER j DUP SUB NUM
'''IF''' DUP 97 ≥ OVER 122 ≤ AND '''THEN''' 32 - '''END'''
'''IF''' DUP 65 ≥ OVER 90 ≤ AND '''THEN''' 65 - + '''ELSE''' 1 SF DROP '''END'''
'''NEXT'''
SWAP DROP ""
1 3 PICK SIZE '''FOR''' j
OVER j GET
key j 1 - key SIZE MOD 1 + DUP SUB NUM 64 -
'''IF''' 1 FC? '''THEN''' + '''ELSE''' - '''END'''
26 MOD 65 + CHR +
'''NEXT'''
SWAP DROP
≫ ≫ ‘<span style="color:blue">VIGENERE</span>’ STO
 
"Beware the Jabberwock!" <span style="color:blue">VIGENERE</span>
DUP <span style="color:blue">VIGENERE</span>
{{out}}
<pre>
2: "FVPVDZBCIATWNZZRSTD"
1: "BEWARETHEJABBERWOCK"
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight Rubylang="ruby">module VigenereCipher
BASE = 'A'.ord
Line 3,096 ⟶ 3,856:
end
end</langsyntaxhighlight>
 
Demonstration:
 
<langsyntaxhighlight Rubylang="ruby">include VigenereCipher
 
plaintext = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'
Line 3,109 ⟶ 3,869:
puts "Original: #{plaintext}"
puts "Encrypted: #{ciphertext}"
puts "Decrypted: #{recovered}"</langsyntaxhighlight>
 
{{out}}
Line 3,119 ⟶ 3,879:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::ascii::AsciiExt;
 
static A: u8 = 'A' as u8;
Line 3,167 ⟶ 3,927:
let decoded = vigenere(key, &encoded, false);
println!("Back: {}", decoded);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
Valid characters for messages: A through Z, zero, 1 to 9, and full-stop (.)
<langsyntaxhighlight lang="scala">
object Vigenere {
def encrypt(msg: String, key: String) : String = {
Line 3,206 ⟶ 3,966:
println("Encrypt text ABC => " + Vigenere.encrypt("ABC", "KEY"))
println("Decrypt text KFA => " + Vigenere.decrypt("KFA", "KEY"))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,213 ⟶ 3,973:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func string: vigenereCipher (in string: source, in var string: keyword) is func
Line 3,263 ⟶ 4,023:
decrypted := vigenereDecipher(encrypted, keyword);
writeln("Decrypted: " <& decrypted);
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,274 ⟶ 4,034:
 
=={{header|Sidef}}==
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="ruby">func s2v(s) { s.uc.scan(/[A-Z]/).map{.ord} »-» 65 }
func v2s(v) { v »%» 26 »+» 65 -> map{.chr}.join }
 
Line 3,286 ⟶ 4,046:
say red
say (var black = blacken(red, key))
say redden(black, key)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,297 ⟶ 4,057:
in the following code, the cypher should consist of upper-case characters only. If that is not guaranteed, apply prep to it before passing it to encrypt/decrypt..
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">
prep := [:s | s select:[:ch | ch isLetter] thenCollect:[:ch | ch asUppercase]].
encrypt := [:s :cypher | (prep value:s) keysAndValuesCollect:[:i :ch | ch rot:((cypher at:((i-1)\\key size+1))-$A) ]].
decrypt := [:s :cypher | (prep value:s) keysAndValuesCollect:[:i :ch | ch rot:26-((cypher at:((i-1)\\key size+1))-$A) ]].
</syntaxhighlight>
</lang>
Test:
<langsyntaxhighlight lang="smalltalk">
plain := 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'.
cypher := 'VIGENERECIPHER'.
Line 3,311 ⟶ 4,071:
crypted -> 'WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY'
plain2 -> 'BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH'
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
 
Can support a larger range of characters, if desired
 
<syntaxhighlight lang="swift">public func convertToUnicodeScalars(
str: String,
minChar: UInt32,
maxChar: UInt32
) -> [UInt32] {
var scalars = [UInt32]()
 
for scalar in str.unicodeScalars {
let val = scalar.value
 
guard val >= minChar && val <= maxChar else {
continue
}
 
scalars.append(val)
}
 
return scalars
}
 
public struct Vigenere {
private let keyScalars: [UInt32]
private let smallestScalar: UInt32
private let largestScalar: UInt32
private let sizeAlphabet: UInt32
 
public init?(key: String, smallestCharacter: Character = "A", largestCharacter: Character = "Z") {
let smallScalars = smallestCharacter.unicodeScalars
let largeScalars = largestCharacter.unicodeScalars
 
guard smallScalars.count == 1, largeScalars.count == 1 else {
return nil
}
 
self.smallestScalar = smallScalars.first!.value
self.largestScalar = largeScalars.first!.value
self.sizeAlphabet = (largestScalar - smallestScalar) + 1
 
let scalars = convertToUnicodeScalars(str: key, minChar: smallestScalar, maxChar: largestScalar)
 
guard !scalars.isEmpty else {
return nil
}
 
self.keyScalars = scalars
 
}
 
public func decrypt(_ str: String) -> String? {
let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)
 
guard !txtBytes.isEmpty else {
return nil
}
 
var res = ""
 
for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar {
guard let char =
UnicodeScalar((c &+ sizeAlphabet &- keyScalars[i % keyScalars.count]) % sizeAlphabet &+ smallestScalar)
else {
return nil
}
 
res += String(char)
}
 
return res
}
 
public func encrypt(_ str: String) -> String? {
let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)
 
guard !txtBytes.isEmpty else {
return nil
}
 
var res = ""
 
for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar {
guard let char =
UnicodeScalar((c &+ keyScalars[i % keyScalars.count] &- 2 &* smallestScalar) % sizeAlphabet &+ smallestScalar)
else {
return nil
}
 
res += String(char)
}
 
return res
}
}
 
let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
let key = "VIGENERECIPHER";
let cipher = Vigenere(key: key)!
 
print("Key: \(key)")
print("Plain Text: \(text)")
 
let encoded = cipher.encrypt(text.uppercased())!
 
print("Cipher Text: \(encoded)")
 
let decoded = cipher.decrypt(encoded)!
 
print("Decoded: \(decoded)")
 
print("\nLarger set:")
 
let key2 = "Vigenère cipher"
let text2 = "This is a ünicode string 😃"
 
let cipher2 = Vigenere(key: key2, smallestCharacter: " ", largestCharacter: "🛹")!
 
print("Key: \(key2)")
print("Plain Text: \(text2)")
 
let encoded2 = cipher2.encrypt(text2)!
 
print("Cipher Text: \(encoded2)")
 
let decoded2 = cipher2.decrypt(encoded2)!
 
print("Decoded: \(decoded2)")</syntaxhighlight>
 
{{out}}
 
<pre>Key: VIGENERECIPHER
Plain Text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Cipher Text: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decoded: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
 
Larger set:
Key: Vigenère cipher
Plain Text: This is a ünicode string 😃
Cipher Text: �±°¸nıÅeacŅ¾±¨Á�®g¸Âĺ»³gc🙌
Decoded: This is a ünicode string 😃</pre>
 
=={{header|Tcl}}==
{{trans|C++}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
oo::class create Vigenere {
Line 3,350 ⟶ 4,253:
return $out
}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">set cypher [Vigenere new "Vigenere Cipher"]
set original "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
set encrypted [$cypher encrypt $original]
Line 3,358 ⟶ 4,261:
puts $original
puts "Encrypted: $encrypted"
puts "Decrypted: $decrypted"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,368 ⟶ 4,271:
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txr">@(next :args)
@(do
(defun vig-op (plus-or-minus)
Line 3,390 ⟶ 4,293:
dec: @decoded
check: @check
@(end)</langsyntaxhighlight>
 
Here, the TXR pattern language is used to scan letters out of two arguments,
Line 3,409 ⟶ 4,312:
 
=={{header|TypeScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">class Vigenere {
 
key: string
Line 3,456 ⟶ 4,359:
 
})()
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub test()
Line 3,523 ⟶ 4,426:
Private Function CharToAscii(s As String) As Byte()
CharToAscii = StrConv(s, vbFromUnicode)
End Function</langsyntaxhighlight>
 
{{Out}}
Line 3,531 ⟶ 4,434:
=={{header|VBScript}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="vb">
<lang vb>
Function Encrypt(text,key)
text = OnlyCaps(text)
Line 3,579 ⟶ 4,482:
WScript.StdOut.WriteLine "Encrypted: " & Encrypt(orig_text,orig_key)
WScript.StdOut.WriteLine "Decrypted: " & Decrypt(Encrypt(orig_text,orig_key),orig_key)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,590 ⟶ 4,493:
 
An alternate implementation using RegExp to filter the input
<syntaxhighlight lang="vb">
<lang vb>
'vigenere cypher
option explicit
Line 3,626 ⟶ 4,529:
wscript.echo decrypt(encoded,key)
 
</syntaxhighlight>
</lang>
 
=={{header|Vedit macro language}}==
Line 3,632 ⟶ 4,535:
starting from cursor location.
The user enters the keyword (upper or lower case).
<langsyntaxhighlight lang="vedit">Get_Input(10, "Key: ", STATLINE+NOCR) // @10 = key
Reg_Copy_Block(11, Cur_Pos, EOL_Pos) // @11 = copy of original text
EOL Ins_Newline
Line 3,679 ⟶ 4,582:
}
Num_Pop(6,9)
Return </langsyntaxhighlight>
 
{{out}}
Line 3,687 ⟶ 4,590:
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
const
(
key = "VIGENERECIPHER"
text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
)
 
fn main() {
encoded := vigenere(text, key, true)
println(encoded)
decoded := vigenere(encoded, key, false)
println(decoded)
}
 
fn vigenere(str string, key string, encrypt bool) string {
mut txt :=''
mut chr_arr := []u8{}
mut kidx, mut cidx := 0, 0
if encrypt == true {txt = str.to_upper()}
else {txt = str}
for chr in txt {
if (chr > 64 && chr < 91) == false {continue}
if encrypt == true {cidx = (chr + key[kidx] - 130) % 26}
else {cidx = (chr - key[kidx] + 26) % 26}
chr_arr << u8(cidx + 65)
kidx = (kidx + 1) % key.len
}
return chr_arr.bytestr()
}
</syntaxhighlight>
 
{{out}}
<pre>
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-str}}
<syntaxhighlight lang="wren">import "./str" for Char, Str
 
var vigenere = Fn.new { |text, key, encrypt|
var t = encrypt ? Str.upper(text) : text
var sb = ""
var ki = 0
for (c in t) {
if (Char.isAsciiUpper(c)) {
var ci = encrypt ? (c.bytes[0] + key[ki].bytes[0] - 130) % 26 :
(c.bytes[0] - key[ki].bytes[0] + 26) % 26
sb = sb + Char.fromCode(ci + 65)
ki = (ki + 1) % key.count
}
}
return sb
}
 
var key = "VIGENERECIPHER"
var text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
var encoded = vigenere.call(text, key, true)
System.print(encoded)
var decoded = vigenere.call(encoded, key, false)
System.print(decoded)</syntaxhighlight>
 
{{out}}
<pre>
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
 
Line 3,693 ⟶ 4,667:
Usage: vigenere KEYWORD <infile.txt >outfile.xxx
 
<langsyntaxhighlight XPL0lang="xpl0">code ChIn=7, ChOut=8;
int Neg, C, Len, I, Key;
char KeyWord(80);
Line 3,713 ⟶ 4,687:
until C=$1A; \EOF
ChOut(0, $1A); \encrypted file must end with EOF otherwise the decode will hang
]</langsyntaxhighlight>
 
{{out}}
Line 3,723 ⟶ 4,697:
outfile = PACKMYBOXWITHFIVEDOZENLIQUORJUGS
</pre>
 
=={{header|Zig}}==
{{works with|Zig|0.11.0}}
<syntaxhighlight lang="zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
</syntaxhighlight><syntaxhighlight lang="zig">
const Vigenere = enum {
encode,
decode,
};
</syntaxhighlight><syntaxhighlight lang="zig">
pub fn main() anyerror!void {
// ------------------------------------------ allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const ok = gpa.deinit();
std.debug.assert(ok == .ok);
}
const allocator = gpa.allocator();
// --------------------------------------------- stdout
const stdout = std.io.getStdOut().writer();
// ----------------------------------------------------
const key = "VIGENERECIPHER";
const text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
 
const encoded = try vigenere(allocator, text, key, .encode);
defer allocator.free(encoded);
try stdout.print("{s}\n", .{encoded});
 
const decoded = try vigenere(allocator, encoded, key, .decode);
defer allocator.free(decoded);
try stdout.print("{s}\n", .{decoded});
}
</syntaxhighlight><syntaxhighlight lang="zig">
/// Caller owns the returned slice memory.
fn vigenere(allocator: Allocator, text: []const u8, key: []const u8, mode: Vigenere) Allocator.Error![]u8 {
var dynamic_string = std.ArrayList(u8).init(allocator);
var key_index: usize = 0;
for (text) |letter| {
const c = if (std.ascii.isLower(letter)) std.ascii.toUpper(letter) else letter;
if (std.ascii.isUpper(c)) {
const k = key[key_index];
const n = switch (mode) {
.encode => ((c - 'A') + (k - 'A')),
.decode => 26 + c - k,
};
try dynamic_string.append(n % 26 + 'A'); // A-Z
key_index += 1;
key_index %= key.len;
}
}
return dynamic_string.toOwnedSlice();
}
</syntaxhighlight>{{out}}
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
=={{header|zkl}}==
{{trans|C}}
<langsyntaxhighlight lang="zkl">fcn encipher(src,key,is_encode){
upperCase:=["A".."Z"].pump(String);
src=src.toUpper().inCommon(upperCase); // only uppercase
Line 3,737 ⟶ 4,768:
else c - key[i] + 26 ) % 26).toChar()
});
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">str := "Beware the Jabberwock, my son! The jaws that bite, "
"the claws that catch!";
key := "Vigenere Cipher";
Line 3,746 ⟶ 4,777:
cod := encipher(str, key, True); println("Code: ", cod);
dec := encipher(cod, key, False); println("Back: ", dec);</langsyntaxhighlight>
{{out}}
<pre>
9,479

edits