Last active
August 19, 2023 02:29
-
-
Save s1037989/ee13f64f13fee38c3fef6d86e79f6dd8 to your computer and use it in GitHub Desktop.
encrypt and decrypt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# $ perl aes.pl decrypt $(perl aes.pl encrypt 123 qaz) # 123 is the key and qaz is the plaintext | |
# qaz # qaz is the plaintext from the 123 ciphertext encryption | |
# $ key=123 ciphertext=08eaad9aec6b6ccba1067aa4de838dd3d5c6423024d5eb087a4e70cd32b9caba | |
# $ perl aes.pl decrypt $key $ciphertext | |
# qaz | |
# $ perl aes.pl decrypt 40bd001563085fc35165329ea1ff5c5ecbdbbeef40bd001563085fc35165329e $ciphertext | |
# qaz # 40b...29e is the actual key derived from 123 and used in the enc/dec | |
# # this allows a simple key of any length or a randomly generated complex key | |
# Now quickly share the ciphertext! | |
# $ key=123 plaintext=qaz | |
# $ perl aes.pl e $key $plaintext | curl -F 'f:1=<-' ix.io | |
# 123 / 40bd001563085fc35165329ea1ff5c5ecbdbbeef40bd001563085fc35165329e # the key printed to STDERR | |
# http://ix.io/4DUQ # the URL the ciphertext was posted to | |
# $ perl aes.pl d $key $(curl -s http://ix.io/4DUQ) # the key and the URL the cipertext was posted to | |
# qaz # the decrypted plaintext! | |
# $ curl -s http://ix.io/4DUS # see, it's just the ciphertext! | |
# 30e7f01c5b09cc8be9fd5a818e90e33de547b8f5661f3137974762cf54680734 | |
# $ perl aes.pl d $key 30e7f01c5b09cc8be9fd5a818e90e33de547b8f5661f3137974762cf54680734 | |
# qaz # and as expected, the decrypted plaintext! | |
use 5.010; | |
use Crypt::CBC qw(); | |
use Digest::SHA qw(sha1_hex); | |
my %cipher_options = (-cipher => 'Rijndael', -literal_key => 1, -header => 'none', -pbkdf =>'pbkdf2'); | |
sub encrypt { | |
my $iv = Crypt::CBC->random_bytes(16); | |
my $cipher = Crypt::CBC->new(%cipher_options, -key => $_[0], -iv => $iv); | |
return $iv.$cipher->encrypt($_[1]); | |
} | |
sub decrypt { | |
my $iv = substr($_[1], 0, 16, ''); | |
my $cipher = Crypt::CBC->new(%cipher_options, -key => $_[0], -iv => $iv); | |
return $cipher->decrypt($_[1]); | |
} | |
my $mode = shift @ARGV; | |
if (substr($mode, 0, 1) eq 'e') { | |
my $key = $ARGV[0] ? substr(sha1_hex($ARGV[0]) x 2, 0, 64) : unpack('H*', Crypt::CBC->random_bytes(32)); | |
printf STDERR "%s\n", $ARGV[0] ? "$ARGV[0] / $key" : $key; | |
printf "%s %s\n", ($ARGV[0] || $key), unpack("H*", encrypt(pack('H*', $key), join "\n", $ARGV[1] || <STDIN>)); | |
} | |
elsif (substr($mode, 0, 1) eq 'd') { | |
my $key = $ARGV[0] =~ /^[0-9a-f]{64}$/ ? $ARGV[0] : substr(sha1_hex($ARGV[0]) x 2, 0, 64); | |
chomp(my $ciphertext = $ARGV[1] || <STDIN>); | |
printf "%s", decrypt(pack("H*", $key), pack("H*", $ciphertext)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment