Cryptography Reference
In-Depth Information
4.5.2.1 Encrypting and Decrypting Files
Next, we give functions to encrypt and decrypt binary files using AES-based
OFB or CTR modes. We use the functions bytestofile , filetobytes and
checkkey , given in Appendix A, as well as the previously defined functions
AESModes and selectiv . The input for the encryption function below is the
AES key (as a hex string or a list of bytes), the name of the file to be encrypted
or decrypted (as a string delimited by double quotes), the name of the file where
the result of the encryption/decryption operation is to be written, the mode of oper-
ation (a name equal to OFB or CTR with the latter as default) and three optional
keyword parameters. The first of them, iv is for the IV and, by default, it selects
the IV by calling selectiv() , but can also be fed with an externally generated
random IV. The parameter filecheck is used for file checking (in order to pre-
vent inadvertently overwriting an existing file) and logoutput specifies (with the
same format as in bytestofile and with default value terminal ) where the
output log is to be written. By default, the function checks whether a file of the same
name exists in the working directory but this check can be overridden by specifying
filecheck = false .
> AESFileEncrypt := proc(key, filename::string, cfilename::string, mode::name:=CTR,
{iv:=selectiv(), filecheck::truefalse:=true, logoutput::name:=terminal})
local k, f;
k := checkkey(key);
f := filetobytes(filename);
f := AESModes(k, f, mode, iv);
bytestofile(f, cfilename, filecheck, logoutput)
end proc:
The file decryption function is similar, except that now the iv parameter ismissing
because the IV is included in the ciphertext:
> AESFileDecrypt := proc(key, cfilename::string, filename::string, mode::name:=CTR,
{filecheck::truefalse:= true, logoutput::name:=terminal})
local k, f;
k := checkkey(key);
f := filetobytes(cfilename);
f := AESModes(k, f, mode);
bytestofile(f, filename, filecheck, logoutput)
end proc:
Example 4.8 Let us check the behavior of these functions.We generate a list of bytes,
write it to a file named "testfile" in the current directory and encrypt it in CTR
mode—with default values and using the previously defined key k192 —writing the
ciphertext to a file named "ctestfile" :
> k192 := "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b":
testlist := RandomTools:-Generate(list(nonnegint(range = 255), 16381));
testfile := bytestofile(testlist, "testfile");
16381 bytes saved to testfile
> AESFileEncrypt(k192, "testfile", "ctestfile");
16397 bytes saved to ctestfile
Next, we decrypt the previously encrypted file, we read it from disk to a list and we
compare this list with the one originally used to generate the file that was encrypted
Search WWH ::




Custom Search