Vigenère cipher: Difference between revisions
m
→{{header|Wren}}: Minor tidy
Cyril Nocton (talk | contribs) m (→Main version) |
m (→{{header|Wren}}: Minor tidy) |
||
(21 intermediate revisions by 11 users not shown) | |||
Line 22:
{{trans|C++}}
<
V out = ‘’
V j = 0
Line 49:
print(original)
print(‘Encrypted: ’encrypted)
print(‘Decrypted: ’decrypted)</
{{out}}
Line 59:
=={{header|Action!}}==
<
INT i
CHAR c
Line 129:
Test("Crypto is short for cryptography.","ABCDABCDABCDABCDABCDABCDABCD")
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Vigen%C3%A8re_cipher.png Screenshot from Atari 8-bit computer]
Line 150:
=={{header|Ada}}==
<
USE Ada.Text_IO, Ada.Characters.Handling;
Line 206:
END Main;
</syntaxhighlight>
{{out}}
Line 219:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d].}}
<
PROC vigenere cipher = (REF STRING key)VOID:
Line 280:
print(("Encrypted: ", encrypted, new line));
print(("Decrypted: ", decrypted, new line))
)</
{{out}}
<pre>
Line 291:
Lines <code>340,350,430,440</code> could probably been put into some DEF FN, but it would probably have made it harder to read. The maximum length for a string in AppleSoft BASIC is 255 characters.
I have not used the DEF FN MOD(A) function in line <code>450</code> on purpose, as I still would have had to correct for a possible negative value.
<syntaxhighlight lang="applesoft basic">
100 :
110 REM VIGENERE CIPHER
Line 319:
470 K = K + 1: IF K > LEN (K$) THEN K = 1
480 NEXT I
490 PRINT "DECRYPTED TEXT: ";DT$ </
{{out}}
KEY: LEMON
Line 328:
=={{header|Arturo}}==
<
encrypt: function [msg, key][
pos: 0
Line 358:
print text
print encr
print decr</
{{out}}
Line 367:
=={{header|AutoHotkey}}==
<
Text= Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 389:
decoderKey .= Chr(26-(Asc(A_LoopField)-65)+65)
return VigenereCipher(Text, decoderKey)
}</
{{out}}
<pre>Input =Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 399:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
function Filtrar(cadorigen)
filtrado = ""
Line 451:
print "Descifrado: "; DesEncriptar(cadcifrada, llave)
end
</syntaxhighlight>
{{out}}
<pre>
Line 459:
=={{header|BBC BASIC}}==
<
plaintext$ = "ATTACK AT DAWN"
ciphertext$ = FNencrypt(plaintext$, key$)
Line 498:
IF C% >= 97 IF C% <= 122 MID$(A$,A%,1) = CHR$(C%-32)
NEXT
= A$</
{{out}}
<pre>
Line 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 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 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 644:
return buf;
}</
{{out}}
Line 656:
=={{header|C sharp|C#}}==
<
using System;
Line 701:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 712:
=={{header|C++}}==
<
#include <string>
using namespace std;
Line 784:
cout << "Encrypted: " << encrypted << endl;
cout << "Decrypted: " << decrypted << endl;
}</
{{out}}
Line 794:
=={{header|Ceylon}}==
<
function normalize(String text) => text.uppercased.filter(Character.letter);
Line 818:
print(encrypted);
print(decrypted);
}</
=={{header|Clojure}}==
Requires Clojure 1.2.
<
(:require [clojure.string :as string]))
Line 850:
; decipher a text
(defn decrypt [ciphertext key] (crypt #'- ciphertext key))</
Demonstration code:
<
(:require [org.rosettacode.clojure.vigenere :as vigenere]))
Line 864:
(doall (map (fn [[k v]] (printf "%9s: %s\n" k v))
[ ["Original" plaintext] ["Key" key] ["Encrypted" ciphertext] ["Decrypted" recovered] ])))
</syntaxhighlight>
{{out}}
Line 874:
=={{header|CoffeeScript}}==
{{trans|D}}
<
code = (char) -> char.charCodeAt()
Line 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 914:
=={{header|Common Lisp}}==
====Main
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 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!
Line 947:
dec: BEWARETHEJABBERWOCKTHEJAWSTHATTHECLAWSTHATCATCH</pre>
====
No string to circular list conversion here.
1. Program
<
(defun strip (s)
(string-upcase (remove-if-not 'alpha-char-p s)))
(defun vigenere (
(let ((
(map 'string
(lambda (c)
(setf i (mod (1+ i) (length key)))
(char +a+ (mod (+ (position c +a+) (*
2. Execution
<pre>(vigenere "« Through the Looking-Glass »" "Lewis Carroll")
(vigenere "ELNWMIHKYSWZZOEVYILRJG" "Lewis Carroll" :
{{out}}
<pre>
Line 975:
=={{header|D}}==
<
string encrypt(in string txt, in string key) pure @safe
Line 1,003:
immutable encoded = original.encrypt(key);
writeln(encoded, "\n", encoded.decrypt(key));
}</
{{out}}
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Line 1,010:
===Alternative Version===
{{trans|Raku}}
<
std.conv;
Line 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 1,048 ⟶ 1,179:
class VCipher
{
string PW
var TXT
foreach(char t; in TXT)
{
int tmp := t - 65 + d * (pw[pwi] -
if (tmp < 0) tmp +=
^ output.Value
}
}
Line 1,081 ⟶ 1,209:
var pw := "VIGENERECIPHER";
console.printLine(s0,
var s1 := v.encrypt(s0, pw, 1);
console.printLine("Encrypted:",s1);
Line 1,088 ⟶ 1,216:
console.printLine("Press any key to continue..");
console.readChar()
}</
{{out}}
<pre>
Line 1,101 ⟶ 1,229:
=={{header|Elixir}}==
{{trans|Ruby}}
<
@base ?A
@size ?Z - @base + 1
Line 1,128 ⟶ 1,256:
IO.puts "Original: #{plaintext}"
IO.puts "Encrypted: #{ciphertext}"
IO.puts "Decrypted: #{recovered}"</
{{out}}
Line 1,139 ⟶ 1,267:
=={{header|Erlang}}==
Erlang is not ideal for string manipulation, but with some utility function definitions it can express this fairly elegantly:
<
-module(vigenere).
-export([encrypt/2, decrypt/2]).
Line 1,185 ⟶ 1,313:
encrypt(Text, Key) -> crypt(Text, Key, fun encipher/2).
decrypt(Text, Key) -> crypt(Text, Key, fun decipher/2).</
Demonstration code:
<
-import(vigenere,[encrypt/2, decrypt/2]).
main(_) ->
Line 1,194 ⟶ 1,322:
CipherText = encrypt("Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", Key),
RecoveredText = decrypt(CipherText, Key),
io:fwrite("Ciphertext: ~s~nDecrypted: ~s~n", [CipherText, RecoveredText]).</
{{out}}
Line 1,201 ⟶ 1,329:
=={{header|F_Sharp|F#}}==
<
module vigenere =
let keyschedule (key:string) =
Line 1,229 ⟶ 1,357:
let plain = vigenere.decrypt passwd cipher
printfn "%s\n%s" cipher plain
</syntaxhighlight>
<pre>C:\src\fsharp>fsi vigenere.fsx
Line 1,237 ⟶ 1,365:
=={{header|Factor}}==
<syntaxhighlight lang="text">USING: arrays ascii formatting kernel math math.functions
math.order sequences ;
IN: rosetta-code.vigenere-cipher
Line 1,266 ⟶ 1,394:
vigenere-decrypt "Decrypted: %s\n" printf ;
MAIN: main</
{{out}}
<pre>
Line 1,277 ⟶ 1,405:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
implicit none
Line 1,338 ⟶ 1,466:
end do
end subroutine
end program</
{{out}}
<pre> Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 1,347 ⟶ 1,475:
=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<
Function Filtrar(cadorigen As String) As String
Dim As String letra
Line 1,402 ⟶ 1,530:
Print "Descifrado: "; DesEncriptar(cadcifrada, llave)
Sleep
</syntaxhighlight>
{{out}}
<pre>
Line 1,413 ⟶ 1,541:
=={{header|Go}}==
<
import "fmt"
Line 1,481 ⟶ 1,609:
}
fmt.Println("Deciphered:", dt)
}</
{{out}}
<pre>
Line 1,493 ⟶ 1,621:
=={{header|Haskell}}==
<
import Text.Printf
Line 1,519 ⟶ 1,647:
decr = decrypt key encr
printf " Input: %s\n Key: %s\nEncrypted: %s\nDecrypted: %s\n"
text key encr decr</
{{out}}
<pre>
Line 1,529 ⟶ 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,552 ⟶ 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,568 ⟶ 1,696:
text ? (s := "", until pos(0) do s ||:= " " || move(5)|tab(0))
return s[2:0]
end</
{{libheader|Icon Programming Library}}
Line 1,582 ⟶ 1,710:
=={{header|J}}==
'''Solution:'''<br>
Using [https://github.com/jsoftware/convert_misc/blob/master/vig.ijs <code>vig</code>] from the [[j:Addons/convert/misc/vig|convert/misc/vig addon]]:
<syntaxhighlight lang="j">ALPHA=: (65,:26) ];.0 a. NB. Character Set
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,637 ⟶ 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,701 ⟶ 1,820:
}
</syntaxhighlight>
=={{header|JavaScript}}==
<
// helper
function ordA(a) {
Line 1,727 ⟶ 1,846:
console.log(enc);
console.log(dec);</
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<
# retain alphabetic characters only
def n:
Line 1,755 ⟶ 1,874:
| (., example("VIGENERECIPHER")),
"",
(., example("ROSETTACODE"))</
{{out}}
<pre>
Line 1,768 ⟶ 1,887:
=={{header|Jsish}}==
From Javascript entry.
<
"use strict";
Line 1,803 ⟶ 1,922:
vigenere(enc, key, true) ==> THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGTHELAZYDOGLAZYDOGDOG
=!EXPECTEND!=
*/</
{{out}}
Line 1,812 ⟶ 1,931:
=={{header|Julia}}==
{{works with|Julia|1.5}}
<syntaxhighlight lang="julia">
→(a::Char, b::Char, ± = +) = 'A'+((a-'A')±(b-'A')+26)%26
←(a::Char, b::Char) = →(a,b,-)
Line 1,829 ⟶ 1,948:
println(cyphertext)
println(cyphertext ← "Gimme!")
</syntaxhighlight>
{{out}}
Line 1,839 ⟶ 1,958:
=={{header|Kotlin}}==
<
fun vigenere(text: String, key: String, encrypt: Boolean = true): String {
Line 1,864 ⟶ 1,983:
val decoded = vigenere(encoded, key, false)
println(decoded)
}</
{{out}}
Line 1,874 ⟶ 1,993:
=={{header|Lambdatalk}}==
Only texts in uppercases [A-Z] and spaces.
<
{def vigenere
{def vigenere.map
Line 1,898 ⟶ 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,952 ⟶ 2,071:
next
end function
</syntaxhighlight>
Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 1,960 ⟶ 2,079:
=={{header|Lua}}==
<
local msg = { _msg:upper():byte( 1, -1 ) }
local key = { _key:upper():byte( 1, -1 ) }
Line 2,001 ⟶ 2,120:
print( encrypted )
print( decrypted )</
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Module[{textCode, keyCode},
textCode =
Line 2,036 ⟶ 2,155:
keyCode[[;; Length@textCode]],
PadRight[keyCode, Length@textCode, keyCode]];
FromCharacterCode[Mod[textCode - keyCode, 26] + 65]]</
<pre>key = "Vigenere Cipher";
Line 2,052 ⟶ 2,171:
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 2,204 ⟶ 2,323:
return melancholy_dane
</syntaxhighlight>
{{out}}
Line 2,278 ⟶ 2,397:
=={{header|Nim}}==
<
proc encrypt(msg, key: string): string =
Line 2,301 ⟶ 2,420:
echo text
echo encr
echo decr</
{{out}}
Line 2,310 ⟶ 2,429:
=={{header|Objeck}}==
{{trans|D}}
<
bundle Default {
class VigenereCipher {
Line 2,356 ⟶ 2,475:
}
}
</syntaxhighlight>
<pre>
encrypt: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Line 2,365 ⟶ 2,484:
{{trans|C}}
<
let str = String.uppercase src in
let key = String.uppercase key in
Line 2,405 ⟶ 2,524:
Printf.printf "Code: %s\n" cod;
Printf.printf "Back: %s\n" dec;
;;</
Run:
Line 2,420 ⟶ 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,502 ⟶ 2,621:
Printf.printf "Back: %s\n" pt
;;
</syntaxhighlight>
{{out}}
<pre>
Line 2,514 ⟶ 2,633:
{{trans|NetRexx}}
A reworking of the [[#NetRexx|NetRexx]] version using Open Object Rexx but shouldn't take much to translate to Classic Rexx.
<
Do
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Line 2,708 ⟶ 2,827:
End
Exit
</syntaxhighlight>
{{out}}
Line 2,782 ⟶ 2,901:
=={{header|Pascal}}==
<
// The Vigenere cipher in reasonably standard Pascal
// <no library functions: all conversions hand-coded>
Line 2,887 ⟶ 3,006:
END.
</syntaxhighlight>
{{out}}
Line 2,899 ⟶ 3,018:
=={{header|Perl}}==
<
printHelp();
}
Line 2,938 ⟶ 3,057:
}
return $cipher;
}</
Demonstration:
Line 2,960 ⟶ 3,079:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">ENCRYPT</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span>
Line 2,985 ⟶ 3,104:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Original: %s\nEncrypted: %s\nDecrypted: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">})</span>
<!--</
{{Out}}
<pre>
Line 2,995 ⟶ 3,114:
=={{header|PHP}}==
{{trans|C}}
<
$str = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
Line 3,040 ⟶ 3,159:
?>
</syntaxhighlight>
{{out}}
<pre>Text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 3,048 ⟶ 3,167:
=={{header|PicoLisp}}==
<
(extract
'((C)
Line 3,069 ⟶ 3,188:
(char (+ 65 (% (+ 26 (- C K)) 26))) )
(vigenereKey Str)
(apply circ (vigenereKey Key)) ) ) )</
Test:
<pre>: (vigenereEncrypt
Line 3,080 ⟶ 3,199:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
cypher: procedure options (main); /* 21 September 2012 */
declare t(26) character (26);
Line 3,125 ⟶ 3,244:
end;
end cypher;
</syntaxhighlight>
{{out}}
<pre>
Line 3,134 ⟶ 3,253:
=={{header|PowerShell}}==
<
function Get-VigenereCipher
{
Line 3,218 ⟶ 3,337:
$OutText = $null
}
}</
Usage examples:
<pre>
Line 3,231 ⟶ 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,291 ⟶ 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,300 ⟶ 3,419:
{{Works with|Python|3}}
{{trans|Haskell}}
<
from itertools import starmap, cycle
Line 3,349 ⟶ 3,468:
if __name__ == '__main__':
main()
</syntaxhighlight>
{{out}}
<pre>Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Line 3,358 ⟶ 3,477:
=={{header|Quackery}}==
<
[ upper
dup char A char Z 1+ within
Line 3,389 ⟶ 3,508:
say "Encrypted: " $ "Kahlil Gibran" encrypt dup echo$ cr
say "Decrypted: " $ "Kahlil Gibran" decrypt echo$</
{{out}}
Line 3,397 ⟶ 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,414 ⟶ 3,533:
# WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
message(vigen("WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY", "vigenerecipher", decrypt = T))
# BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</
=={{header|Racket}}==
<
#lang racket
(define chr integer->char)
Line 3,439 ⟶ 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,459 ⟶ 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,473 ⟶ 3,592:
to add some more features to make it actually "useful" :-) So not only can u encrypt any character (because the crypted message will be base 64 encoded), but it also includes a Gui.
the Gui window has buttons to access the clipboard too - so u can get the original text from clipboard and put the crypted message back again. To execute it,simply download the latest red.exe (about 1,1 MB size! ) from red-lang.org. This program can also be compiled to an .exe (+ red runtime.dll ) by simply execute <pre>red.exe -c vign1.red</pre> or <pre>red.exe -r vign1.red</pre> which creates a single .exe file whithout the need for any .dll . should be working on windows , linux ( under wine ) and mac OS.
<
CRLF: copy "^M^/" ;; constant for 0D 0A line feed
Line 3,550 ⟶ 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,558 ⟶ 3,677:
=={{header|REXX}}==
===uppercase text only===
<
@.1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
L=length(@.1)
Line 3,584 ⟶ 3,703:
dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1 )
end /*j*/
return dMsg</
{{out|output|text= when using the default internal fields:}}
<pre>
Line 3,597 ⟶ 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,623 ⟶ 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,632 ⟶ 3,751:
=={{header|Ring}}==
<
# Project : Vigenère cipher
Line 3,678 ⟶ 3,797:
next
return a
</syntaxhighlight>
Output:
<pre>
Line 3,685 ⟶ 3,804:
ciphertext = LXFOPVEFRNHR
decrypted = ATTACKATDAWN
</pre>
=={{header|RPL}}==
As the encoding and decoding programs would differ by only one instruction (plus instead of minus), they have been merged into a single function that decodes if the input text is in uppercase only, and encodes otherwise. To encode a uppercase-only text, a space (or any punctuation sign) must be put somwehere.
≪ → key
≪ 1 CF { }
1 3 PICK SIZE '''FOR''' j
OVER j DUP SUB NUM
'''IF''' DUP 97 ≥ OVER 122 ≤ AND '''THEN''' 32 - '''END'''
'''IF''' DUP 65 ≥ OVER 90 ≤ AND '''THEN''' 65 - + '''ELSE''' 1 SF DROP '''END'''
'''NEXT'''
SWAP DROP ""
1 3 PICK SIZE '''FOR''' j
OVER j GET
key j 1 - key SIZE MOD 1 + DUP SUB NUM 64 -
'''IF''' 1 FC? '''THEN''' + '''ELSE''' - '''END'''
26 MOD 65 + CHR +
'''NEXT'''
SWAP DROP
≫ ≫ ‘<span style="color:blue">VIGENERE</span>’ STO
"Beware the Jabberwock!" <span style="color:blue">VIGENERE</span>
DUP <span style="color:blue">VIGENERE</span>
{{out}}
<pre>
2: "FVPVDZBCIATWNZZRSTD"
1: "BEWARETHEJABBERWOCK"
</pre>
=={{header|Ruby}}==
<
BASE = 'A'.ord
Line 3,710 ⟶ 3,856:
end
end</
Demonstration:
<
plaintext = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'
Line 3,723 ⟶ 3,869:
puts "Original: #{plaintext}"
puts "Encrypted: #{ciphertext}"
puts "Decrypted: #{recovered}"</
{{out}}
Line 3,733 ⟶ 3,879:
=={{header|Rust}}==
<
static A: u8 = 'A' as u8;
Line 3,781 ⟶ 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,820 ⟶ 3,966:
println("Encrypt text ABC => " + Vigenere.encrypt("ABC", "KEY"))
println("Decrypt text KFA => " + Vigenere.decrypt("KFA", "KEY"))
</syntaxhighlight>
{{out}}
Line 3,827 ⟶ 3,973:
=={{header|Seed7}}==
<
const func string: vigenereCipher (in string: source, in var string: keyword) is func
Line 3,877 ⟶ 4,023:
decrypted := vigenereDecipher(encrypted, keyword);
writeln("Decrypted: " <& decrypted);
end func;</
{{out}}
Line 3,889 ⟶ 4,035:
=={{header|Sidef}}==
{{trans|Raku}}
<
func v2s(v) { v »%» 26 »+» 65 -> map{.chr}.join }
Line 3,900 ⟶ 4,046:
say red
say (var black = blacken(red, key))
say redden(black, key)</
{{out}}
<pre>
Line 3,911 ⟶ 4,057:
in the following code, the cypher should consist of upper-case characters only. If that is not guaranteed, apply prep to it before passing it to encrypt/decrypt..
{{works with|Smalltalk/X}}
<
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,925 ⟶ 4,071:
crypted -> 'WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY'
plain2 -> 'BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH'
</syntaxhighlight>
=={{header|Swift}}==
Line 3,931 ⟶ 4,077:
Can support a larger range of characters, if desired
<
str: String,
minChar: UInt32,
Line 4,055 ⟶ 4,201:
let decoded2 = cipher2.decrypt(encoded2)!
print("Decoded: \(decoded2)")</
{{out}}
Line 4,072 ⟶ 4,218:
=={{header|Tcl}}==
{{trans|C++}}
<
oo::class create Vigenere {
Line 4,107 ⟶ 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 4,115 ⟶ 4,261:
puts $original
puts "Encrypted: $encrypted"
puts "Decrypted: $decrypted"</
{{out}}
<pre>
Line 4,125 ⟶ 4,271:
=={{header|TXR}}==
<
@(do
(defun vig-op (plus-or-minus)
Line 4,147 ⟶ 4,293:
dec: @decoded
check: @check
@(end)</
Here, the TXR pattern language is used to scan letters out of two arguments,
Line 4,166 ⟶ 4,312:
=={{header|TypeScript}}==
<
key: string
Line 4,213 ⟶ 4,359:
})()
</syntaxhighlight>
=={{header|VBA}}==
<
Sub test()
Line 4,280 ⟶ 4,426:
Private Function CharToAscii(s As String) As Byte()
CharToAscii = StrConv(s, vbFromUnicode)
End Function</
{{Out}}
Line 4,288 ⟶ 4,434:
=={{header|VBScript}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="vb">
Function Encrypt(text,key)
text = OnlyCaps(text)
Line 4,336 ⟶ 4,482:
WScript.StdOut.WriteLine "Encrypted: " & Encrypt(orig_text,orig_key)
WScript.StdOut.WriteLine "Decrypted: " & Decrypt(Encrypt(orig_text,orig_key),orig_key)
</syntaxhighlight>
{{Out}}
Line 4,347 ⟶ 4,493:
An alternate implementation using RegExp to filter the input
<syntaxhighlight lang="vb">
'vigenere cypher
option explicit
Line 4,383 ⟶ 4,529:
wscript.echo decrypt(encoded,key)
</syntaxhighlight>
=={{header|Vedit macro language}}==
Line 4,389 ⟶ 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,436 ⟶ 4,582:
}
Num_Pop(6,9)
Return </
{{out}}
Line 4,444 ⟶ 4,590:
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
const
(
key = "VIGENERECIPHER"
text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
)
fn main() {
encoded := vigenere(text, key, true)
println(encoded)
decoded := vigenere(encoded, key, false)
println(decoded)
}
fn vigenere(str string, key string, encrypt bool) string {
mut txt :=''
mut chr_arr := []u8{}
mut kidx, mut cidx := 0, 0
if encrypt == true {txt = str.to_upper()}
else {txt = str}
for chr in txt {
if (chr > 64 && chr < 91) == false {continue}
if encrypt == true {cidx = (chr + key[kidx] - 130) % 26}
else {cidx = (chr - key[kidx] + 26) % 26}
chr_arr << u8(cidx + 65)
kidx = (kidx + 1) % key.len
}
return chr_arr.bytestr()
}
</syntaxhighlight>
{{out}}
<pre>
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>
Line 4,449 ⟶ 4,633:
{{trans|Kotlin}}
{{libheader|Wren-str}}
<
var vigenere = Fn.new { |text, key, encrypt|
Line 4,471 ⟶ 4,655:
System.print(encoded)
var decoded = vigenere.call(encoded, key, false)
System.print(decoded)</
{{out}}
Line 4,483 ⟶ 4,667:
Usage: vigenere KEYWORD <infile.txt >outfile.xxx
<
int Neg, C, Len, I, Key;
char KeyWord(80);
Line 4,503 ⟶ 4,687:
until C=$1A; \EOF
ChOut(0, $1A); \encrypted file must end with EOF otherwise the decode will hang
]</
{{out}}
Line 4,513 ⟶ 4,697:
outfile = PACKMYBOXWITHFIVEDOZENLIQUORJUGS
</pre>
=={{header|Zig}}==
{{works with|Zig|0.11.0}}
<syntaxhighlight lang="zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
</syntaxhighlight><syntaxhighlight lang="zig">
const Vigenere = enum {
encode,
decode,
};
</syntaxhighlight><syntaxhighlight lang="zig">
pub fn main() anyerror!void {
// ------------------------------------------ allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const ok = gpa.deinit();
std.debug.assert(ok == .ok);
}
const allocator = gpa.allocator();
// --------------------------------------------- stdout
const stdout = std.io.getStdOut().writer();
// ----------------------------------------------------
const key = "VIGENERECIPHER";
const text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
const encoded = try vigenere(allocator, text, key, .encode);
defer allocator.free(encoded);
try stdout.print("{s}\n", .{encoded});
const decoded = try vigenere(allocator, encoded, key, .decode);
defer allocator.free(decoded);
try stdout.print("{s}\n", .{decoded});
}
</syntaxhighlight><syntaxhighlight lang="zig">
/// Caller owns the returned slice memory.
fn vigenere(allocator: Allocator, text: []const u8, key: []const u8, mode: Vigenere) Allocator.Error![]u8 {
var dynamic_string = std.ArrayList(u8).init(allocator);
var key_index: usize = 0;
for (text) |letter| {
const c = if (std.ascii.isLower(letter)) std.ascii.toUpper(letter) else letter;
if (std.ascii.isUpper(c)) {
const k = key[key_index];
const n = switch (mode) {
.encode => ((c - 'A') + (k - 'A')),
.decode => 26 + c - k,
};
try dynamic_string.append(n % 26 + 'A'); // A-Z
key_index += 1;
key_index %= key.len;
}
}
return dynamic_string.toOwnedSlice();
}
</syntaxhighlight>{{out}}
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
=={{header|zkl}}==
{{trans|C}}
<
upperCase:=["A".."Z"].pump(String);
src=src.toUpper().inCommon(upperCase); // only uppercase
Line 4,527 ⟶ 4,768:
else c - key[i] + 26 ) % 26).toChar()
});
}</
<
"the claws that catch!";
key := "Vigenere Cipher";
Line 4,536 ⟶ 4,777:
cod := encipher(str, key, True); println("Code: ", cod);
dec := encipher(cod, key, False); println("Back: ", dec);</
{{out}}
<pre>
|