Vigenère cipher: Difference between revisions

m
m (printf has an unspecified return type, if ghc doesn't know it's IO() we get a confusing error message. I don't think I'm including external links?)
m (→‎{{header|Wren}}: Minor tidy)
 
(34 intermediate revisions by 17 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 56:
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Fix(CHAR ARRAY in,fixed)
INT i
CHAR c
 
fixed(0)=0
FOR i=1 TO in(0)
DO
c=in(i)
IF c>='a AND c<='z THEN
c==-('a-'A)
FI
IF c>='A AND c<='Z THEN
fixed(0)==+1
fixed(fixed(0))=c
FI
OD
RETURN
 
PROC Process(CHAR ARRAY in,key,out INT dir)
CHAR ARRAY inFixed(256),keyFixed(256)
INT keyI,tmp,i
CHAR c
 
out(0)=0
Fix(in,inFixed)
Fix(key,keyFixed)
IF inFixed(0)=0 OR keyFixed(0)=0 THEN
RETURN
FI
 
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>
Original:
Attack at dawn!
Encrypted key=LEMONLEMONLE:
LXFOPVEFRNHR
Decrypted key=LEMONLEMONLE:
ATTACKATDAWN
 
Original:
Crypto is short for cryptography.
Encrypted key=ABCDABCDABCDABCDABCDABCDABCD:
CSASTPKVSIQUTGQUCSASTPIUAQJB
Decrypted key=ABCDABCDABCDABCDABCDABCDABCD:
CRYPTOISSHORTFORCRYPTOGRAPHY
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">WITH Ada.Text_IO, Ada.Characters.Handling;
USE Ada.Text_IO, Ada.Characters.Handling;
 
Line 116 ⟶ 206:
END Main;
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 129 ⟶ 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 190 ⟶ 280:
print(("Encrypted: ", encrypted, new line));
print(("Decrypted: ", decrypted, new line))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 201 ⟶ 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 229 ⟶ 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 238 ⟶ 328:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">Letters: append `A`..`Z` `a`..`z`
encrypt: function [msg, key][
pos: 0
Line 268 ⟶ 358:
print text
print encr
print decr</langsyntaxhighlight>
 
{{out}}
Line 277 ⟶ 367:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Key = VIGENERECIPHER
Text= Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
 
Line 299 ⟶ 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 305 ⟶ 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 346 ⟶ 498:
IF C% >= 97 IF C% <= 122 MID$(A$,A%,1) = CHR$(C%-32)
NEXT
= A$</langsyntaxhighlight>
{{out}}
<pre>
Line 358 ⟶ 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 369 ⟶ 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 380 ⟶ 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 492 ⟶ 644:
 
return buf;
}</langsyntaxhighlight>
 
{{out}}
Line 504 ⟶ 656:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
 
Line 549 ⟶ 701:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 560 ⟶ 712:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
using namespace std;
Line 632 ⟶ 784:
cout << "Encrypted: " << encrypted << endl;
cout << "Decrypted: " << decrypted << endl;
}</langsyntaxhighlight>
 
{{out}}
Line 642 ⟶ 794:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
function normalize(String text) => text.uppercased.filter(Character.letter);
Line 666 ⟶ 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 698 ⟶ 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 712 ⟶ 864:
(doall (map (fn [[k v]] (printf "%9s: %s\n" k v))
[ ["Original" plaintext] ["Key" key] ["Encrypted" ciphertext] ["Decrypted" recovered] ])))
</syntaxhighlight>
</lang>
 
{{out}}
Line 722 ⟶ 874:
=={{header|CoffeeScript}}==
{{trans|D}}
<langsyntaxhighlight lang="coffeescript"># Simple helper since charCodeAt is quite long to write.
code = (char) -> char.charCodeAt()
 
Line 756 ⟶ 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 762 ⟶ 914:
 
=={{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.)
<langsyntaxhighlight lang="lisp">(defun strip (s)
(remove-if-not
(lambda (c) (char<= #\A c #\Z))
Line 788 ⟶ 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!
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 823 ⟶ 1,003:
immutable encoded = original.encrypt(key);
writeln(encoded, "\n", encoded.decrypt(key));
}</langsyntaxhighlight>
{{out}}
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Line 830 ⟶ 1,010:
===Alternative Version===
{{trans|Raku}}
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.ascii, std.string, std.algorithm,
std.conv;
 
Line 855 ⟶ 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 868 ⟶ 1,179:
class VCipher
{
string encrypt(string txt, string pw, int d)
{
auto output := new TextBuilder();
int pwi := 0;
string PW := pw.upperCasetoUpper();
var TXT := txt.toUpper();
 
txt.upperCase().forEach:(t)
foreach(char t; in TXT) {
if(t >= $65){
if (t < {$65) $continue;
 
int tmp := t.toInt() - 65 + d * (PW[pwi].toInt() - 65);
int tmp := t - 65 + ifd * (tmppw[pwi] <- 065);
if (tmp < 0) tmp += {26;
output.write((65 + tmp += .mod(26)).toChar());
}pwi++;
if (pwi == PW.Length) { pwi := output.write((650 + tmp.mod:26).toChar());}
pwi += 1};
 
if (pwi == PW.Length) { pwi := 0 }
^ }output.Value
};
^ output.Value
}
}
Line 901 ⟶ 1,209:
var pw := "VIGENERECIPHER";
console.printLine(s0,newLinenewLineConstant,pw,newLinenewLineConstant);
var s1 := v.encrypt(s0, pw, 1);
console.printLine("Encrypted:",s1);
Line 908 ⟶ 1,216:
console.printLine("Press any key to continue..");
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 921 ⟶ 1,229:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule VigenereCipher do
@base ?A
@size ?Z - @base + 1
Line 948 ⟶ 1,256:
IO.puts "Original: #{plaintext}"
IO.puts "Encrypted: #{ciphertext}"
IO.puts "Decrypted: #{recovered}"</langsyntaxhighlight>
 
{{out}}
Line 959 ⟶ 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,005 ⟶ 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,014 ⟶ 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,021 ⟶ 1,329:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
module vigenere =
let keyschedule (key:string) =
Line 1,049 ⟶ 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,057 ⟶ 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,086 ⟶ 1,394:
vigenere-decrypt "Decrypted: %s\n" printf ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,097 ⟶ 1,405:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program vigenere_cipher
implicit none
Line 1,158 ⟶ 1,466:
end do
end subroutine
end program</langsyntaxhighlight>
{{out}}
<pre> Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
 
=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="freebasic">
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
texto = Filtrar(texto)
Dim As String mSS, kSS, letra, cifrado = ""
Dim As Integer m, k, c, j = 1
For i As Integer = 1 To Len(texto)
mSS = Mid(texto, i, 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
Dim As String mSS, kSS, letra, descifrado = ""
Dim As Integer m, k, c, j = 1
For i As Integer = 1 To Len(texto)
mSS = Mid(texto, i, 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
llave = Filtrar("vigenerecipher")
 
Dim As String cadorigen = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
Print cadorigen
Print llave
 
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,233 ⟶ 1,609:
}
fmt.Println("Deciphered:", dt)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,245 ⟶ 1,621:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Char
import Text.Printf
 
Line 1,271 ⟶ 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,281 ⟶ 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,304 ⟶ 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,320 ⟶ 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,334 ⟶ 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,389 ⟶ 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,453 ⟶ 1,820:
 
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">// helpers
// helper
function ordA(a) {
Line 1,479 ⟶ 1,846:
 
console.log(enc);
console.log(dec);</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<syntaxhighlight lang="jq">def vigenere(text; key; encryptp):
# retain alphabetic characters only
def n:
ascii_upcase | explode | map(select(65 <= . and . <= 90)) | [., length];
(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
def example($key):
vigenere(.; $key; true)
| . as $encoded
| ., vigenere($encoded; $key; false) ;
 
"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
| (., 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!
SSOEKXTJSMESPWVPHCMABWFBLLXCAYGWLRHTMMXTJSFPRKKXATTEOWGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
 
=={{header|Jsish}}==
From Javascript entry.
<langsyntaxhighlight lang="javascript">/* Vigenère cipher, in Jsish */
"use strict";
 
Line 1,518 ⟶ 1,922:
vigenere(enc, key, true) ==> THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGTHELAZYDOGLAZYDOGDOG
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
<pre>prompt$ jsish -u vigenereCipher.jsi
[PASS] vigenereCipher.jsi</pre>
 
 
=={{header|Julia}}==
{{works with|Julia|01.65}}
<syntaxhighlight lang="julia">
<lang Julia>function encrypt(msg::AbstractString, key::AbstractString)
→(a::Char, b::Char, ± = +) = 'A'+((a-'A')±(b-'A')+26)%26
msg = uppercase(join(filter(isalpha, collect(msg))))
←(a::Char, b::Char) = →(a,b,-)
key = uppercase(join(filter(isalpha, collect(key))))
msglen = length(msg)
keylen = length(key)
 
cleanup(str) = filter(a-> a in 'A':'Z', collect(uppercase.(str)))
if keylen < msglen
match_length(word, len) = repeat(word,len)[1:len]
key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen]
end
 
enc = Vector{Char}(msglen)
 
@inbounds for i in 1:length(msg)
enc[i] = Char((Int(msg[i]) + Int(key[i]) - 130) % 26 + 65)
end
 
function →(message::String, codeword::String, ↔ = →)
return join(enc)
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!"
function decrypt(enc::AbstractString, key::AbstractString)
println(cyphertext)
enc = uppercase(join(filter(isalpha, collect(enc))))
println(cyphertext ← "Gimme!")
key = uppercase(join(filter(isalpha, collect(key))))
</syntaxhighlight>
msglen = length(enc)
keylen = length(key)
 
if keylen < msglen
key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen]
end
 
msg = Vector{Char}(msglen)
 
@inbounds for i in 1:length(enc)
msg[i] = Char((Int(enc[i]) - Int(key[i]) + 26) % 26 + 65)
end
 
return join(msg)
end
 
const messages = ("Attack at dawn.", "Don't attack.", "The war is over.")
const key = "LEMON"
 
for msg in messages
enc = encrypt(msg, key)
dec = decrypt(enc, key)
println("Original: $msg\n -> encrypted: $enc\n -> decrypted: $dec")
end</lang>
 
{{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,611 ⟶ 1,983:
val decoded = vigenere(encoded, key, false)
println(decoded)
}</langsyntaxhighlight>
 
{{out}}
Line 1,621 ⟶ 1,993:
=={{header|Lambdatalk}}==
Only texts in uppercases [A-Z] and spaces.
<langsyntaxhighlight lang="scheme">
{def vigenere
{def vigenere.map
Line 1,645 ⟶ 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,699 ⟶ 2,071:
next
end function
</syntaxhighlight>
</lang>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 1,707 ⟶ 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 1,748 ⟶ 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,783 ⟶ 2,155:
keyCode[[;; Length@textCode]],
PadRight[keyCode, Length@textCode, keyCode]];
FromCharacterCode[Mod[textCode - keyCode, 26] + 65]]</langsyntaxhighlight>
 
<pre>key = "Vigenere Cipher";
Line 1,799 ⟶ 2,171:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 1,951 ⟶ 2,323:
return melancholy_dane
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,025 ⟶ 2,397:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
proc encrypt(msg, key: string): string =
Line 2,048 ⟶ 2,420:
echo text
echo encr
echo decr</langsyntaxhighlight>
 
{{out}}
Line 2,057 ⟶ 2,429:
=={{header|Objeck}}==
{{trans|D}}
<langsyntaxhighlight lang="objeck">
bundle Default {
class VigenereCipher {
Line 2,103 ⟶ 2,475:
}
}
</syntaxhighlight>
</lang>
<pre>
encrypt: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Line 2,112 ⟶ 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,152 ⟶ 2,524:
Printf.printf "Code: %s\n" cod;
Printf.printf "Back: %s\n" dec;
;;</langsyntaxhighlight>
 
Run:
Line 2,167 ⟶ 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,249 ⟶ 2,621:
Printf.printf "Back: %s\n" pt
;;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,261 ⟶ 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,455 ⟶ 2,827:
End
Exit
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,529 ⟶ 2,901:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">
// The Vigenere cipher in reasonably standard Pascal
// <no library functions: all conversions hand-coded>
Line 2,634 ⟶ 3,006:
END.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,646 ⟶ 3,018:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">if( @ARGV != 3 ){
printHelp();
}
Line 2,685 ⟶ 3,057:
}
return $cipher;
}</langsyntaxhighlight>
 
Demonstration:
Line 2,707 ⟶ 3,079:
 
=={{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,738 ⟶ 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,783 ⟶ 3,159:
 
?>
</syntaxhighlight>
</lang>
{{out}}
<pre>Text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 2,791 ⟶ 3,167:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de vigenereKey (Str)
(extract
'((C)
Line 2,812 ⟶ 3,188:
(char (+ 65 (% (+ 26 (- C K)) 26))) )
(vigenereKey Str)
(apply circ (vigenereKey Key)) ) ) )</langsyntaxhighlight>
Test:
<pre>: (vigenereEncrypt
Line 2,823 ⟶ 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,868 ⟶ 3,244:
end;
end cypher;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,877 ⟶ 3,253:
 
=={{header|PowerShell}}==
<langsyntaxhighlight Powershelllang="powershell"># Author: D. Cudnohufsky
function Get-VigenereCipher
{
Line 2,961 ⟶ 3,337:
$OutText = $null
}
}</langsyntaxhighlight>
Usage examples:
<pre>
Line 2,974 ⟶ 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,034 ⟶ 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,043 ⟶ 3,419:
{{Works with|Python|3}}
{{trans|Haskell}}
<langsyntaxhighlight lang="python">'''Vigenere encryption and decryption'''
 
from itertools import starmap, cycle
Line 3,092 ⟶ 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,101 ⟶ 3,477:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ [] swap witheach
[ upper
dup char A char Z 1+ within
Line 3,132 ⟶ 3,508:
say "Encrypted: " $ "Kahlil Gibran" encrypt dup echo$ cr
say "Decrypted: " $ "Kahlil Gibran" decrypt echo$</langsyntaxhighlight>
 
{{out}}
Line 3,140 ⟶ 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,157 ⟶ 3,533:
# WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
message(vigen("WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY", "vigenerecipher", decrypt = T))
# BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define chr integer->char)
Line 3,182 ⟶ 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,202 ⟶ 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,216 ⟶ 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,293 ⟶ 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,301 ⟶ 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,327 ⟶ 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,340 ⟶ 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,366 ⟶ 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,375 ⟶ 3,751:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Vigenère cipher
 
Line 3,421 ⟶ 3,797:
next
return a
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,428 ⟶ 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,453 ⟶ 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,466 ⟶ 3,869:
puts "Original: #{plaintext}"
puts "Encrypted: #{ciphertext}"
puts "Decrypted: #{recovered}"</langsyntaxhighlight>
 
{{out}}
Line 3,476 ⟶ 3,879:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::ascii::AsciiExt;
 
static A: u8 = 'A' as u8;
Line 3,524 ⟶ 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,563 ⟶ 3,966:
println("Encrypt text ABC => " + Vigenere.encrypt("ABC", "KEY"))
println("Decrypt text KFA => " + Vigenere.decrypt("KFA", "KEY"))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,570 ⟶ 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,620 ⟶ 4,023:
decrypted := vigenereDecipher(encrypted, keyword);
writeln("Decrypted: " <& decrypted);
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,632 ⟶ 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,643 ⟶ 4,046:
say red
say (var black = blacken(red, key))
say redden(black, key)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,654 ⟶ 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,668 ⟶ 4,071:
crypted -> 'WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY'
plain2 -> 'BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH'
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
Line 3,674 ⟶ 4,077:
Can support a larger range of characters, if desired
 
<langsyntaxhighlight lang="swift">public func convertToUnicodeScalars(
str: String,
minChar: UInt32,
Line 3,798 ⟶ 4,201:
let decoded2 = cipher2.decrypt(encoded2)!
 
print("Decoded: \(decoded2)")</langsyntaxhighlight>
 
{{out}}
Line 3,815 ⟶ 4,218:
=={{header|Tcl}}==
{{trans|C++}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
oo::class create Vigenere {
Line 3,850 ⟶ 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,858 ⟶ 4,261:
puts $original
puts "Encrypted: $encrypted"
puts "Decrypted: $decrypted"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,868 ⟶ 4,271:
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txr">@(next :args)
@(do
(defun vig-op (plus-or-minus)
Line 3,890 ⟶ 4,293:
dec: @decoded
check: @check
@(end)</langsyntaxhighlight>
 
Here, the TXR pattern language is used to scan letters out of two arguments,
Line 3,909 ⟶ 4,312:
 
=={{header|TypeScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">class Vigenere {
 
key: string
Line 3,956 ⟶ 4,359:
 
})()
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub test()
Line 4,023 ⟶ 4,426:
Private Function CharToAscii(s As String) As Byte()
CharToAscii = StrConv(s, vbFromUnicode)
End Function</langsyntaxhighlight>
 
{{Out}}
Line 4,031 ⟶ 4,434:
=={{header|VBScript}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="vb">
<lang vb>
Function Encrypt(text,key)
text = OnlyCaps(text)
Line 4,079 ⟶ 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,090 ⟶ 4,493:
 
An alternate implementation using RegExp to filter the input
<syntaxhighlight lang="vb">
<lang vb>
'vigenere cypher
option explicit
Line 4,126 ⟶ 4,529:
wscript.echo decrypt(encoded,key)
 
</syntaxhighlight>
</lang>
 
=={{header|Vedit macro language}}==
Line 4,132 ⟶ 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,179 ⟶ 4,582:
}
Num_Pop(6,9)
Return </langsyntaxhighlight>
 
{{out}}
Line 4,187 ⟶ 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,192 ⟶ 4,633:
{{trans|Kotlin}}
{{libheader|Wren-str}}
<langsyntaxhighlight ecmascriptlang="wren">import "./str" for Char, Str
 
var vigenere = Fn.new { |text, key, encrypt|
Line 4,214 ⟶ 4,655:
System.print(encoded)
var decoded = vigenere.call(encoded, key, false)
System.print(decoded)</langsyntaxhighlight>
 
{{out}}
Line 4,226 ⟶ 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,246 ⟶ 4,687:
until C=$1A; \EOF
ChOut(0, $1A); \encrypted file must end with EOF otherwise the decode will hang
]</langsyntaxhighlight>
 
{{out}}
Line 4,256 ⟶ 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,270 ⟶ 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,279 ⟶ 4,777:
cod := encipher(str, key, True); println("Code: ", cod);
dec := encipher(cod, key, False); println("Back: ", dec);</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits