I'd like to use Mathematica 10's new Encrypt and Decrypt functions to secure files and folders on my mac.
Here's what I have so far but something goes wrong along the way, since by the end of this process the original file and the encrypted-and-then-decrypted file have different sizes:
(* Step 1: zip the target directory *)
CreateArchive["~/input", "~/input.zip"]
FileByteCount@"~/input.zip"
(*356431*)
(* Step 2: Read + encrypt + export it *)
t = Import["~/input.zip", "Text"];
ByteCount@t
(*532888*)
Export["~/encrypted.txt", Encrypt["my password", t], "Text"];
(* Ok half way there, now for the opposite direction *)
(* Step 3: Read + decrypt it *)
t = Decrypt["my password",
ToExpression@Import["~/encrypted.txt", "Text"]];
ByteCount@t
(*532888 good so far*)
(* Step 4: Export and unzip it *)
Export["~/output.zip", t, "Text"];
FileByteCount /@ {"~/input.zip", "~/output.zip"}
(*{356431, 532809} mismatch, something went wrong*)
Solution
Clear[EncryptPath, DecryptPath];
EncryptPath[path_, pass_, encryptedFileName_:"~/enc.txt"] := Module[
{tmp = "~/enc_temp.zip"},
CreateArchive[path, tmp];
enc = Encrypt[pass, ToExpression @ Import[tmp, "Byte"]];
DeleteFile[tmp];
Export[encryptedFileName, Compress @ ToString @ InputForm @ enc]
]
DecryptPath[path_, pass_, decryptedFileName_:"~/decrypted.zip"] := Module[{enc},
enc = ToExpression @ Uncompress @ Import[path];
Export[decryptedFileName, Decrypt[pass, enc], "Byte"]
]