Vigenère cipher: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(16 intermediate revisions by 10 users not shown)
Line 22:
{{trans|C++}}
 
<langsyntaxhighlight lang="11l">F encrypt(key, text)
V out = ‘’
V j = 0
Line 49:
print(original)
print(‘Encrypted: ’encrypted)
print(‘Decrypted: ’decrypted)</langsyntaxhighlight>
 
{{out}}
Line 59:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Fix(CHAR ARRAY in,fixed)
INT i
CHAR c
Line 129:
 
Test("Crypto is short for cryptography.","ABCDABCDABCDABCDABCDABCDABCD")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Vigen%C3%A8re_cipher.png Screenshot from Atari 8-bit computer]
Line 150:
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">WITH Ada.Text_IO, Ada.Characters.Handling;
USE Ada.Text_IO, Ada.Characters.Handling;
 
Line 206:
END Main;
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 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 280:
print(("Encrypted: ", encrypted, new line));
print(("Decrypted: ", decrypted, new line))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 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 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 328:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">Letters: append `A`..`Z` `a`..`z`
encrypt: function [msg, key][
pos: 0
Line 358:
print text
print encr
print decr</langsyntaxhighlight>
 
{{out}}
Line 367:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Key = VIGENERECIPHER
Text= Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
 
Line 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 399:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
<lang BASIC256>
function Filtrar(cadorigen)
filtrado = ""
Line 451:
print "Descifrado: "; DesEncriptar(cadcifrada, llave)
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 459:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> key$ = "LEMON"
plaintext$ = "ATTACK AT DAWN"
ciphertext$ = FNencrypt(plaintext$, key$)
Line 498:
IF C% >= 97 IF C% <= 122 MID$(A$,A%,1) = CHR$(C%-32)
NEXT
= A$</langsyntaxhighlight>
{{out}}
<pre>
Line 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 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 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 644:
 
return buf;
}</langsyntaxhighlight>
 
{{out}}
Line 656:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
 
Line 701:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 712:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
using namespace std;
Line 784:
cout << "Encrypted: " << encrypted << endl;
cout << "Decrypted: " << decrypted << endl;
}</langsyntaxhighlight>
 
{{out}}
Line 794:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
function normalize(String text) => text.uppercased.filter(Character.letter);
Line 818:
print(encrypted);
print(decrypted);
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Requires Clojure 1.2.
<langsyntaxhighlight lang="clojure">(ns org.rosettacode.clojure.vigenere
(:require [clojure.string :as string]))
 
Line 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 864:
(doall (map (fn [[k v]] (printf "%9s: %s\n" k v))
[ ["Original" plaintext] ["Key" key] ["Encrypted" ciphertext] ["Decrypted" recovered] ])))
</syntaxhighlight>
</lang>
 
{{out}}
Line 874:
=={{header|CoffeeScript}}==
{{trans|D}}
<langsyntaxhighlight lang="coffeescript"># Simple helper since charCodeAt is quite long to write.
code = (char) -> char.charCodeAt()
 
Line 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
Line 916:
====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.)
<langsyntaxhighlight lang="lisp">(defun strip (s)
(remove-if-not
(lambda (c) (char<= #\A c #\Z))
Line 941:
(enc (vigenère msg key))
(dec (vigenère enc key :decipher t)))
(format t "msg: ~a~%enc: ~a~%dec: ~a~%" msg enc dec))</langsyntaxhighlight>
{{out}}
<pre>msg: Beware the Jabberwock... The jaws that... the claws that catch!
Line 952:
1. Program
 
<langsyntaxhighlight lang="lisp">(defconstant +a+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
 
(defun strip (s)
Line 963:
(setf i (mod (1+ i) (length key)))
(char +a+ (mod (+ (position c +a+) (* p (position (elt key i) +a+))) 26)))
txt)))</langsyntaxhighlight>
 
2. Execution
Line 975:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.string;
 
string encrypt(in string txt, in string key) pure @safe
Line 1,003:
immutable encoded = original.encrypt(key);
writeln(encoded, "\n", encoded.decrypt(key));
}</langsyntaxhighlight>
{{out}}
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Line 1,010:
===Alternative Version===
{{trans|Raku}}
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.ascii, std.string, std.algorithm,
std.conv;
 
Line 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 46.x :
<langsyntaxhighlight lang="elena">import system'text;
import system'culture;
import system'math;
import system'routines;
Line 1,048 ⟶ 1,179:
class VCipher
{
string encrypt(string txt, string pw, int d)
{
auto output := new TextBuilder();
int pwi := 0;
string PW := pw.upperCase();
string PW txt:= pw.upperCase().forEach:toUpper(t);
var TXT {:= txt.toUpper();
 
if(t >= $65)
foreach(char t; in TXT) {
{
int tmp := t.toInt() - 65 + d * (PW[pwi].toInt() - 65);
if (tmpt < 0$65) $continue;
 
{
int tmp := t - 65 + d * (pw[pwi] - tmp += 2665);
if (tmp < 0) tmp += }26;
output.write((65 + tmp.mod:(26)).toChar());
pwi += 1+;
if (pwi == PW.Length) { pwi := 0 }
};
 
};
^ output.Value
}
^ output.Value
}
}
Line 1,081 ⟶ 1,209:
var pw := "VIGENERECIPHER";
console.printLine(s0,newLinenewLineConstant,pw,newLinenewLineConstant);
var s1 := v.encrypt(s0, pw, 1);
console.printLine("Encrypted:",s1);
Line 1,088 ⟶ 1,216:
console.printLine("Press any key to continue..");
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,101 ⟶ 1,229:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule VigenereCipher do
@base ?A
@size ?Z - @base + 1
Line 1,128 ⟶ 1,256:
IO.puts "Original: #{plaintext}"
IO.puts "Encrypted: #{ciphertext}"
IO.puts "Decrypted: #{recovered}"</langsyntaxhighlight>
 
{{out}}
Line 1,139 ⟶ 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 1,185 ⟶ 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 1,194 ⟶ 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}}
Line 1,201 ⟶ 1,329:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
module vigenere =
let keyschedule (key:string) =
Line 1,229 ⟶ 1,357:
let plain = vigenere.decrypt passwd cipher
printfn "%s\n%s" cipher plain
</syntaxhighlight>
</lang>
 
<pre>C:\src\fsharp>fsi vigenere.fsx
Line 1,237 ⟶ 1,365:
 
=={{header|Factor}}==
<syntaxhighlight lang="text">USING: arrays ascii formatting kernel math math.functions
math.order sequences ;
IN: rosetta-code.vigenere-cipher
Line 1,266 ⟶ 1,394:
vigenere-decrypt "Decrypted: %s\n" printf ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,277 ⟶ 1,405:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program vigenere_cipher
implicit none
Line 1,338 ⟶ 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,347 ⟶ 1,475:
=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<langsyntaxhighlight lang="freebasic">
Function Filtrar(cadorigen As String) As String
Dim As String letra
Line 1,402 ⟶ 1,530:
Print "Descifrado: "; DesEncriptar(cadcifrada, llave)
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,413 ⟶ 1,541:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,481 ⟶ 1,609:
}
fmt.Println("Deciphered:", dt)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,493 ⟶ 1,621:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Char
import Text.Printf
 
Line 1,519 ⟶ 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,529 ⟶ 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,552 ⟶ 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,568 ⟶ 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,582 ⟶ 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,637 ⟶ 1,756:
return res;
}
}</langsyntaxhighlight>
 
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
===Alternative Version===
<syntaxhighlight lang="java">
<lang Java>
import com.google.common.collect.Streams;
import java.util.function.Supplier;
Line 1,701 ⟶ 1,820:
 
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">// helpers
// helper
function ordA(a) {
Line 1,727 ⟶ 1,846:
 
console.log(enc);
console.log(dec);</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<langsyntaxhighlight lang="jq">def vigenere(text; key; encryptp):
# retain alphabetic characters only
def n:
Line 1,755 ⟶ 1,874:
| (., example("VIGENERECIPHER")),
"",
(., example("ROSETTACODE"))</langsyntaxhighlight>
{{out}}
<pre>
Line 1,768 ⟶ 1,887:
=={{header|Jsish}}==
From Javascript entry.
<langsyntaxhighlight lang="javascript">/* Vigenère cipher, in Jsish */
"use strict";
 
Line 1,803 ⟶ 1,922:
vigenere(enc, key, true) ==> THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGTHELAZYDOGLAZYDOGDOG
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,812 ⟶ 1,931:
=={{header|Julia}}==
{{works with|Julia|1.5}}
<syntaxhighlight lang="julia">
<lang Julia>
→(a::Char, b::Char, ± = +) = 'A'+((a-'A')±(b-'A')+26)%26
←(a::Char, b::Char) = →(a,b,-)
Line 1,829 ⟶ 1,948:
println(cyphertext)
println(cyphertext ← "Gimme!")
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,839 ⟶ 1,958:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
fun vigenere(text: String, key: String, encrypt: Boolean = true): String {
Line 1,864 ⟶ 1,983:
val decoded = vigenere(encoded, key, false)
println(decoded)
}</langsyntaxhighlight>
 
{{out}}
Line 1,874 ⟶ 1,993:
=={{header|Lambdatalk}}==
Only texts in uppercases [A-Z] and spaces.
<langsyntaxhighlight lang="scheme">
{def vigenere
{def vigenere.map
Line 1,898 ⟶ 2,017:
-> ATTACKATDAWN
 
</syntaxhighlight>
</lang>
 
=={{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,952 ⟶ 2,071:
next
end function
</syntaxhighlight>
</lang>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 1,960 ⟶ 2,079:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function Encrypt( _msg, _key )
local msg = { _msg:upper():byte( 1, -1 ) }
local key = { _key:upper():byte( 1, -1 ) }
Line 2,001 ⟶ 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 2,036 ⟶ 2,155:
keyCode[[;; Length@textCode]],
PadRight[keyCode, Length@textCode, keyCode]];
FromCharacterCode[Mod[textCode - keyCode, 26] + 65]]</langsyntaxhighlight>
 
<pre>key = "Vigenere Cipher";
Line 2,052 ⟶ 2,171:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 2,204 ⟶ 2,323:
return melancholy_dane
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,278 ⟶ 2,397:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
proc encrypt(msg, key: string): string =
Line 2,301 ⟶ 2,420:
echo text
echo encr
echo decr</langsyntaxhighlight>
 
{{out}}
Line 2,310 ⟶ 2,429:
=={{header|Objeck}}==
{{trans|D}}
<langsyntaxhighlight lang="objeck">
bundle Default {
class VigenereCipher {
Line 2,356 ⟶ 2,475:
}
}
</syntaxhighlight>
</lang>
<pre>
encrypt: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Line 2,365 ⟶ 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 2,405 ⟶ 2,524:
Printf.printf "Code: %s\n" cod;
Printf.printf "Back: %s\n" dec;
;;</langsyntaxhighlight>
 
Run:
Line 2,420 ⟶ 2,539:
 
This is a custom, more functional version of the existing solution, due to
'''[https://camlocaml.inria.fr/pub/docs/manual-ocamlorg/librefapi/String.html OCaml 4.05's unsafe-string compatibility mode]'''
 
{{works with|OCaml|4.05 or above}}
<syntaxhighlight lang="ocaml">
<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://camlocaml.inria.fr/pub/docs/manual-ocamlorg/librefapi/String.html
*)
 
Line 2,502 ⟶ 2,621:
Printf.printf "Back: %s\n" pt
;;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,514 ⟶ 2,633:
{{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,708 ⟶ 2,827:
End
Exit
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,782 ⟶ 2,901:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">
// The Vigenere cipher in reasonably standard Pascal
// <no library functions: all conversions hand-coded>
Line 2,887 ⟶ 3,006:
END.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,899 ⟶ 3,018:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">if( @ARGV != 3 ){
printHelp();
}
Line 2,938 ⟶ 3,057:
}
return $cipher;
}</langsyntaxhighlight>
 
Demonstration:
Line 2,960 ⟶ 3,079:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
Line 2,985 ⟶ 3,104:
<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>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 2,995 ⟶ 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 3,040 ⟶ 3,159:
 
?>
</syntaxhighlight>
</lang>
{{out}}
<pre>Text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 3,048 ⟶ 3,167:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de vigenereKey (Str)
(extract
'((C)
Line 3,069 ⟶ 3,188:
(char (+ 65 (% (+ 26 (- C K)) 26))) )
(vigenereKey Str)
(apply circ (vigenereKey Key)) ) ) )</langsyntaxhighlight>
Test:
<pre>: (vigenereEncrypt
Line 3,080 ⟶ 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 3,125 ⟶ 3,244:
end;
end cypher;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,134 ⟶ 3,253:
 
=={{header|PowerShell}}==
<langsyntaxhighlight Powershelllang="powershell"># Author: D. Cudnohufsky
function Get-VigenereCipher
{
Line 3,218 ⟶ 3,337:
$OutText = $null
}
}</langsyntaxhighlight>
Usage examples:
<pre>
Line 3,231 ⟶ 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 3,291 ⟶ 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 3,300 ⟶ 3,419:
{{Works with|Python|3}}
{{trans|Haskell}}
<langsyntaxhighlight lang="python">'''Vigenere encryption and decryption'''
 
from itertools import starmap, cycle
Line 3,349 ⟶ 3,468:
if __name__ == '__main__':
main()
</syntaxhighlight>
</lang>
{{out}}
<pre>Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 3,358 ⟶ 3,477:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ [] swap witheach
[ upper
dup char A char Z 1+ within
Line 3,389 ⟶ 3,508:
say "Encrypted: " $ "Kahlil Gibran" encrypt dup echo$ cr
say "Decrypted: " $ "Kahlil Gibran" decrypt echo$</langsyntaxhighlight>
 
{{out}}
Line 3,397 ⟶ 3,516:
 
=={{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 3,414 ⟶ 3,533:
# WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
message(vigen("WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY", "vigenerecipher", decrypt = T))
# BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define chr integer->char)
Line 3,439 ⟶ 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" perl6line>sub s2v ($s) { $s.uc.comb(/ <[ A..Z ]> /)».ord »-» 65 }
sub v2s (@v) { (@v »%» 26 »+» 65)».chr.join }
 
Line 3,459 ⟶ 3,578:
say $red;
say my $black = blacken($red, $key);
say redden($black, $key);</langsyntaxhighlight>
{{out}}
<pre>Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 3,473 ⟶ 3,592:
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 3,550 ⟶ 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 3,558 ⟶ 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 3,584 ⟶ 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 3,597 ⟶ 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,623 ⟶ 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,632 ⟶ 3,751:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Vigenère cipher
 
Line 3,678 ⟶ 3,797:
next
return a
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,685 ⟶ 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,710 ⟶ 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,723 ⟶ 3,869:
puts "Original: #{plaintext}"
puts "Encrypted: #{ciphertext}"
puts "Decrypted: #{recovered}"</langsyntaxhighlight>
 
{{out}}
Line 3,733 ⟶ 3,879:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::ascii::AsciiExt;
 
static A: u8 = 'A' as u8;
Line 3,781 ⟶ 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,820 ⟶ 3,966:
println("Encrypt text ABC => " + Vigenere.encrypt("ABC", "KEY"))
println("Decrypt text KFA => " + Vigenere.decrypt("KFA", "KEY"))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,827 ⟶ 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,877 ⟶ 4,023:
decrypted := vigenereDecipher(encrypted, keyword);
writeln("Decrypted: " <& decrypted);
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,889 ⟶ 4,035:
=={{header|Sidef}}==
{{trans|Raku}}
<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,900 ⟶ 4,046:
say red
say (var black = blacken(red, key))
say redden(black, key)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,911 ⟶ 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,925 ⟶ 4,071:
crypted -> 'WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY'
plain2 -> 'BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH'
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
Line 3,931 ⟶ 4,077:
Can support a larger range of characters, if desired
 
<langsyntaxhighlight lang="swift">public func convertToUnicodeScalars(
str: String,
minChar: UInt32,
Line 4,055 ⟶ 4,201:
let decoded2 = cipher2.decrypt(encoded2)!
 
print("Decoded: \(decoded2)")</langsyntaxhighlight>
 
{{out}}
Line 4,072 ⟶ 4,218:
=={{header|Tcl}}==
{{trans|C++}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
oo::class create Vigenere {
Line 4,107 ⟶ 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 4,115 ⟶ 4,261:
puts $original
puts "Encrypted: $encrypted"
puts "Decrypted: $decrypted"</langsyntaxhighlight>
{{out}}
<pre>
Line 4,125 ⟶ 4,271:
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txr">@(next :args)
@(do
(defun vig-op (plus-or-minus)
Line 4,147 ⟶ 4,293:
dec: @decoded
check: @check
@(end)</langsyntaxhighlight>
 
Here, the TXR pattern language is used to scan letters out of two arguments,
Line 4,166 ⟶ 4,312:
 
=={{header|TypeScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">class Vigenere {
 
key: string
Line 4,213 ⟶ 4,359:
 
})()
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub test()
Line 4,280 ⟶ 4,426:
Private Function CharToAscii(s As String) As Byte()
CharToAscii = StrConv(s, vbFromUnicode)
End Function</langsyntaxhighlight>
 
{{Out}}
Line 4,288 ⟶ 4,434:
=={{header|VBScript}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="vb">
<lang vb>
Function Encrypt(text,key)
text = OnlyCaps(text)
Line 4,336 ⟶ 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 4,347 ⟶ 4,493:
 
An alternate implementation using RegExp to filter the input
<syntaxhighlight lang="vb">
<lang vb>
'vigenere cypher
option explicit
Line 4,383 ⟶ 4,529:
wscript.echo decrypt(encoded,key)
 
</syntaxhighlight>
</lang>
 
=={{header|Vedit macro language}}==
Line 4,389 ⟶ 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 4,436 ⟶ 4,582:
}
Num_Pop(6,9)
Return </langsyntaxhighlight>
 
{{out}}
Line 4,444 ⟶ 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>
 
Line 4,449 ⟶ 4,633:
{{trans|Kotlin}}
{{libheader|Wren-str}}
<langsyntaxhighlight ecmascriptlang="wren">import "./str" for Char, Str
 
var vigenere = Fn.new { |text, key, encrypt|
Line 4,471 ⟶ 4,655:
System.print(encoded)
var decoded = vigenere.call(encoded, key, false)
System.print(decoded)</langsyntaxhighlight>
 
{{out}}
Line 4,483 ⟶ 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 4,503 ⟶ 4,687:
until C=$1A; \EOF
ChOut(0, $1A); \encrypted file must end with EOF otherwise the decode will hang
]</langsyntaxhighlight>
 
{{out}}
Line 4,513 ⟶ 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 4,527 ⟶ 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 4,536 ⟶ 4,777:
cod := encipher(str, key, True); println("Code: ", cod);
dec := encipher(cod, key, False); println("Back: ", dec);</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits