Beispiel #1
0
        public static ContainerV1 FromBytes(byte[] bytes)
        {
            var magicBytes = bytes.Skip(0).Take(MagicBytesLength).ToArray();
            if (!Config.MagicBytes.SequenceEqual(magicBytes))
                throw new Exception("MagicNumber is wrong.");

            var version = BitConverter.ToInt32(bytes.Skip(MagicBytesLength).Take(VersionLength).ToArray(), 0);
            if (version != ContainerVersion)
                throw new Exception("ContainerVersion is wrong.");

            var hmac = bytes.Skip(MagicBytesLength + VersionLength).Take(HmacLength).ToArray();
            var iv = bytes.Skip(MagicBytesLength + VersionLength + HmacLength).Take(IVLength).ToArray();
            var data = bytes.Skip(MagicBytesLength + VersionLength + HmacLength + IVLength).ToArray();
            var result = new ContainerV1(iv, data, hmac);

            return result;
        }
Beispiel #2
0
        public static string Encrypt(string path, string password, bool replaceFilename = false,
            Action<double, string> statusCallback = null)
        {
            if (!File.Exists(path))
                throw new FileNotFoundException();

            SetStatusEncryption(statusCallback, Status.ReadFile);
            var bytes = File.ReadAllBytes(path);

            var iv = CryptoProvider.CreateIV();

            var plainContent = new PlainContent
            {
                Data = bytes,
                Filename = Path.GetFileName(path)
            };

            SetStatusEncryption(statusCallback, Status.EncryptData);
            var encryptedBytes = CryptoProvider.EncryptData(plainContent.GetBytes(), iv, password);

            SetStatusEncryption(statusCallback, Status.CreateHmac);
            var hmac = CryptoProvider.CreateHmac(iv, encryptedBytes, password);

            var newPath = CreateEnryptedFilename(path, replaceFilename);

            var container = new ContainerV1(iv, encryptedBytes, hmac);

            SetStatusEncryption(statusCallback, Status.WriteAllBytes);
            File.WriteAllBytes(newPath, container.GetBytes());

            SetStatusEncryption(statusCallback, Status.Done);
            return newPath;
        }