6 /// To read and write metadata.
7 type internal Metadata (d
: (string * string) list
) =
8 /// Read metadata from a stream.
9 new (stream
: Stream) =
10 let reader = new BinaryReader (stream
)
11 let length = reader.ReadByte () |> int
12 Metadata ([for _
in 1 .. length -> reader.ReadString (), reader.ReadString ()])
14 /// Write metadata to a stream.
15 member this
.WriteTo (stream
: Stream) =
16 let writer = new BinaryWriter (stream
)
17 writer.Write (byte
d.Length)
18 List.iter
(fun (key
: string, value
: string) -> writer.Write key; writer.Write value) d
20 /// May raise 'KeyNotFoundException'.
21 member this
.get
(key: string) : string =
23 | (k
, v
) when k
= key -> Some (v
)
27 module internal MetadataKeys =
28 let filename = "filename"
29 let modificationTime = "file-modification-time"
31 let internal (@@) a1 a2
= Array.append a1 a2
33 let hmacSize = 256 / 8 // [byte].
34 let signatureSize = Crypto.rsaKeySize
/ 8 // [byte].
35 let keysSize = Crypto.rsaKeySize
/ 8 // [byte].
37 let generatKeysPair () : Key * Key = Crypto.generateRSAKeysPair
()
39 /// Format of the container:
40 /// <mac><signature><encrypted keys><cyphertext>
41 /// Where the sizes of the three first parts are given by 'hmacSize', 'signatureSize' and 'keysSize'.
42 let encryptFile (inputFilePath
: string) (outputFilePath
: string) (signaturePrivKey
: Key) (cryptPubKey
: Key) =
43 let keyAES, keyMAC
, iv
= Crypto.rand
16, Crypto.rand
32, Crypto.rand
16
44 let fileInfo = FileInfo (inputFilePath
)
45 use inputStream = fileInfo.OpenRead ()
46 use outputStream = new FileStream (outputFilePath
, FileMode.Create, FileAccess.Write)
47 use writer = new BinaryWriter (outputStream)
49 outputStream.Position <- (int64
<| hmacSize + signatureSize) // Skips mac and signature. They will be written later.
51 Crypto.encryptRSA cryptPubKey
(keyAES @@ keyMAC
@@ iv
) |> writer.Write
53 // Plaintext -> cryptoStream -> hmacStream -> cyphertext.
54 let hmacStream, hmac
= Crypto.HMACStream keyMAC
outputStream
55 use cryptoStream = Crypto.encryptAES
keyAES iv
hmacStream
56 use cryptoWriter = new BinaryWriter (cryptoStream)
58 // Write the file metadata.
59 let metaData = Metadata ([MetadataKeys.filename, fileInfo.Name
60 MetadataKeys.modificationTime, fileInfo.LastWriteTimeUtc.Ticks.ToString ()])
61 metaData.WriteTo cryptoStream
63 // Write the content of the file.
64 inputStream.CopyTo cryptoStream
65 cryptoStream.FlushFinalBlock ()
67 // Write the HMAC at the begining of the file.
68 outputStream.Position <- 0L
69 writer.Write hmac.Hash
71 // Write the signature.
72 Crypto.signRSA signaturePrivKey
hmac.Hash |> writer.Write
74 /// May raise one of the following error:
76 /// * SignatureMismatch
77 /// * UnableToDecryptAESKeys
78 let decryptFile (sourceFilePath
: string) (targetDirPath
: string) (signaturePubKey
: Key) (decryptPrivKey
: Key) =
79 use inputStream = new FileStream (sourceFilePath
, FileMode.Open, FileAccess.Read)
80 use reader = new BinaryReader (inputStream)
81 let mac = reader.ReadBytes hmacSize
82 let signature = reader.ReadBytes signatureSize
84 try reader.ReadBytes keysSize |> Crypto.decryptRSA decryptPrivKey
86 | :? Security.Cryptography.CryptographicException -> raise
UnableToDecryptKeys
87 let keyAES = keys.[0 .. 15]
88 let keyMAC = keys.[16 .. 47]
89 let iv = keys.[48 .. 63]
91 // Integrity validation.
92 let mac' = Crypto.ComputeHMAC keyMAC inputStream
96 // Authentication validation.
97 if not
<| Crypto.verifySignRSA signaturePubKey
mac' signature then
98 raise SignatureMismatch
101 inputStream.Position <- (int64 <| hmacSize + signatureSize + keysSize)
102 use cryptoStream = Crypto.decryptAES keyAES iv inputStream
103 let metadata = Metadata cryptoStream
105 // Create the file and write its content and metadata.
106 let filePath = Path.Combine (targetDirPath, metadata.get MetadataKeys.filename)
107 let modificationTime = DateTime (metadata.get MetadataKeys.modificationTime |> int64)
108 let fileInfo = FileInfo filePath
109 using (fileInfo.Create ()) cryptoStream.CopyTo // We have to close the result file before updating the modification time.
110 fileInfo.LastWriteTimeUtc <- modificationTime