Typos in report + clean up.
[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 test = 256 / 8
34 let hmacSize = 256 / 8 // [byte].
35 let signatureSize = Crypto.rsaKeySize / 8 // [byte].
36 let keysSize = Crypto.rsaKeySize / 8 // [byte].
37
38 let generatKeysPair () : Key * Key = Crypto.generateRSAKeysPair ()
39
40 /// Format of the container:
41 /// <mac><signature><encrypted keys><cyphertext>
42 /// Where the sizes of the three first parts are given by 'hmacSize', 'signatureSize' and 'keysSize'.
43 let encryptFile (inputFilePath : string) (outputFilePath : string) (signaturePrivKey: Key) (cryptPubKey : Key) =
44 let keyAES, keyMAC, iv = Crypto.rand 16, Crypto.rand 32, Crypto.rand 16
45 let fileInfo = FileInfo (inputFilePath)
46 use inputStream = fileInfo.OpenRead ()
47 use outputStream = new FileStream (outputFilePath, FileMode.Create, FileAccess.Write)
48 use writer = new BinaryWriter (outputStream)
49
50 outputStream.Position <- (int64 <| hmacSize + signatureSize) // Skips mac and signature. They will be written later.
51
52 Crypto.encryptRSA cryptPubKey (keyAES @@ keyMAC @@ iv) |> writer.Write
53
54 // Plaintext -> cryptoStream -> hmacStream -> cyphertext.
55 let hmacStream, hmac = Crypto.HMACStream keyMAC outputStream
56 use cryptoStream = Crypto.encryptAES keyAES iv hmacStream
57 use cryptoWriter = new BinaryWriter (cryptoStream)
58
59 // Write the file metadata.
60 let metaData = Metadata ([MetadataKeys.filename, fileInfo.Name
61 MetadataKeys.modificationTime, fileInfo.LastWriteTimeUtc.Ticks.ToString ()])
62 metaData.WriteTo cryptoStream
63
64 // Write the content of the file.
65 inputStream.CopyTo cryptoStream
66 cryptoStream.FlushFinalBlock ()
67
68 // Write the HMAC at the begining of the file.
69 outputStream.Position <- 0L
70 writer.Write hmac.Hash
71
72 // Write the signature.
73 Crypto.signRSA signaturePrivKey hmac.Hash |> writer.Write
74
75 /// May raise one of the following error:
76 /// * IntegrityError
77 /// * SignatureMismatch
78 /// * UnableToDecryptAESKeys
79 let decryptFile (sourceFilePath : string) (targetDirPath : string) (signaturePubKey: Key) (decryptPrivKey : Key) =
80 use inputStream = new FileStream (sourceFilePath, FileMode.Open, FileAccess.Read)
81 use reader = new BinaryReader (inputStream)
82 let mac = reader.ReadBytes hmacSize
83 let signature = reader.ReadBytes signatureSize
84 let keys =
85 try reader.ReadBytes keysSize |> Crypto.decryptRSA decryptPrivKey
86 with
87 | :? Security.Cryptography.CryptographicException -> raise UnableToDecryptKeys
88 let keyAES = keys.[0 .. 15]
89 let keyMAC = keys.[16 .. 47]
90 let iv = keys.[48 .. 63]
91
92 // Integrity validation.
93 let mac' = Crypto.ComputeHMAC keyMAC inputStream
94 if mac' <> mac then
95 raise IntegrityError
96
97 // Authentication validation.
98 if not <| Crypto.verifySignRSA signaturePubKey mac' signature then
99 raise SignatureMismatch
100
101 // Decrypt metadata.
102 inputStream.Position <- (int64 <| hmacSize + signatureSize + keysSize)
103 use cryptoStream = Crypto.decryptAES keyAES iv inputStream
104 let metadata = Metadata cryptoStream
105
106 // Create the file and write its content and metadata.
107 let filePath = Path.Combine (targetDirPath, metadata.get MetadataKeys.filename)
108 let modificationTime = DateTime (metadata.get MetadataKeys.modificationTime |> int64)
109 let fileInfo = FileInfo filePath
110 using (fileInfo.Create ()) cryptoStream.CopyTo // We have to close the result file before updating the modification time.
111 fileInfo.LastWriteTimeUtc <- modificationTime
112