Vigenère cipher: Difference between revisions
m
→{{header|Wren}}: Minor tidy
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++}}
<
V out = ‘’
V j = 0
Line 49:
print(original)
print(‘Encrypted: ’encrypted)
print(‘Decrypted: ’decrypted)</
{{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}}==
<
USE Ada.Text_IO, Ada.Characters.Handling;
Line 116 ⟶ 206:
END Main;
</syntaxhighlight>
{{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].}}
<
PROC vigenere cipher = (REF STRING key)VOID:
Line 190 ⟶ 280:
print(("Encrypted: ", encrypted, new line));
print(("Decrypted: ", decrypted, new line))
)</
{{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">
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$ </
{{out}}
KEY: LEMON
Line 238 ⟶ 328:
=={{header|Arturo}}==
<
encrypt: function [msg, key][
pos: 0
Line 268 ⟶ 358:
print text
print encr
print decr</
{{out}}
Line 277 ⟶ 367:
=={{header|AutoHotkey}}==
<
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)
}</
{{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}}==
<
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$</
{{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.
<
>>!#:0#-0#1g#,*#<+:v:-1$_^#!:\+1g00p<
\"{"\v>9+2*%"A"+^>$>~>:48*\`#@_::"`"`
*84*`<^4+"4"+g0\_^#!+`*55\`\0::-"A"-*</
{{out}}
Line 369 ⟶ 521:
The decrypter is essentially identical, except for a change of sign on the last line.
<
>>!#:0#-0#1g#,*#<+:v:-1$_^#!:\+1g00p<
\"{"\v>9+2*%"A"+^>$>~>:48*\`#@_::"`"`
*84*`<^4+"4"-g0\_^#!+`*55\`\0::-"A"-*</
{{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.
<
#include <stdlib.h>
#include <string.h>
Line 492 ⟶ 644:
return buf;
}</
{{out}}
Line 504 ⟶ 656:
=={{header|C sharp|C#}}==
<
using System;
Line 549 ⟶ 701:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 560 ⟶ 712:
=={{header|C++}}==
<
#include <string>
using namespace std;
Line 632 ⟶ 784:
cout << "Encrypted: " << encrypted << endl;
cout << "Decrypted: " << decrypted << endl;
}</
{{out}}
Line 642 ⟶ 794:
=={{header|Ceylon}}==
<
function normalize(String text) => text.uppercased.filter(Character.letter);
Line 666 ⟶ 818:
print(encrypted);
print(decrypted);
}</
=={{header|Clojure}}==
Requires Clojure 1.2.
<
(:require [clojure.string :as string]))
Line 698 ⟶ 850:
; decipher a text
(defn decrypt [ciphertext key] (crypt #'- ciphertext key))</
Demonstration code:
<
(: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>
{{out}}
Line 722 ⟶ 874:
=={{header|CoffeeScript}}==
{{trans|D}}
<
code = (char) -> char.charCodeAt()
Line 756 ⟶ 908:
console.log "Original : #{original}"
console.log "Encrypted : #{encrypted}"
console.log "Decrypted : #{decrypt encrypted, key}"</
<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.)
<
(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))</
{{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}}==
<
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));
}</
{{out}}
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Line 830 ⟶ 1,010:
===Alternative Version===
{{trans|Raku}}
<
std.conv;
Line 855 ⟶ 1,035:
immutable encoded = original.encrypt(key);
writeln(encoded, "\n", encoded.decrypt(key));
}</
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
<
import system'culture;
import system'math;
import system'routines;
Line 868 ⟶ 1,179:
class VCipher
{
var TXT := txt.toUpper();
foreach(char t; in TXT)
if (t <
int tmp := t - 65 +
if (tmp < 0) tmp +=
output.write((65
if (pwi == PW.Length) { pwi :=
^
}
Line 901 ⟶ 1,209:
var pw := "VIGENERECIPHER";
console.printLine(s0,
var s1 := v.encrypt(s0, pw, 1);
console.printLine("Encrypted:",s1);
Line 908 ⟶ 1,216:
console.printLine("Press any key to continue..");
console.readChar()
}</
{{out}}
<pre>
Line 921 ⟶ 1,229:
=={{header|Elixir}}==
{{trans|Ruby}}
<
@base ?A
@size ?Z - @base + 1
Line 948 ⟶ 1,256:
IO.puts "Original: #{plaintext}"
IO.puts "Encrypted: #{ciphertext}"
IO.puts "Decrypted: #{recovered}"</
{{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:
<
-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).</
Demonstration code:
<
-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]).</
{{out}}
Line 1,021 ⟶ 1,329:
=={{header|F_Sharp|F#}}==
<
module vigenere =
let keyschedule (key:string) =
Line 1,049 ⟶ 1,357:
let plain = vigenere.decrypt passwd cipher
printfn "%s\n%s" cipher plain
</syntaxhighlight>
<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</
{{out}}
<pre>
Line 1,097 ⟶ 1,405:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
implicit none
Line 1,158 ⟶ 1,466:
end do
end subroutine
end program</
{{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}}==
<
import "fmt"
Line 1,233 ⟶ 1,609:
}
fmt.Println("Deciphered:", dt)
}</
{{out}}
<pre>
Line 1,245 ⟶ 1,621:
=={{header|Haskell}}==
<
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</
{{out}}
<pre>
Line 1,281 ⟶ 1,657:
=={{header|Icon}} and {{header|Unicon}}==
<
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</
The following helper procedures will be of general use with classical cryptography tasks.
<syntaxhighlight 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</
{{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
preprocess=: (#~ e.&ALPHA)@toupper NB. force uppercase and discard non-alpha chars
vigEncryptRC=: 0 vig ALPHA preprocess
vigDecryptRC=: 1 vig ALPHA preprocess</
'''Example Use:'''
<
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
'VIGENERECIPHER' vigDecryptRC 'WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY'
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</
=={{header|Java}}==
{{trans|D}}
<
public static void main(String[] args) {
String key = "VIGENERECIPHER";
Line 1,389 ⟶ 1,756:
return res;
}
}</
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
===Alternative Version===
<syntaxhighlight lang="java">
import com.google.common.collect.Streams;
import java.util.function.Supplier;
Line 1,453 ⟶ 1,820:
}
</syntaxhighlight>
=={{header|JavaScript}}==
<
// helper
function ordA(a) {
Line 1,479 ⟶ 1,846:
console.log(enc);
console.log(dec);</
=={{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.
<
"use strict";
Line 1,518 ⟶ 1,922:
vigenere(enc, key, true) ==> THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGTHELAZYDOGLAZYDOGDOG
=!EXPECTEND!=
*/</
{{out}}
<pre>prompt$ jsish -u vigenereCipher.jsi
[PASS] vigenereCipher.jsi</pre>
=={{header|Julia}}==
{{works with|Julia|
<syntaxhighlight lang="julia">
→(a::Char, b::Char, ± = +) = 'A'+((a-'A')±(b-'A')+26)%26
←(a::Char, b::Char) = →(a,b,-)
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>
"OEMZXYXQMVSQZFKAU"
"IWANTSPEARMINTGUM"
</pre>
=={{header|Kotlin}}==
<
fun vigenere(text: String, key: String, encrypt: Boolean = true): String {
Line 1,611 ⟶ 1,983:
val decoded = vigenere(encoded, key, false)
println(decoded)
}</
{{out}}
Line 1,621 ⟶ 1,993:
=={{header|Lambdatalk}}==
Only texts in uppercases [A-Z] and spaces.
<
{def vigenere
{def vigenere.map
Line 1,645 ⟶ 2,017:
-> ATTACKATDAWN
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<syntaxhighlight 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>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 1,707 ⟶ 2,079:
=={{header|Lua}}==
<
local msg = { _msg:upper():byte( 1, -1 ) }
local key = { _key:upper():byte( 1, -1 ) }
Line 1,748 ⟶ 2,120:
print( encrypted )
print( decrypted )</
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Module[{textCode, keyCode},
textCode =
Line 1,783 ⟶ 2,155:
keyCode[[;; Length@textCode]],
PadRight[keyCode, Length@textCode, keyCode]];
FromCharacterCode[Mod[textCode - keyCode, 26] + 65]]</
<pre>key = "Vigenere Cipher";
Line 1,799 ⟶ 2,171:
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 1,951 ⟶ 2,323:
return melancholy_dane
</syntaxhighlight>
{{out}}
Line 2,025 ⟶ 2,397:
=={{header|Nim}}==
<
proc encrypt(msg, key: string): string =
Line 2,048 ⟶ 2,420:
echo text
echo encr
echo decr</
{{out}}
Line 2,057 ⟶ 2,429:
=={{header|Objeck}}==
{{trans|D}}
<
bundle Default {
class VigenereCipher {
Line 2,103 ⟶ 2,475:
}
}
</syntaxhighlight>
<pre>
encrypt: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Line 2,112 ⟶ 2,484:
{{trans|C}}
<
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;
;;</
Run:
Line 2,167 ⟶ 2,539:
This is a custom, more functional version of the existing solution, due to
'''[https://
{{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://
*)
Line 2,249 ⟶ 2,621:
Printf.printf "Back: %s\n" pt
;;
</syntaxhighlight>
{{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.
<
Do
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Line 2,455 ⟶ 2,827:
End
Exit
</syntaxhighlight>
{{out}}
Line 2,529 ⟶ 2,901:
=={{header|Pascal}}==
<
// The Vigenere cipher in reasonably standard Pascal
// <no library functions: all conversions hand-coded>
Line 2,634 ⟶ 3,006:
END.
</syntaxhighlight>
{{out}}
Line 2,646 ⟶ 3,018:
=={{header|Perl}}==
<
printHelp();
}
Line 2,685 ⟶ 3,057:
}
return $cipher;
}</
Demonstration:
Line 2,707 ⟶ 3,079:
=={{header|Phix}}==
<!--<syntaxhighlight lang="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>
<span style="color: #000000;">DECRYPT</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
<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>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<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>
<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>
<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}}
<
$str = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
Line 2,783 ⟶ 3,159:
?>
</syntaxhighlight>
{{out}}
<pre>Text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 2,791 ⟶ 3,167:
=={{header|PicoLisp}}==
<
(extract
'((C)
Line 2,812 ⟶ 3,188:
(char (+ 65 (% (+ 26 (- C K)) 26))) )
(vigenereKey Str)
(apply circ (vigenereKey Key)) ) ) )</
Test:
<pre>: (vigenereEncrypt
Line 2,823 ⟶ 3,199:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
cypher: procedure options (main); /* 21 September 2012 */
declare t(26) character (26);
Line 2,868 ⟶ 3,244:
end;
end cypher;
</syntaxhighlight>
{{out}}
<pre>
Line 2,877 ⟶ 3,253:
=={{header|PowerShell}}==
<
function Get-VigenereCipher
{
Line 2,961 ⟶ 3,337:
$OutText = $null
}
}</
Usage examples:
<pre>
Line 2,974 ⟶ 3,350:
=={{header|PureBasic}}==
<
;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</
{{out}}
<pre> Plain text = "The quick brown fox jumped over the lazy dogs."
Line 3,043 ⟶ 3,419:
{{Works with|Python|3}}
{{trans|Haskell}}
<
from itertools import starmap, cycle
Line 3,092 ⟶ 3,468:
if __name__ == '__main__':
main()
</syntaxhighlight>
{{out}}
<pre>Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 3,101 ⟶ 3,477:
=={{header|Quackery}}==
<
[ 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$</
{{out}}
Line 3,140 ⟶ 3,516:
=={{header|R}}==
<
# 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</
=={{header|Racket}}==
<
#lang racket
(define chr integer->char)
Line 3,182 ⟶ 3,558:
"VIGENERECIPHER")
"VIGENERECIPHER")
</syntaxhighlight>
{{out}}
<
"BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH"
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2015-11-14}}
<syntaxhighlight lang="raku"
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);</
{{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.
<
CRLF: copy "^M^/" ;; constant for 0D 0A line feed
Line 3,293 ⟶ 3,669:
pad 270x1 button "Quit " [quit]
]
</syntaxhighlight>
{{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===
<
@.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</
{{out|output|text= when using the default internal fields:}}
<pre>
Line 3,340 ⟶ 3,716:
Additional characters can be added by simply appending them to the <big>'''@.1'''</big> variable.
<
@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</
{{out|output|text= when using the default internal fields:}}
<pre>
Line 3,375 ⟶ 3,751:
=={{header|Ring}}==
<
# Project : Vigenère cipher
Line 3,421 ⟶ 3,797:
next
return a
</syntaxhighlight>
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}}==
<
BASE = 'A'.ord
Line 3,453 ⟶ 3,856:
end
end</
Demonstration:
<
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}"</
{{out}}
Line 3,476 ⟶ 3,879:
=={{header|Rust}}==
<
static A: u8 = 'A' as u8;
Line 3,524 ⟶ 3,927:
let decoded = vigenere(key, &encoded, false);
println!("Back: {}", decoded);
}</
=={{header|Scala}}==
Valid characters for messages: A through Z, zero, 1 to 9, and full-stop (.)
<
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>
{{out}}
Line 3,570 ⟶ 3,973:
=={{header|Seed7}}==
<
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;</
{{out}}
Line 3,632 ⟶ 4,035:
=={{header|Sidef}}==
{{trans|Raku}}
<
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)</
{{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}}
<
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>
Test:
<
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>
=={{header|Swift}}==
Line 3,674 ⟶ 4,077:
Can support a larger range of characters, if desired
<
str: String,
minChar: UInt32,
Line 3,798 ⟶ 4,201:
let decoded2 = cipher2.decrypt(encoded2)!
print("Decoded: \(decoded2)")</
{{out}}
Line 3,815 ⟶ 4,218:
=={{header|Tcl}}==
{{trans|C++}}
<
oo::class create Vigenere {
Line 3,850 ⟶ 4,253:
return $out
}
}</
Demonstrating:
<
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"</
{{out}}
<pre>
Line 3,868 ⟶ 4,271:
=={{header|TXR}}==
<
@(do
(defun vig-op (plus-or-minus)
Line 3,890 ⟶ 4,293:
dec: @decoded
check: @check
@(end)</
Here, the TXR pattern language is used to scan letters out of two arguments,
Line 3,909 ⟶ 4,312:
=={{header|TypeScript}}==
<
key: string
Line 3,956 ⟶ 4,359:
})()
</syntaxhighlight>
=={{header|VBA}}==
<
Sub test()
Line 4,023 ⟶ 4,426:
Private Function CharToAscii(s As String) As Byte()
CharToAscii = StrConv(s, vbFromUnicode)
End Function</
{{Out}}
Line 4,031 ⟶ 4,434:
=={{header|VBScript}}==
{{trans|Liberty BASIC}}
<syntaxhighlight 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>
{{Out}}
Line 4,090 ⟶ 4,493:
An alternate implementation using RegExp to filter the input
<syntaxhighlight lang="vb">
'vigenere cypher
option explicit
Line 4,126 ⟶ 4,529:
wscript.echo decrypt(encoded,key)
</syntaxhighlight>
=={{header|Vedit macro language}}==
Line 4,132 ⟶ 4,535:
starting from cursor location.
The user enters the keyword (upper or lower case).
<
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 </
{{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}}
<
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)</
{{out}}
Line 4,226 ⟶ 4,667:
Usage: vigenere KEYWORD <infile.txt >outfile.xxx
<
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
]</
{{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}}
<
upperCase:=["A".."Z"].pump(String);
src=src.toUpper().inCommon(upperCase); // only uppercase
Line 4,270 ⟶ 4,768:
else c - key[i] + 26 ) % 26).toChar()
});
}</
<
"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);</
{{out}}
<pre>
|