Add some tests.
[crypto_lab2.git] / labo2-fsharp / CryptoFileTests / Tests.fs
1 module CryptoFileTests.Tests
2
3 open System.IO
4 open CryptoFile
5
6 let doSomeTests () =
7 printfn "===== Unit tests"
8 CryptoFile.UnitTests.runAllUnitTests ()
9 printfn "===== Unit tests OK"
10
11 printfn "===== API tests"
12 let plainFilename = "test.txt"
13 let cipherFilename = "test.cipher"
14 let fileContent = "Screw the NSA"
15
16 File.WriteAllText (plainFilename, fileContent)
17
18 let keyCryptPub, keyCryptPriv = API.generatKeysPair
19 let keySigPub, keySigPriv = API.generatKeysPair
20
21 let encrypt () =
22 API.encryptFile plainFilename cipherFilename keySigPriv keyCryptPub
23
24 let decrypt () =
25 API.decryptFile cipherFilename "." keySigPub keyCryptPriv
26
27 let writeByteToCipherFileAt byte position =
28 using (new FileStream (cipherFilename, FileMode.Open, FileAccess.Write))
29 (fun fs -> fs.Position <- position
30 fs.Write ([| byte |], 0, 1))
31
32 encrypt ()
33 File.Delete plainFilename
34 decrypt ()
35 assert (File.ReadAllText plainFilename = fileContent)
36
37 printfn "== Altering the MAC..."
38 writeByteToCipherFileAt 0uy 0L
39 try
40 decrypt ()
41 assert false
42 with
43 | error -> assert (error :? IntegrityError)
44
45 printfn "== Altering the signature..."
46 encrypt ()
47 writeByteToCipherFileAt 0uy 32L
48 try
49 decrypt ()
50 assert false
51 with
52 | error -> assert (error :? SignatureMismatch)
53
54 printfn "== Altering the keys..."
55 encrypt ()
56 writeByteToCipherFileAt 0uy (32L + 256L)
57 try
58 decrypt ()
59 assert false
60 with
61 | error -> assert (error :? UnableToDecryptAESKeys)
62
63 printfn "== Altering the cyphering..."
64 encrypt ()
65 writeByteToCipherFileAt 0uy (32L + 256L + 256L)
66 try
67 decrypt ()
68 assert false
69 with
70 | error -> assert (error :? IntegrityError)
71
72 File.Delete cipherFilename
73 File.Delete plainFilename
74
75 printfn "===== API tests OK"