Typos in report + clean up.
[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 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 incrementByteCipherFileAt position =
28 use fs = new FileStream (cipherFilename, FileMode.Open, FileAccess.ReadWrite)
29 fs.Position <- position
30 let byte = fs.ReadByte () |> byte
31 fs.Position <- position
32 fs.Write ([| byte + 1uy |], 0, 1) // Modulo 256.
33
34 encrypt ()
35 File.Delete plainFilename
36 decrypt ()
37 assert (File.ReadAllText plainFilename = fileContent)
38
39 printfn "== Altering the MAC... (%d bytes)" (API.hmacSize - 1)
40 for i in 0 .. API.hmacSize - 1 do
41 printf "."
42 encrypt ()
43 incrementByteCipherFileAt (int64 i)
44 try
45 decrypt ()
46 assert false
47 with
48 | error -> assert (error :? IntegrityError)
49 printfn ""
50
51 printfn "== Altering the signature... (%d bytes)" (API.signatureSize - 1)
52 for i in 0 .. API.signatureSize - 1 do
53 printf "."
54 encrypt ()
55 incrementByteCipherFileAt (int64 <| API.hmacSize + i)
56 try
57 decrypt ()
58 assert false
59 with
60 | error -> assert (error :? SignatureMismatch)
61 printfn ""
62
63 printfn "== Altering the keys... (%d bytes)" (API.keysSize - 1)
64 for i in 0 .. API.keysSize - 1 do
65 printf "."
66 encrypt ()
67 incrementByteCipherFileAt (int64 <| API.hmacSize + API.signatureSize + i)
68 try
69 decrypt ()
70 assert false
71 with
72 | error -> assert (error :? UnableToDecryptKeys)
73 printfn ""
74
75 let cyphertextLength = (int (FileInfo (cipherFilename)).Length) + API.hmacSize + API.signatureSize + API.keysSize
76 printfn "== Altering the cyphertext... (%d bytes)" cyphertextLength
77 for i in 0 .. cyphertextLength do
78 printf "."
79 encrypt ()
80 incrementByteCipherFileAt (int64 <| API.hmacSize + API.signatureSize + API.keysSize + i)
81 try
82 decrypt ()
83 assert false
84 with
85 | error -> assert (error :? IntegrityError)
86 printfn ""
87
88 File.Delete cipherFilename
89 File.Delete plainFilename
90
91 printfn "===== API tests OK"