Vigenère cipher: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(8 intermediate revisions by 5 users not shown)
Line 1,037:
}</syntaxhighlight>
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">
procfunc$ encr txt$ pw$ d . r$ .
r$ = ""
txt$[] = strchars txt$
for c$ in strchars pw$
Line 1,058 ⟶ 1,159:
.
.
return r$
.
s$ = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
pw$ = "VIGENERECIPHER"
callr$ = encr s$ pw$ 1 r$
print r$
call encr r$ pw$ -1 r$
print r$
print encr r$ pw$ -1
</syntaxhighlight>
 
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 46.x :
<syntaxhighlight lang="elena">import system'text;
import system'culture;
import system'math;
import system'routines;
Line 1,078 ⟶ 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 1,111 ⟶ 1,209:
var pw := "VIGENERECIPHER";
console.printLine(s0,newLinenewLineConstant,pw,newLinenewLineConstant);
var s1 := v.encrypt(s0, pw, 1);
console.printLine("Encrypted:",s1);
Line 3,706 ⟶ 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>
 
Line 4,508 ⟶ 4,633:
{{trans|Kotlin}}
{{libheader|Wren-str}}
<syntaxhighlight lang="ecmascriptwren">import "./str" for Char, Str
 
var vigenere = Fn.new { |text, key, encrypt|
Line 4,574 ⟶ 4,699:
 
=={{header|Zig}}==
{{works with|Zig|0.11.0dev0}}
<syntaxhighlight lang="zig">const std = @import("std");
const std = @import("std");
const Allocator = std.mem.Allocator;
</syntaxhighlight><syntaxhighlight lang="zig">
const Vigenere = enum {
<syntaxhighlight lang="zig">/// Caller owns the returned slice memory.
encode,
fn vigenere(allocator: Allocator, text: []const u8, key: []const u8, encrypt: bool) Allocator.Error![]u8 {
decode,
var dynamic_string = std.ArrayList(u8).init(allocator);
};
var key_index: usize = 0;
</syntaxhighlight><syntaxhighlight lang="zig">
for (text) |letter| {
pub fn main() anyerror!void {
const c = if (std.ascii.isLower(letter)) std.ascii.toUpper(letter) else letter;
// ------------------------------------------ allocator
if (std.ascii.isUpper(c)) {
const k = key[key_index];
const n = if (encrypt) ((c - 'A') + (k - 'A')) else 26 + c - k;
try dynamic_string.append(n % 26 + 'A'); // A-Z
key_index += 1;
key_index %= key.len;
}
}
return dynamic_string.toOwnedSlice();
}</syntaxhighlight>
<syntaxhighlight lang="zig">pub fn main() anyerror!void {
// allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
Line 4,602 ⟶ 4,717:
}
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, true.encode);
defer allocator.free(encoded);
_ = try stdout.print("{s}\n", .{encoded});
 
const decoded = try vigenere(allocator, encoded, key, false.decode);
defer allocator.free(decoded);
_ = try stdout.print("{s}\n", .{decoded});
}
}</syntaxhighlight>
</syntaxhighlight><syntaxhighlight lang="zig">
{{out}}
/// 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>
9,476

edits