Beispiel #1
0
        public Task RunAsync(Stream input, Stream output, byte[] password, bool forward, IProgress <double> progress = null, CancellationToken cancellationToken = default)
        {
            using SymmetricAlgorithm alg = FromEncryptionAlgorithm(Algorithm);
            Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(password, Salt.GetBytes <UTF8Encoding>(), Iterations);

            byte[] key = rdb.GetBytes(KeySize / 8);
            byte[] iv  = rdb.GetBytes(BlockSize / 8);

            alg.Mode    = CipherMode;
            alg.Padding = PaddingMode;
            alg.Key     = key;
            alg.IV      = iv;

            long             workedOn = 0;
            ICryptoTransform trans    = forward ? alg.CreateEncryptor() : alg.CreateDecryptor();

            using CryptoStream csInput = new CryptoStream(input, trans, CryptoStreamMode.Read);

            //TODO: As soon as the projects targets a higher .NET Version, get rid of this dirty hack
            try
            {
                var prop = csInput
                           .GetType()
                           .GetField("_leaveOpen", System.Reflection.BindingFlags.NonPublic
                                     | System.Reflection.BindingFlags.Instance);

                prop.SetValue(csInput, true);
            }
            catch (NullReferenceException)
            {
                //do nothing
                //Unity Mono throws a NullReferenceException on this method
            }

            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                byte[] buffer = new byte[8];
                int    read   = csInput.Read(buffer, 0, buffer.Length);

                output.Write(buffer, 0, read);

                workedOn += read;
                if (progress != null && input.CanSeek)
                {
                    progress.Report(workedOn / (double)input.Length);
                }

                if (read == 0)
                {
                    break;
                }
            }

            return(Task.CompletedTask);
        }
Beispiel #2
0
 private void Set(byte[] wrapped, Salt salt, long keyWrapIterations)
 {
     Array.Copy(wrapped, 0, GetDataBlockBytesReference(), 0, wrapped.Length);
     Array.Copy(salt.GetBytes(), 0, GetDataBlockBytesReference(), WRAP_SALT_OFFSET, salt.Length);
     byte[] keyWrapIterationsBytes = keyWrapIterations.GetLittleEndianBytes();
     Array.Copy(keyWrapIterationsBytes, 0, GetDataBlockBytesReference(), WRAP_ITERATIONS_OFFSET, WRAP_ITERATIONS_LENGTH);
 }
        public byte[] UnwrapMasterKey(SymmetricKey keyEncryptingKey, byte fileVersionMajor)
        {
            if (keyEncryptingKey == null)
            {
                throw new ArgumentNullException("keyEncryptingKey");
            }

            byte[]       wrappedKeyData         = GetKeyData();
            Salt         salt                   = Salt;
            SymmetricKey masterKeyEncryptingKey = keyEncryptingKey;

            if (fileVersionMajor <= 1)
            {
                // Due to a bug in 1.1 and earlier we only used a truncated part of the key and salt :-(
                // Compensate for this here. Users should be warned if FileVersionMajor <= 1 .
                byte[] badKey = new byte[masterKeyEncryptingKey.Size / 8];
                Array.Copy(keyEncryptingKey.GetBytes(), 0, badKey, 0, 4);
                masterKeyEncryptingKey = new SymmetricKey(badKey);

                byte[] badSalt = new byte[salt.Length];
                Array.Copy(salt.GetBytes(), 0, badSalt, 0, 4);
                salt = new Salt(badSalt);
            }

            KeyWrap keyWrap = new KeyWrap(salt, KeyWrapIterations, KeyWrapMode.AxCrypt);

            byte[] unwrappedKeyData = keyWrap.Unwrap(Resolve.CryptoFactory.Legacy.CreateCrypto(masterKeyEncryptingKey, null, 0), wrappedKeyData);
            return(unwrappedKeyData);
        }
Beispiel #4
0
        public void Run(Stream input, Stream output, byte[] password, bool forward)
        {
            using SymmetricAlgorithm alg = FromEncryptionAlgorithm(Algorithm);

            Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(password, Salt.GetBytes <UTF8Encoding>(), Iterations);

            byte[] key = rdb.GetBytes(KeySize / 8);
            byte[] iv  = rdb.GetBytes(BlockSize / 8);

            alg.Mode    = CipherMode;
            alg.Padding = PaddingMode;
            alg.Key     = key;
            alg.IV      = iv;

            ICryptoTransform trans = forward ? alg.CreateEncryptor() : alg.CreateDecryptor();

            using CryptoStream csInput = new CryptoStream(input, trans, CryptoStreamMode.Read);

            //TODO: As soon as the projects targets a higher .NET Version, get rid of this dirty hack
            var prop = csInput
                       .GetType()
                       .GetField("_leaveOpen", System.Reflection.BindingFlags.NonPublic
                                 | System.Reflection.BindingFlags.Instance);

            while (true)
            {
                byte[] buffer = new byte[8];
                int    read   = csInput.Read(buffer, 0, buffer.Length);
                if (read == 0)
                {
                    break;
                }
                output.Write(buffer, 0, read);
            }
        }
            public void WhenClearTextIsNull_ThenThrowException()
            {
                var keyIv = _keyFactoryRijndael.Create(Password, Salt.GetBytes());

                var sut = CreateSut(_rijndaelAlgo, keyIv);

                Assert.Throws <ArgumentException>(() => sut.Encrypt(null));
            }
            public void SetUp()
            {
                var algo = new RijndaelAlgorithm();
                var encryptionKeyIvFactory = new EncryptionKeyIvFactory(algo);

                var keyIv = encryptionKeyIvFactory.Create(Password, Salt.GetBytes());

                _sut = CreateSut(algo, keyIv);
            }
        public static void TestThumbprintSaltDefault()
        {
            Salt salt = new Salt(128);

            TypeMap.Register.New((int n) => salt);
            UserSettings settings = new UserSettings(new SettingsStore(New <IDataStore>(@"C:\Folder\UserSettings.txt")), new FakeIterationCalculator());

            Assert.That(settings.ThumbprintSalt.GetBytes(), Is.EqualTo(salt.GetBytes()), "The value should be this.");
        }
            public void WhenSourceAndSaltSupplied_ThenEncryptText()
            {
                var keyIv = _keyFactoryRijndael.Create(Password, Salt.GetBytes());

                var sut = CreateSut(_rijndaelAlgo, keyIv);

                var ciphertext = sut.Encrypt(ClearText);

                Assert.That(ciphertext, Is.Not.EqualTo(ClearText));
            }
        public static void TestLoadOfInvalidFormatKeyWrapSaltWithFallbackReturn()
        {
            UserSettings settings = new UserSettings(new SettingsStore(New <IDataStore>(@"C:\Folder\UserSettings.txt")), new FakeIterationCalculator());

            settings.Store <string>("MyKey", "NotASalt");

            Salt salt       = new Salt(128);
            Salt loadedSalt = settings.Load("MyKey", () => salt);

            Assert.That(loadedSalt.GetBytes(), Is.EquivalentTo(salt.GetBytes()), "Since the value is invalid, but there is a fallback this should be returned.");
        }
            public void WhenDifferentAlgorithms_ThenDifferentCiphers()
            {
                var keyIvRij  = _keyFactoryRijndael.Create(Password, Salt.GetBytes());
                var keyIvTDes = _keyFactoryTripleDes.Create(Password, Salt.GetBytes());

                var sutRij       = CreateSut(_rijndaelAlgo, keyIvRij);
                var sutTripleDes = CreateSut(_tripleDesAlgo, keyIvTDes);

                var cipherText1 = sutRij.Encrypt(ClearText);
                var cipherText2 = sutTripleDes.Encrypt(ClearText);

                Assert.That(cipherText1, Is.Not.EqualTo(cipherText2));
            }
Beispiel #11
0
        public void TestAesKeyThumbprintMethods()
        {
            Passphrase key1  = new Passphrase("key");
            Passphrase key2  = new Passphrase("key");
            Salt       salt1 = new Salt(512);
            Salt       salt2 = new Salt(salt1.GetBytes());

            SymmetricKeyThumbprint thumbprint1 = new SymmetricKeyThumbprint(key1, salt1, 10);
            SymmetricKeyThumbprint thumbprint2 = new SymmetricKeyThumbprint(key2, salt2, 10);

            Assert.That(thumbprint1 == thumbprint2, "Two thumb prints made from the same key and salt bytes, although different AesKey instances should be equivalent.");

            SymmetricKeyThumbprint thumbprint3 = new SymmetricKeyThumbprint(new Passphrase("passphrase"), new Salt(512), 10);

            Assert.That(thumbprint2 != thumbprint3, "Two very different keys and salts should not be equivalent.");
        }
Beispiel #12
0
        public static void TestMethodsEtc()
        {
            Salt salt = null;

            Assert.DoesNotThrow(() =>
            {
                salt = new Salt(0);
                Assert.That(salt.Length, Is.EqualTo(0), "As a special case, zero length salt is supported - equivalent to no salt.");

                salt = new Salt(128);
                Assert.That(salt.Length, Is.EqualTo(16), "The length should be what was asked for.");
                Assert.That(salt.GetBytes(), Is.Not.EquivalentTo(new byte[16]), "A random salt is not likely to be all zeros.");

                salt = new Salt(192);
                Assert.That(salt.Length, Is.EqualTo(24), "The length should be what was asked for.");
                Assert.That(salt.GetBytes(), Is.Not.EquivalentTo(new byte[24]), "A random salt is not likely to be all zeros.");

                salt = new Salt(256);
                Assert.That(salt.Length, Is.EqualTo(32), "The length should be what was asked for.");
                Assert.That(salt.GetBytes(), Is.Not.EquivalentTo(new byte[32]), "A random salt is not likely to be all zeros.");

                salt = new Salt(new byte[16]);
                Assert.That(salt.GetBytes(), Is.EquivalentTo(new byte[16]), "A salt with all zeros was requested.");

                salt = new Salt(new byte[24]);
                Assert.That(salt.GetBytes(), Is.EquivalentTo(new byte[24]), "A salt with all zeros was requested.");

                salt = new Salt(new byte[32]);
                Assert.That(salt.GetBytes(), Is.EquivalentTo(new byte[32]), "A salt with all zeros was requested.");

                salt = new Salt(new byte[0]);
                Assert.That(salt.Length, Is.EqualTo(0), "As a special case, zero length salt is supported - equivalent to no salt.");
            }
                                );

            Assert.Throws <ArgumentNullException>(() =>
            {
                salt = new Salt(null);
            });

            Assert.Throws <ArgumentOutOfRangeException>(() =>
            {
                salt = new Salt(-128);
            });
        }
        public static void TestNamedStronglyTypedProperties()
        {
            UserSettings settings = new UserSettings(new SettingsStore(New <IDataStore>(@"C:\Folder\UserSettings.txt")), new IterationCalculator());

            settings.CultureName = "sv-SE";
            Assert.That(settings.CultureName, Is.EqualTo("sv-SE"), "The value should be this.");

            settings.UpdateUrl = new Uri("http://localhost/update");
            Assert.That(settings.UpdateUrl, Is.EqualTo(new Uri("http://localhost/update")), "The value should be this.");

            settings.LastUpdateCheckUtc = new DateTime(2001, 02, 03);
            Assert.That(settings.LastUpdateCheckUtc, Is.EqualTo(new DateTime(2001, 02, 03)), "The value should be this.");

            settings.NewestKnownVersion = "1.2.3.4";
            Assert.That(settings.NewestKnownVersion, Is.EqualTo("1.2.3.4"), "The value should be this.");

            settings.DebugMode = true;
            Assert.That(settings.DebugMode, Is.True, "The value should be this.");

            settings.AxCrypt2HelpUrl = new Uri("http://localhost/help");
            Assert.That(settings.AxCrypt2HelpUrl, Is.EqualTo(new Uri("http://localhost/help")), "The value should be this.");

            settings.DisplayEncryptPassphrase = true;
            Assert.That(settings.DisplayEncryptPassphrase, Is.True, "The value should be this.");

            settings.DisplayDecryptPassphrase = true;
            Assert.That(settings.DisplayDecryptPassphrase, Is.True, "The value should be this.");

            settings.SetKeyWrapIterations(new V1Aes128CryptoFactory().CryptoId, 1234);
            Assert.That(settings.GetKeyWrapIterations(new V1Aes128CryptoFactory().CryptoId), Is.EqualTo(1234), "The value should be this.");

            Salt salt = new Salt(128);

            settings.ThumbprintSalt = salt;
            Assert.That(settings.ThumbprintSalt.GetBytes(), Is.EqualTo(salt.GetBytes()), "The value should be this.");

            settings.SetKeyWrapIterations(new V2Aes256CryptoFactory().CryptoId, 999);
            Assert.That(settings.GetKeyWrapIterations(new V2Aes256CryptoFactory().CryptoId), Is.EqualTo(999));
        }
 protected void Set(byte[] wrapped, Salt salt, long keyWrapIterations)
 {
     if (wrapped == null)
     {
         throw new ArgumentNullException("wrapped");
     }
     if (wrapped.Length != 16 + 8)
     {
         throw new ArgumentException("wrapped must be 128 bits + 8 bytes.");
     }
     if (salt == null)
     {
         throw new ArgumentNullException("salt");
     }
     if (salt.Length != 16)
     {
         throw new ArgumentException("salt must have same length as the wrapped key, i.e. 128 bits.");
     }
     Array.Copy(wrapped, 0, GetDataBlockBytesReference(), 0, wrapped.Length);
     Array.Copy(salt.GetBytes(), 0, GetDataBlockBytesReference(), 16 + 8, salt.Length);
     byte[] iterationsBytes = keyWrapIterations.GetLittleEndianBytes();
     Array.Copy(iterationsBytes, 0, GetDataBlockBytesReference(), 16 + 8 + 16, sizeof(uint));
 }