Пример #1
0
        private static byte[] EncryptKey(byte[] stretchedKey, byte[] buffer, int offset)
        {
            using var twofish = new TwofishManaged();
            twofish.Mode      = CipherMode.ECB;
            twofish.Padding   = PaddingMode.None;
            twofish.KeySize   = 256;
            twofish.Key       = stretchedKey;

            using var transform = twofish.CreateEncryptor();
            return(transform.TransformFinalBlock(buffer, offset, 32));
        }
Пример #2
0
        public void Twofish_MultiBlockFinal_ECB_256_Encrypt()
        {
            var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000");
            var pt  = ParseBytes("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");

            using (var algorithm = new TwofishManaged()
            {
                KeySize = 256, Mode = CipherMode.ECB, Padding = PaddingMode.None
            }) {
                algorithm.Key = key;
                var ct = algorithm.CreateEncryptor().TransformFinalBlock(pt, 0, pt.Length);
                Assert.AreEqual("57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F", BitConverter.ToString(ct).Replace("-", ""));
            }
        }
Пример #3
0
        public void Twofish_TransformBlock_Encrypt_UseSameArray()
        {
            var key  = ParseBytes("00000000000000000000000000000000");
            var iv   = ParseBytes("00000000000000000000000000000000");
            var ctpt = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog once");

            using (var twofish = new TwofishManaged()
            {
                Mode = CipherMode.CBC, Padding = PaddingMode.None, KeySize = 128, Key = key, IV = iv
            }) {
                using (var transform = twofish.CreateEncryptor()) {
                    transform.TransformBlock(ctpt, 0, 48, ctpt, 0);
                }
            }
            Assert.AreEqual("B0DD30E9AB1F1329C1BEE154DDBE88AF8C47A4FE24D56DC027ED503652C9D164CE26E0C6E32BCA8756482B99988E8C79", BitConverter.ToString(ctpt).Replace("-", ""));
        }
Пример #4
0
        public void Twofish_MultiBlockFinal_CBC_256_Encrypt()
        {
            var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000");
            var iv  = ParseBytes("00000000000000000000000000000000");
            var pt  = ParseBytes("9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A");

            using (var algorithm = new TwofishManaged()
            {
                KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.None
            }) {
                algorithm.Key = key;
                algorithm.IV  = iv;
                var ct = algorithm.CreateEncryptor().TransformFinalBlock(pt, 0, pt.Length);
                Assert.AreEqual("61B5BC459C4E9491DD9E6ACB7478813047BE7250D34F792C17F0C23583C0B040B95C9FAE11107EE9BAC3D79BBFE019EE", BitConverter.ToString(ct).Replace("-", ""));
            }
        }
Пример #5
0
        public static void Main(string[] args)
        {
            Console.Title = "Twofish.Tests";

            var bIn = Encoding.UTF8.GetBytes("It works!");

            byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; // 128bit key
            byte[] iv  = { 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; // initialization vector

            using (var algorithm = new TwofishManaged {
                KeySize = key.Length * 8, Mode = CipherMode.CBC
            })
            {
                byte[] encrypted;

                using (var ms = new MemoryStream())
                {
                    using (var transform = algorithm.CreateEncryptor(key, iv))
                    {
                        using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
                        {
                            cs.Write(bIn, 0, bIn.Length);
                        }
                    }

                    encrypted = ms.ToArray();

                    Console.WriteLine($"Encrypted: {BitConverter.ToString(encrypted).Replace("-", string.Empty)}");
                }

                using (var ms = new MemoryStream())
                {
                    using (var transform = algorithm.CreateDecryptor(key, iv))
                    {
                        using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
                        {
                            cs.Write(encrypted, 0, encrypted.Length);
                        }
                    }

                    Console.WriteLine($"Decrypted: {Encoding.UTF8.GetString(ms.ToArray())}");
                }
            }

            Console.Read();
        }
Пример #6
0
        public static bool TestTwofish()
        {
            TwofishManaged twofish = new TwofishManaged();

            twofish.Padding = PaddingMode.None;
            twofish.Mode    = CipherMode.ECB;
            byte[] key        = new byte[] { 0xD4, 0x3B, 0xB7, 0x55, 0x6E, 0xA3, 0x2E, 0x46, 0xF2, 0xA2, 0x82, 0xB7, 0xD4, 0x5B, 0x4E, 0x0D, 0x57, 0xFF, 0x73, 0x9D, 0x4D, 0xC9, 0x2C, 0x1B, 0xD7, 0xFC, 0x01, 0x70, 0x0C, 0xC8, 0x21, 0x6F };
            byte[] plaintext  = new byte[] { 0x90, 0xAF, 0xE9, 0x1B, 0xB2, 0x88, 0x54, 0x4F, 0x2C, 0x32, 0xDC, 0x23, 0x9B, 0x26, 0x35, 0xE6 };
            byte[] ciphertext = new byte[] { 0x6C, 0xB4, 0x56, 0x1C, 0x40, 0xBF, 0x0A, 0x97, 0x05, 0x93, 0x1C, 0xB6, 0xD4, 0x08, 0xE7, 0xFA };

            byte[]           initializationVector = new byte[16];
            ICryptoTransform encryptor            = twofish.CreateEncryptor(key, initializationVector);
            ICryptoTransform decryptor            = twofish.CreateDecryptor(key, initializationVector);

            byte[] result1 = new byte[16];
            byte[] result2 = new byte[16];
            encryptor.TransformBlock(plaintext, 0, 16, result1, 0);
            decryptor.TransformBlock(ciphertext, 0, 16, result2, 0);
            return(ByteUtils.AreByteArraysEqual(result1, ciphertext) && ByteUtils.AreByteArraysEqual(result2, plaintext));
        }
Пример #7
0
        public void Save(Stream stream, byte[] passphraseBuffer)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream), "Stream cannot be null.");
            }
            if (passphraseBuffer == null)
            {
                throw new ArgumentNullException(nameof(passphraseBuffer), "Passphrase cannot be null.");
            }

            if (!this.IsReadOnly && this.TrackModify)
            {
                this.Headers[HeaderType.TimestampOfLastSave].Time = DateTime.UtcNow;

                var assemblyName = Assembly.GetExecutingAssembly().GetName();
                this.Headers[HeaderType.WhatPerformedLastSave].Text = string.Format(CultureInfo.InvariantCulture, "{0} V{1}.{2:00}", assemblyName.Name, assemblyName.Version.Major, assemblyName.Version.Minor);

                this.Headers[HeaderType.LastSavedByUser].Text = Environment.UserName;
                this.Headers[HeaderType.LastSavedOnHost].Text = Environment.MachineName;
            }

            byte[] stretchedKey = null;
            byte[] keyK         = null;
            byte[] keyL         = null;
            //byte[] data = null;
            try {
                stream.Write(BitConverter.GetBytes(Tag), 0, 4);

                var salt = new byte[32];
                Rnd.GetBytes(salt);
                stream.Write(salt, 0, salt.Length);

                this.Iterations = this.Iterations; //to force minimum iteration count
                var iter = (uint)this.Iterations;
                stream.Write(BitConverter.GetBytes(iter), 0, 4);

                stretchedKey = GetStretchedKey(passphraseBuffer, salt, iter);
                stream.Write(GetSha256Hash(stretchedKey), 0, 32);

                keyK = new byte[32];
                Rnd.GetBytes(keyK);
                stream.Write(EncryptKey(stretchedKey, keyK, 0), 0, 32);

                keyL = new byte[32];
                Rnd.GetBytes(keyL);
                stream.Write(EncryptKey(stretchedKey, keyL, 0), 0, 32);

                var iv = new byte[16];
                Rnd.GetBytes(iv);
                stream.Write(iv, 0, iv.Length);

                using (var dataHash = new HMACSHA256(keyL))
                    using (var twofish = new TwofishManaged()) {
                        twofish.Mode    = CipherMode.CBC;
                        twofish.Padding = PaddingMode.None;
                        twofish.KeySize = 256;
                        twofish.Key     = keyK;
                        twofish.IV      = iv;
                        using (var dataEncryptor = twofish.CreateEncryptor()) {
                            foreach (var field in this.Headers)
                            {
                                WriteBlock(stream, dataHash, dataEncryptor, (byte)field.HeaderType, field.RawData);
                            }
                            WriteBlock(stream, dataHash, dataEncryptor, (byte)HeaderType.EndOfEntry, new byte[] { });

                            foreach (var entry in this.Entries)
                            {
                                foreach (var field in entry.Records)
                                {
                                    WriteBlock(stream, dataHash, dataEncryptor, (byte)field.RecordType, field.RawData);
                                }
                                WriteBlock(stream, dataHash, dataEncryptor, (byte)RecordType.EndOfEntry, new byte[] { });
                            }
                        }

                        dataHash.TransformFinalBlock(new byte[] { }, 0, 0);

                        stream.Write(BitConverter.GetBytes(Tag), 0, 4);
                        stream.Write(BitConverter.GetBytes(TagEof), 0, 4);
                        stream.Write(BitConverter.GetBytes(Tag), 0, 4);
                        stream.Write(BitConverter.GetBytes(TagEof), 0, 4);

                        stream.Write(dataHash.Hash, 0, dataHash.Hash.Length);
                        this.HasChanged = false;
                    }
            } finally {
                if (stretchedKey != null)
                {
                    Array.Clear(stretchedKey, 0, stretchedKey.Length);
                }
                if (keyK != null)
                {
                    Array.Clear(keyK, 0, keyK.Length);
                }
                if (keyL != null)
                {
                    Array.Clear(keyL, 0, keyL.Length);
                }
                //if (data != null) { Array.Clear(data, 0, data.Length); }
            }
        }
Пример #8
0
        /// <summary>
        /// Save document.
        /// If key buffer is given, keys won't be randomized. This will reduce security!
        /// If passphrase is null, attempt will be made to use passphrase that was used for load.
        /// </summary>
        /// <param name="stream">Stream.</param>
        /// <param name="passphraseBuffer">Password bytes. Caller has to avoid keeping bytes unencrypted in memory.</param>
        /// <param name="keyBuffer">Key bytes containing both key K and L. Must be 64 bytes. Caller has to avoid keeping bytes unencrypted in memory.</param>
        internal void InternalSave(Stream stream, byte[]?passphraseBuffer, byte[]?keyBuffer)
        {
            if (passphraseBuffer == null)
            {
                passphraseBuffer = GetPassphrase();
            }                                                                     //first try old passphrase
            if (passphraseBuffer == null)
            {
                throw new ArgumentNullException(nameof(passphraseBuffer), "Passphrase cannot be null.");
            }
            if ((keyBuffer != null) && (keyBuffer.Length != 64))
            {
                throw new ArgumentOutOfRangeException(nameof(keyBuffer), "Keys must be 64 bytes long.");
            }

            if (!IsReadOnly && TrackModify)
            {
                Headers[HeaderType.TimestampOfLastSave].Time = DateTime.UtcNow;

                var assemblyName = Assembly.GetExecutingAssembly().GetName();
                Headers[HeaderType.WhatPerformedLastSave].Text = string.Format(CultureInfo.InvariantCulture, "{0} V{1}.{2:00}", assemblyName.Name, assemblyName.Version?.Major ?? 0, assemblyName.Version?.Minor ?? 0);

                Headers[HeaderType.LastSavedByUser].Text = Environment.UserName;
                Headers[HeaderType.LastSavedOnHost].Text = Environment.MachineName;
            }

            byte[]? stretchedKey = null;
            byte[]? keyK         = null;
            byte[]? keyL         = null;
            try {
                stream.Write(BitConverter.GetBytes(Tag), 0, 4);

                var salt = new byte[32];
                Rnd.GetBytes(salt);
                stream.Write(salt, 0, salt.Length);

                if (Iterations < 2048)
                {
                    Iterations = 2048;
                }                                              // to force minimum iteration count
                var iter = (uint)Iterations;
                stream.Write(BitConverter.GetBytes(iter), 0, 4);

                stretchedKey = GetStretchedKey(passphraseBuffer, salt, iter);
                stream.Write(GetSha256Hash(stretchedKey), 0, 32);

                keyK = new byte[32];
                keyL = new byte[32];
                if (keyBuffer == null)
                {
                    Rnd.GetBytes(keyK);
                    Rnd.GetBytes(keyL);
                }
                else
                {
                    Buffer.BlockCopy(keyBuffer, 0, keyK, 0, keyK.Length);
                    Buffer.BlockCopy(keyBuffer, 32, keyL, 0, keyL.Length);
                }

                stream.Write(EncryptKey(stretchedKey, keyK, 0), 0, 32);
                stream.Write(EncryptKey(stretchedKey, keyL, 0), 0, 32);

                var iv = new byte[16];
                Rnd.GetBytes(iv);
                stream.Write(iv, 0, iv.Length);

                using var dataHash = new HMACSHA256(keyL);
                using var twofish  = new TwofishManaged();
                twofish.Mode       = CipherMode.CBC;
                twofish.Padding    = PaddingMode.None;
                twofish.KeySize    = 256;
                twofish.Key        = keyK;
                twofish.IV         = iv;
                using (var dataEncryptor = twofish.CreateEncryptor()) {
                    foreach (var field in Headers)
                    {
                        WriteBlock(stream, dataHash, dataEncryptor, (byte)field.HeaderType, field.RawData);
                    }
                    WriteBlock(stream, dataHash, dataEncryptor, (byte)HeaderType.EndOfEntry, Array.Empty <byte>());

                    foreach (var entry in Entries)
                    {
                        foreach (var field in entry.Records)
                        {
                            WriteBlock(stream, dataHash, dataEncryptor, (byte)field.RecordType, field.RawData);
                        }
                        WriteBlock(stream, dataHash, dataEncryptor, (byte)RecordType.EndOfEntry, Array.Empty <byte>());
                    }
                }

                dataHash.TransformFinalBlock(Array.Empty <byte>(), 0, 0);

                stream.Write(BitConverter.GetBytes(Tag), 0, 4);
                stream.Write(BitConverter.GetBytes(TagEof), 0, 4);
                stream.Write(BitConverter.GetBytes(Tag), 0, 4);
                stream.Write(BitConverter.GetBytes(TagEof), 0, 4);

                if (dataHash.Hash == null)
                {
                    throw new InvalidOperationException("Cannot compute hash.");
                }                                                                                            // newer happens actually
                stream.Write(dataHash.Hash, 0, dataHash.Hash.Length);
                HasChanged = false;
            } finally {
                if (stretchedKey != null)
                {
                    Array.Clear(stretchedKey, 0, stretchedKey.Length);
                }
                if (keyK != null)
                {
                    Array.Clear(keyK, 0, keyK.Length);
                }
                if (keyL != null)
                {
                    Array.Clear(keyL, 0, keyL.Length);
                }
                //if (data != null) { Array.Clear(data, 0, data.Length); }
            }
        }