-
Notifications
You must be signed in to change notification settings - Fork 34
/
simple_XOR_cipher.pl
73 lines (52 loc) · 1.59 KB
/
simple_XOR_cipher.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/perl
# Author: Trizen
# Date: 03 March 2022
# https://github.com/trizen
# A simple encryption cihpher, using XOR with SHA-512 of the key and substring shuffling.
# WARNING: should NOT be used for encrypting real-world data.
# See also:
# https://en.wikipedia.org/wiki/Block_cipher
# https://en.wikipedia.org/wiki/XOR_cipher
use 5.020;
use strict;
use warnings;
use experimental qw(signatures);
use ntheory qw(random_bytes);
use Digest::SHA qw(sha512);
use constant {
ROUNDS => 13, # how many encryption rounds to perform
};
sub encrypt ($str, $key) {
if (length($str) > 64) {
die "Input string is too long. Max size: 64\n";
}
if (length($str) != 64) {
$str .= random_bytes(64 - length($str));
}
$key = sha512($key);
$str ^= $key;
my $i = my $l = length($str);
for my $k (1 .. ROUNDS) {
$str =~ s/(.{$i})(.)/$2$1/sg while (--$i > 0);
$str ^= sha512($key . $k);
$str =~ s/(.{$i})(.)/$2$1/sg while (++$i < $l);
$str ^= sha512($k . $key);
}
return $str;
}
sub decrypt ($str, $key, $len = 64) {
$key = sha512($key);
my $i = my $l = length($str);
for my $k (reverse(1 .. ROUNDS)) {
$str ^= sha512($k . $key);
$str =~ s/(.)(.{$i})/$2$1/sg while (--$i > 0);
$str ^= sha512($key . $k);
$str =~ s/(.)(.{$i})/$2$1/sg while (++$i < $l);
}
$str ^= $key;
$str = substr($str, 0, $len);
return $str;
}
my $text = "Hello, world!";
my $key = "foo";
say decrypt(encrypt($text, $key), $key, length($text)); #=> "Hello, world!"