File: aes.pl

package info (click to toggle)
libcrypt-cbc-perl 2.33-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster
  • size: 212 kB
  • sloc: perl: 1,356; makefile: 2
file content (65 lines) | stat: -rw-r--r-- 1,600 bytes parent folder | download | duplicates (5)
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
#!/usr/bin/perl

use lib '../blib/lib';

use Getopt::Std;
use Crypt::CBC;
use strict vars;

my %options;

getopts('edk:i:o:',\%options) || die <<USAGE;
Usage: aes.pl [options] file1 file2 file3...
   AES encrypt/decrypt files using Cipher Block Chaining mode.
Options:
       -e        encrypt (default)
       -d        decrypt
       -k 'key'  provide key on command line
       -i file   input file
       -o file   output file

(NB: The Rijndael cipher is the basis for AES)
USAGE
    ;

@ARGV = $options{'i'} if $options{'i'};
push(@ARGV,'-') unless @ARGV;
open(STDOUT,">$options{'o'}") or die "$options{'o'}: $!"
    if $options{'o'};

my $key = $options{'k'} || get_key();
my $cipher = Crypt::CBC->new(-key    =>  $key,
			     -cipher => 'Rijndael',
			     -salt   => 1,
			    ) || die "Couldn't create CBC object";
my $decrypt = $options{'d'} and !$options{'e'};
$cipher->start($decrypt ? 'decrypt' : 'encrypt');

my $in;
while (@ARGV) {
    my $file = shift @ARGV;
    open(ARGV,$file) || die "$file: $!";
    print $cipher->crypt($in) while read(ARGV,$in,1024);
    close ARGV;
}
print $cipher->finish;

sub get_key {
    local($|) = 1;
    local(*TTY);
    open(TTY,"/dev/tty");
    my ($key1,$key2);
    system "stty -echo </dev/tty";
    do {
	print STDERR "AES key: ";
        chomp($key1 = <TTY>);
	print STDERR "\r\nRe-type key: ";
        chomp($key2 = <TTY>);
        print STDERR "\r\n";
        print STDERR "The two keys don't match. Try again.\r\n"
            unless $key1 eq $key2;
    } until $key1 eq $key2;
    system "stty echo </dev/tty";
    close(TTY);
    $key1;
}