Encrypt[] and Decrypt[] perform as expected. As an exercise I wanted to write encrypted raw binary data to disk for a block based cipher. In such a case there will be an initialization vector which guards against detection of repeated messages. Encrypt[] creates this for you each time the function is called on a message. One could write the resulting EncryptedObject out to disk using an appropriate file format. However, in my case I wanted to write out only the raw data. To do this I would also need to store the initialization vector data along side the encrypted file. That makes two files per message. To decode the file the initialization vector would need to be read back in. Below is the code I used.
$fPrefix = "em"; (* em = encrypted message *)
rndFileName[] :=
StringJoin[{$fPrefix, ToString@RandomInteger[{10000, 20000}]}]
ivExtract[encObject_EncryptedObject] :=
ByteArray@Normal@((Association @@ encObject)["InitializationVector"])
ivWrite[outfile_, encObject_EncryptedObject] := (
iv = Normal@ivExtract[encObject];
BinaryWrite[outfile, iv];
Close[outfile];
ByteArray@iv
)
encWrite[outfile_, encObject_EncryptedObject] := (
BinaryWrite[outfile, Normal@Normal@encObject];
Close[outfile])
encToFile[key_, msg_String, fname_String] := Module[{eo, iv},
eo = Encrypt[key, msg];
encWrite[fname, eo];
ivWrite[fname <> ".iv", eo];
eo
]
dec[key_, data_ByteArray, iv_ByteArray] :=
Decrypt[key,
EncryptedObject[<|"Data" -> data, "InitializationVector" -> iv,
"OriginalForm" -> String|>]]
decFile[key_, fname_String] := Module[{data, dataIV},
dataIV = ByteArray@BinaryReadList[fname <> ".iv"];
data = ByteArray@BinaryReadList[fname];
dec[key, data, dataIV]
]
Usage follows:
SetDirectory[$HomeDirectory];
key = GenerateSymmetricKey[
Method -> <|"Cipher" -> "Blowfish", "KeySize" -> 192,
"BlockMode" -> "CFB"|>];
key >> "testKeySym-bf-cfb-192"; (* save the key*)
(* key = <<
"testKeySym-bf-cfb-192" ; *)
message = "
Little Secret Hoppy Ale / 55 IBU / 6% ABV
Little Secret falls somewhere between Session IPA and American Pale \
Ale. Using a blend of three malts and four hops, Little Secret \
presents an herbal, fruity hop character punctuated by a citrus \
bitterness that lasts through the finish.";
outfile = rndFileName[];
encToFile[key, message, outfile];
In[960]:= FileNames[outfile <> "*"]
Out[960]= {"em15466", "em15466.iv"}
In[959]:= BinaryReadList[outfile][[;; 15]]
Out[959]= {73, 207, 234, 169, 245, 89, 128, 25, 232, 22, 114, 44, \
163, 242, 213}
In[958]:= decFile[key, outfile]
Out[958]= "
Little Secret Hoppy Ale / 55 IBU / 6% ABV
Little Secret falls somewhere between Session IPA and American Pale \
Ale. Using a blend of three malts and four hops, Little Secret \
presents an herbal, fruity hop character punctuated by a citrus \
bitterness that lasts through the finish."