Remove a usless binding.
[crypto_lab2.git] / labo2-fsharp / CryptoFile / API.fs
1 namespace CryptoFile
2
3 open System
4 open System.IO
5
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 ()])
13
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
19
20 /// May raise 'KeyNotFoundException'.
21 member this.get (key: string) : string =
22 List.pick (function
23 | (k, v) when k = key -> Some (v)
24 | _ -> None) d
25
26 module API =
27 module internal MetadataKeys =
28 let filename = "filename"
29 let modificationTime = "file-modification-time"
30
31 let internal (@@) a1 a2 = Array.append a1 a2
32
33 let hmacSize = 256 / 8 // [byte].
34 let signatureSize = Crypto.rsaKeySize / 8 // [byte].
35 let keysSize = Crypto.rsaKeySize / 8 // [byte].
36
37 let generatKeysPair () : Key * Key = Crypto.generateRSAKeysPair ()
38
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)
48
49 outputStream.Position <- (int64 <| hmacSize + signatureSize) // Skips mac and signature. They will be written later.
50
51 Crypto.encryptRSA cryptPubKey (keyAES @@ keyMAC @@ iv) |> writer.Write
52
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)
57
58 // Write the file metadata.
59 let metaData = Metadata ([MetadataKeys.filename, fileInfo.Name
60 MetadataKeys.modificationTime, fileInfo.LastWriteTimeUtc.Ticks.ToString ()])
61 metaData.WriteTo cryptoStream
62
63 // Write the content of the file.
64 inputStream.CopyTo cryptoStream
65 cryptoStream.FlushFinalBlock ()
66
67 // Write the HMAC at the begining of the file.
68 outputStream.Position <- 0L
69 writer.Write hmac.Hash
70
71 // Write the signature.
72 Crypto.signRSA signaturePrivKey hmac.Hash |> writer.Write
73
74 /// May raise one of the following error:
75 /// * IntegrityError
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
83 let keys =
84 try reader.ReadBytes keysSize |> Crypto.decryptRSA decryptPrivKey
85 with
86 | :? Security.Cryptography.CryptographicException -> raise UnableToDecryptKeys
87 let keyAES = keys.[0 .. 15]
88 let keyMAC = keys.[16 .. 47]
89 let iv = keys.[48 .. 63]
90
91 // Integrity validation.
92 let mac' = Crypto.ComputeHMAC keyMAC inputStream
93 if mac' <> mac then
94 raise IntegrityError
95
96 // Authentication validation.
97 if not <| Crypto.verifySignRSA signaturePubKey mac' signature then
98 raise SignatureMismatch
99
100 // Decrypt metadata.
101 inputStream.Position <- (int64 <| hmacSize + signatureSize + keysSize)
102 use cryptoStream = Crypto.decryptAES keyAES iv inputStream
103 let metadata = Metadata cryptoStream
104
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
111