let internal (@@) a1 a2 = Array.append a1 a2
- let generatKeysPair : Key * Key = Crypto.generateRSAKeysPair
+ let test = 256 / 8
+ let hmacSize = 256 / 8 // [byte].
+ let signatureSize = Crypto.rsaKeySize / 8 // [byte].
+ let keysSize = Crypto.rsaKeySize / 8 // [byte].
+ let generatKeysPair () : Key * Key = Crypto.generateRSAKeysPair ()
+
+ // Format of the container:
+ // <mac><signature><encrypted keys><cyphertext>
+ // Where the sizes of the three first parts are given by 'hmacSize', 'signatureSize' and 'keysSize'.
let encryptFile (inputFilePath : string) (outputFilePath : string) (signaturePrivKey: Key) (cryptPubKey : Key) =
let keyAES, keyMAC, iv = Crypto.rand 16, Crypto.rand 32, Crypto.rand 16
let fileInfo = FileInfo (inputFilePath)
use outputStream = new FileStream (outputFilePath, FileMode.Create, FileAccess.Write)
use writer = new BinaryWriter (outputStream)
- outputStream.Position <- 32L + 256L // Skips mac and signature. They will be written later.
+ outputStream.Position <- (int64 <| hmacSize + signatureSize) // Skips mac and signature. They will be written later.
Crypto.encryptRSA cryptPubKey (keyAES @@ keyMAC @@ iv) |> writer.Write
let decryptFile (sourceFilePath : string) (targetDirPath : string) (signaturePubKey: Key) (decryptPrivKey : Key) =
use inputStream = new FileStream (sourceFilePath, FileMode.Open, FileAccess.Read)
use reader = new BinaryReader (inputStream)
- let mac = reader.ReadBytes 32
- let signature = reader.ReadBytes 256
+ let mac = reader.ReadBytes hmacSize
+ let signature = reader.ReadBytes signatureSize
let keys =
- try reader.ReadBytes 256 |> Crypto.decryptRSA decryptPrivKey
+ try reader.ReadBytes keysSize |> Crypto.decryptRSA decryptPrivKey
with
- | :? Security.Cryptography.CryptographicException -> raise UnableToDecryptAESKeys
+ | :? Security.Cryptography.CryptographicException -> raise UnableToDecryptKeys
let keyAES = keys.[0..15]
let keyMAC = keys.[16..47]
let iv = keys.[48..63]
raise SignatureMismatch
// Decrypt metadata.
- inputStream.Position <- 32L + 256L + 256L
+ inputStream.Position <- (int64 <| hmacSize + signatureSize + keysSize)
use cryptoStream = Crypto.decryptAES keyAES iv inputStream
let metadata = Metadata cryptoStream
let filePath = Path.Combine (targetDirPath, metadata.get MetadataKeys.filename)
let modificationTime = DateTime (metadata.get MetadataKeys.modificationTime |> int64)
let fileInfo = FileInfo filePath
- using (fileInfo.Create ()) <| fun outputStream -> cryptoStream.CopyTo outputStream
+ using (fileInfo.Create ()) cryptoStream.CopyTo // We have to close the result file before updating the modification time.
fileInfo.LastWriteTimeUtc <- modificationTime
\ No newline at end of file