Jump to content

Caesar cipher: Difference between revisions

Restored the Crystal, Cubescript, D and Dart samples deleted during the CommonLisp changes
(Restored the Crystal, Cubescript, D and Dart samples deleted during the CommonLisp changes)
Line 1,917:
(rot "Nir Pnrfne zbevghev gr fnyhgnag" -13)
Ave Caesar morituri te salutant</pre>
 
=={{header|Crystal}}==
<lang crystal>class String
ALPHABET = ("A".."Z").to_a
 
def caesar_cipher(num)
self.tr(ALPHABET.join, ALPHABET.rotate(num).join)
end
end
 
# demo
encrypted = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".caesar_cipher(5)
decrypted = encrypted.caesar_cipher(-5)
</lang>
 
=={{header|Cubescript}}==
<lang cubescript>alias modn [ mod (+ (mod $arg1 $arg2) $arg2) $arg2 ]
//Cubescript's built-in mod will fail on negative numbers
 
alias cipher [
push alpha [
"A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
"a b c d e f g h i j k l m n o p q r s t u v w x y z"
] [ push chars [] [
loop i (strlen $arg1) [
looplist n $alpha [
if (! (listlen $chars)) [
alias chars (? (> (listindex $n (substr $arg1 $i 1)) -1) $n [])
]
]
alias arg1 (
concatword (substr $arg1 0 $i) (
? (> (listindex $chars (substr $arg1 $i 1)) -1) (
at $chars (
modn (+ (
listindex $chars (substr $arg1 $i 1)
) $arg2) (listlen $chars)
)
) (substr $arg1 $i 1)
) (substr $arg1 (+ $i 1) (strlen $arg1))
)
alias chars []
]
] ]
result $arg1
]
 
alias decipher [
push alpha [
"A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
"a b c d e f g h i j k l m n o p q r s t u v w x y z"
] [ push chars [] [
loop i (strlen $arg1) [
looplist n $alpha [
if (! (listlen $chars)) [
alias chars (? (> (listindex $n (substr $arg1 $i 1)) -1) $n [])
]
]
alias arg1 (
concatword (substr $arg1 0 $i) (
? (> (listindex $chars (substr $arg1 $i 1)) -1) (
at $chars (
modn (- (
listindex $chars (substr $arg1 $i 1)
) $arg2 ) (listlen $chars)
)
) (substr $arg1 $i 1)
) (substr $arg1 (+ $i 1) (strlen $arg1))
)
alias chars []
]
] ]
result $arg1
]</lang>
 
Usage:
<lang>>>> cipher "The Quick Brown Fox Jumps Over The Lazy Dog." 5
> Ymj Vznhp Gwtbs Ktc Ozrux Tajw Ymj Qfed Itl.
>>> decipher "Ymj Vznhp Gwtbs Ktc Ozrux Tajw Ymj Qfed Itl." 5
> The Quick Brown Fox Jumps Over The Lazy Dog.</lang>
 
=={{header|D}}==
<lang d>import std.stdio, std.traits;
 
S rot(S)(in S s, in int key) pure nothrow @safe
if (isSomeString!S) {
auto res = s.dup;
 
foreach (immutable i, ref c; res) {
if ('a' <= c && c <= 'z')
c = ((c - 'a' + key) % 26 + 'a');
else if ('A' <= c && c <= 'Z')
c = ((c - 'A' + key) % 26 + 'A');
}
return res;
}
 
void main() @safe {
enum key = 3;
immutable txt = "The five boxing wizards jump quickly";
writeln("Original: ", txt);
writeln("Encrypted: ", txt.rot(key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
}</lang>
{{out}}
<pre>Original: The five boxing wizards jump quickly
Encrypted: Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted: The five boxing wizards jump quickly</pre>
Simpler in-place version (same output):
<lang d>import std.stdio, std.ascii;
 
void inplaceRot(char[] txt, in int key) pure nothrow {
foreach (ref c; txt) {
if (isLower(c))
c = (c - 'a' + key) % 26 + 'a';
else if (isUpper(c))
c = (c - 'A' + key) % 26 + 'A';
}
}
 
void main() {
enum key = 3;
auto txt = "The five boxing wizards jump quickly".dup;
writeln("Original: ", txt);
txt.inplaceRot(key);
writeln("Encrypted: ", txt);
txt.inplaceRot(26 - key);
writeln("Decrypted: ", txt);
}</lang>
 
A version that uses the standard library (same output):
<lang d>import std.stdio, std.ascii, std.string, std.algorithm;
 
string rot(in string s, in int key) pure nothrow @safe {
auto uppr = uppercase.dup.representation;
bringToFront(uppr[0 .. key], uppr[key .. $]);
auto lowr = lowercase.dup.representation;
bringToFront(lowr[0 .. key], lowr[key .. $]);
return s.translate(makeTrans(letters, assumeUTF(uppr ~ lowr)));
}
 
void main() {
enum key = 3;
immutable txt = "The five boxing wizards jump quickly";
writeln("Original: ", txt);
writeln("Encrypted: ", txt.rot(key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
}</lang>
 
=={{header|Dart}}==
<lang dart>class Caesar {
int _key;
 
Caesar(this._key);
 
int _toCharCode(String s) {
return s.charCodeAt(0);
}
 
String _fromCharCode(int ch) {
return new String.fromCharCodes([ch]);
}
 
String _process(String msg, int offset) {
StringBuffer sb=new StringBuffer();
for(int i=0;i<msg.length;i++) {
int ch=msg.charCodeAt(i);
if(ch>=_toCharCode('A')&&ch<=_toCharCode('Z')) {
sb.add(_fromCharCode(_toCharCode("A")+(ch-_toCharCode("A")+offset)%26));
}
else if(ch>=_toCharCode('a')&&ch<=_toCharCode('z')) {
sb.add(_fromCharCode(_toCharCode("a")+(ch-_toCharCode("a")+offset)%26));
} else {
sb.add(msg[i]);
}
}
return sb.toString();
}
 
String encrypt(String msg) {
return _process(msg, _key);
}
 
String decrypt(String msg) {
return _process(msg, 26-_key);
}
}
 
void trip(String msg) {
Caesar cipher=new Caesar(10);
 
String enc=cipher.encrypt(msg);
String dec=cipher.decrypt(enc);
print("\"$msg\" encrypts to:");
print("\"$enc\" decrypts to:");
print("\"$dec\"");
Expect.equals(msg,dec);
}
 
main() {
Caesar c2=new Caesar(2);
print(c2.encrypt("HI"));
Caesar c20=new Caesar(20);
print(c20.encrypt("HI"));
 
// try a few roundtrips
 
trip("");
trip("A");
trip("z");
trip("Caesar cipher");
trip(".-:/\"\\!");
trip("The Quick Brown Fox Jumps Over The Lazy Dog.");
}</lang>
{{out}}
<pre>JK
BC
"" encrypts to:
"" decrypts to:
""
"A" encrypts to:
"K" decrypts to:
"A"
"z" encrypts to:
"j" decrypts to:
"z"
"Caesar cipher" encrypts to:
"Mkockb mszrob" decrypts to:
"Caesar cipher"
".-:/"\!" encrypts to:
".-:/"\!" decrypts to:
".-:/"\!"
"The Quick Brown Fox Jumps Over The Lazy Dog." encrypts to:
"Dro Aesmu Lbygx Pyh Tewzc Yfob Dro Vkji Nyq." decrypts to:
"The Quick Brown Fox Jumps Over The Lazy Dog."</pre>
 
=={{header|Delphi}}==
See [[#Pascal]].
 
=={{header|Dyalect}}==
 
3,038

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.