1#!/usr/bin/env perl
2
3##
4## Author......: See docs/credits.txt
5## License.....: MIT
6##
7
8use strict;
9use warnings;
10
11#
12# Helper functions
13#
14
15sub read_bytes
16{
17  my $handle = shift;
18  my $size   = shift;
19
20  my $data = "";
21
22  read ($handle, $data, $size);
23
24  # this function is very strict:
25  # it only returns something if all the bytes can be read
26
27  if (length ($data) != $size)
28  {
29    die "ERROR: Couldn't read data from the file. Maybe incorrect file format?\n";
30  }
31
32  return $data;
33}
34
35#
36# Start
37#
38
39if (scalar (@ARGV) != 1)
40{
41  die "usage: $0 file.txt.aes\n";
42}
43
44my $file_name = $ARGV[0];
45
46my $file_handle;
47
48if (! open ($file_handle, "<", $file_name))
49{
50  die "ERROR: Couldn't open file '$file_name'\n";
51}
52
53binmode ($file_handle);
54
55
56# Signature:
57
58my $signature = read_bytes ($file_handle, 3);
59
60if ($signature ne "AES")
61{
62  die "ERROR: The file doesn't seem to be a correct aescrypt file (signature mismatch)\n";
63}
64
65# Version
66
67my $version = read_bytes ($file_handle, 1);
68
69if ($version ne "\x02")
70{
71  die "ERROR: Currently only aescrypt file version 2 is supported by this script\n";
72}
73
74
75read_bytes ($file_handle, 1); # reservered/skip (normally should be just \x00)
76
77
78# Loop over the extensions until we got extension size 0
79
80my $extension_size = read_bytes ($file_handle, 2);
81
82while ($extension_size ne "\x00\x00")
83{
84  my $skip_size = unpack ("S>", $extension_size); # 16-bit lengths
85
86  read_bytes ($file_handle, $skip_size); # skip the extension
87
88  $extension_size = read_bytes ($file_handle, 2);
89}
90
91# IV (for KDF)
92
93my $iv = read_bytes ($file_handle, 16);
94
95
96# IV (encrypted IV for AES decryption)
97
98my $iv_enc = read_bytes ($file_handle, 16);
99
100
101# key_enc
102
103my $key_enc = read_bytes ($file_handle, 32);
104
105
106# HMAC
107
108my $hmac = read_bytes ($file_handle, 32);
109
110#
111# Hex conversion
112#
113
114$iv      = unpack ("H*", $iv);
115$iv_enc  = unpack ("H*", $iv_enc);
116$key_enc = unpack ("H*", $key_enc);
117$hmac    = unpack ("H*", $hmac);
118
119#
120# Final output
121#
122
123print sprintf ("\$aescrypt\$1*%s*%s*%s*%s\n", $iv, $iv_enc, $key_enc, $hmac);
124
125#
126# Cleanup
127#
128
129close ($file_handle);
130
131exit (0);
132