示例#1
0
        public static void TestSubkeyMethods()
        {
            AesKey key = new AesKey(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });
            Subkey subkey = null;
            Assert.Throws<ArgumentNullException>(() =>
            {
                subkey = new Subkey(null, HeaderSubkey.Data);
            });

            Assert.Throws<InternalErrorException>(() =>
            {
                subkey = new Subkey(key, HeaderSubkey.None);
            });

            subkey = new Subkey(key, HeaderSubkey.Data);
            Assert.That(subkey.Key.Length, Is.EqualTo(16), "A Subkey is exactly 16 bytes.");
            Assert.That(subkey.Key.GetBytes(), Is.EquivalentTo(new byte[] { 0x5f, 0xfe, 0x14, 0x56, 0xd5, 0x94, 0xf9, 0x22, 0x42, 0xe3, 0x66, 0x8f, 0x8c, 0xe6, 0xea, 0xc6 }), "Comparing with a pre-calculated value assumed to be correct.");
            subkey = new Subkey(key, HeaderSubkey.Headers);
            Assert.That(subkey.Key.Length, Is.EqualTo(16), "A Subkey is exactly 16 bytes.");
            Assert.That(subkey.Key.GetBytes(), Is.EquivalentTo(new byte[] { 0x1c, 0x81, 0x0e, 0xe7, 0x65, 0xe7, 0x0b, 0x8f, 0x7a, 0xa3, 0x2b, 0x03, 0x05, 0x07, 0xf8, 0x8a }), "Comparing with a pre-calculated value assumed to be correct.");
            subkey = new Subkey(key, HeaderSubkey.Hmac);
            Assert.That(subkey.Key.Length, Is.EqualTo(16), "A Subkey is exactly 16 bytes.");
            Assert.That(subkey.Key.GetBytes(), Is.EquivalentTo(new byte[] { 0xdb, 0xf1, 0x84, 0x11, 0x2e, 0xb9, 0x11, 0x16, 0x59, 0x71, 0x2b, 0xaf, 0xcf, 0xf2, 0xab, 0x24 }), "Comparing with a pre-calculated value assumed to be correct.");
            subkey = new Subkey(key, HeaderSubkey.Validator);
            Assert.That(subkey.Key.Length, Is.EqualTo(16), "A Subkey is exactly 16 bytes.");
            Assert.That(subkey.Key.GetBytes(), Is.EquivalentTo(new byte[] { 0x45, 0x22, 0xa0, 0x3d, 0x98, 0x00, 0x9d, 0x55, 0x45, 0xed, 0x42, 0xfb, 0xd8, 0x35, 0x78, 0xd0 }), "Comparing with a pre-calculated value assumed to be correct.");

            Assert.That(new Subkey(key, HeaderSubkey.Hmac).Key.GetBytes(), Is.EquivalentTo(new Subkey(key, HeaderSubkey.Hmac).Key.GetBytes()), "The subkey generation should be stable.");
        }
示例#2
0
        public static void TestInvalidArguments()
        {
            AesKey key = new AesKey();
            AesIV iv = new AesIV();

            Assert.Throws<ArgumentNullException>(() =>
            {
                if (new AesCrypto(null) == null) { }
            });

            Assert.Throws<ArgumentNullException>(() =>
            {
                if (new AesCrypto(null, iv, CipherMode.CBC, PaddingMode.None) == null) { }
            });

            Assert.Throws<ArgumentNullException>(() =>
            {
                if (new AesCrypto(key, null, CipherMode.CBC, PaddingMode.None) == null) { }
            });

            Assert.DoesNotThrow(() =>
            {
                if (new AesCrypto(key, iv, CipherMode.CBC, PaddingMode.None) == null) { }
            });
        }
        public static void TestComparisons()
        {
            AesKey key1 = new AesKey(new byte[] { 5, 6, 7, 8, 2, 4, 55, 77, 34, 65, 89, 12, 45, 87, 54, 255 });
            AesKey key2 = new AesKey(new byte[] { 5, 6, 7, 8, 2, 4, 55, 77, 34, 65, 89, 12, 45, 87, 54, 255 });
            KeyWrapSalt salt1 = new KeyWrapSalt(AesKey.DefaultKeyLength);
            KeyWrapSalt salt2 = new KeyWrapSalt(AesKey.DefaultKeyLength);

            AesKeyThumbprint thumbprint1a = new AesKeyThumbprint(key1, salt1, 13);
            AesKeyThumbprint thumbprint1a_alias = thumbprint1a;
            AesKeyThumbprint thumbprint1b = new AesKeyThumbprint(key1, salt2, 25);
            AesKeyThumbprint thumbprint2a = new AesKeyThumbprint(key2, salt2, 25);
            AesKeyThumbprint thumbprint2b = new AesKeyThumbprint(key2, salt1, 13);
            AesKeyThumbprint nullThumbprint = null;

            Assert.That(thumbprint1a == thumbprint1a_alias, "Same instance should of course compare equal.");
            Assert.That(nullThumbprint != thumbprint1a, "A null should not compare equal to any other instance.");
            Assert.That(thumbprint1a != nullThumbprint, "A null should not compare equal to any other instance.");
            Assert.That(thumbprint1a == thumbprint2b, "Same raw key and salt, but different instance, should compare equal.");
            Assert.That(thumbprint1b == thumbprint2a, "Same raw key and salt, but different instance, should compare equal.");
            Assert.That(thumbprint1a != thumbprint1b, "Same raw key but different salt, should compare inequal.");
            Assert.That(thumbprint2a != thumbprint2b, "Same raw key but different salt, should compare inequal.");

            object object1a = thumbprint1a;
            object object2b = thumbprint2b;
            Assert.That(object1a.Equals(nullThumbprint), Is.False, "An instance does not equals null.");
            Assert.That(object1a.Equals(object2b), Is.True, "The two instances are equivalent.");

            object badTypeObject = key1;
            Assert.That(object1a.Equals(badTypeObject), Is.False, "The object being compared to is of the wrong type.");
        }
        public static void TestMethods()
        {
            AesKey key = new AesKey();
            HMAC hmac = AxCryptHMACSHA1.Create(key);

            Assert.That(hmac.Key, Is.EquivalentTo(key.GetBytes()), "Ensure that we're using the specified key.");
        }
示例#5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Subkey"/> class. Different data is encrypted using
        /// different variants of the master encryption key.
        /// </summary>
        /// <param name="masterKey">The master key.</param>
        /// <param name="headerSubkey">The header subkey.</param>
        public Subkey(AesKey masterKey, HeaderSubkey headerSubkey)
        {
            if (masterKey == null)
            {
                throw new ArgumentNullException("masterKey");
            }

            byte[] block = new byte[16];
            byte subKeyValue;
            switch (headerSubkey)
            {
                case HeaderSubkey.Hmac:
                    subKeyValue = 0;
                    break;
                case HeaderSubkey.Validator:
                    subKeyValue = 1;
                    break;
                case HeaderSubkey.Headers:
                    subKeyValue = 2;
                    break;
                case HeaderSubkey.Data:
                    subKeyValue = 3;
                    break;
                default:
                    throw new InternalErrorException("headerSubkey");
            }

            block[0] = subKeyValue;
            using (AesCrypto aesCrypto = new AesCrypto(masterKey))
            {
                _subKey = new AesKey(aesCrypto.Encrypt(block));
            }
        }
示例#6
0
        public static void TestInvalidArguments()
        {
            AesKey key = null;
            Assert.DoesNotThrow(() =>
            {
                key = new AesKey(new byte[16]);
            });
            Assert.DoesNotThrow(() =>
            {
                key = new AesKey(new byte[24]);
            });
            Assert.DoesNotThrow(() =>
            {
                key = new AesKey(new byte[32]);
            });

            Assert.Throws<InternalErrorException>(() =>
            {
                key = new AesKey(new byte[0]);
            });

            Assert.Throws<ArgumentNullException>(() =>
            {
                key = new AesKey((byte[])null);
            });

            // Use the instance to avoid FxCop errors.
            Object.Equals(key, null);
        }
示例#7
0
 public static void TestAddNewKnownKey()
 {
     KnownKeys knownKeys = new KnownKeys();
     AesKey key = new AesKey();
     knownKeys.Add(key);
     Assert.That(knownKeys.Keys.First(), Is.EqualTo(key), "The first and only key should be the one just added.");
 }
示例#8
0
 /// <summary>
 /// Decrypt a source file to a destination file, given a passphrase
 /// </summary>
 /// <param name="sourceFile">The source file</param>
 /// <param name="destinationFile">The destination file</param>
 /// <param name="passphrase">The passphrase</param>
 /// <returns>true if the passphrase was correct</returns>
 public static bool Decrypt(IRuntimeFileInfo sourceFile, IRuntimeFileInfo destinationFile, AesKey key, AxCryptOptions options, ProgressContext progress)
 {
     if (sourceFile == null)
     {
         throw new ArgumentNullException("sourceFile");
     }
     if (destinationFile == null)
     {
         throw new ArgumentNullException("destinationFile");
     }
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     if (progress == null)
     {
         throw new ArgumentNullException("progress");
     }
     using (AxCryptDocument document = Document(sourceFile, key, new ProgressContext()))
     {
         if (!document.PassphraseIsValid)
         {
             return false;
         }
         Decrypt(document, destinationFile, options, progress);
     }
     return true;
 }
示例#9
0
        public static void DecryptAndOpenFile(IRuntimeFileInfo encryptedDocument, Passphrase passphrase, ProgressContext progress, Action<string, ProgressContext> failure = null)
        {
            string tempPath = Path.GetTempPath();
            string decryptedFileName;
            lastUsedKey = passphrase.DerivedPassphrase;

            if (!TryDecrypt(encryptedDocument, tempPath, lastUsedKey, progress, out decryptedFileName)) {
                failure("Could not open file", progress);
                return;
            }

            string fullPathToDecryptedFile = Path.Combine(tempPath, decryptedFileName);
            IRuntimeFileInfo decryptedFile = OS.Current.FileInfo(fullPathToDecryptedFile);

            NSDictionary userInfo = new NSDictionary(Launcher.TargetFileUserInfoKey, decryptedFile.FullName);
            NSNotification notification = NSNotification.FromName(Launcher.FileDecryptedNotification, new NSObject(), userInfo);
            NSNotificationCenter.DefaultCenter.PostNotification(notification);

            ILauncher launcher = OS.Current.Launch (fullPathToDecryptedFile);
            launcher.Exited += (sender, e) => {
                fileSystemState.CheckActiveFiles(ChangedEventMode.RaiseOnlyOnModified, new ProgressContext());
            };

            fileSystemState.Add (new ActiveFile(encryptedDocument, decryptedFile, lastUsedKey, ActiveFileStatus.AssumedOpenAndDecrypted, launcher));
            //fileSystemState.Save ();
        }
示例#10
0
        public static void Setup()
        {
            SetupAssembly.AssemblySetup();

            _keyEncryptingKey = new AesKey(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F });
            _keyData = new AesKey(new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF });
            _wrapped = new byte[] { 0x1F, 0xA6, 0x8B, 0x0A, 0x81, 0x12, 0xB4, 0x47, 0xAE, 0xF3, 0x4B, 0xD8, 0xFB, 0x5A, 0x7B, 0x82, 0x9D, 0x3E, 0x86, 0x23, 0x71, 0xD2, 0xCF, 0xE5 };
        }
示例#11
0
 /// <summary>
 /// An AxCrypt HMAC SHA1-calculating stream. This uses the AxCrypt variant with a block size of 20 for the key.
 /// </summary>
 /// <param name="key">The key for the HMAC</param>
 /// <param name="chainedStream">A stream where data is chain-written to. This stream is not disposed of when this instance is disposed.</param>
 public HmacStream(AesKey key, Stream chainedStream)
 {
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     _hmac = AxCryptHMACSHA1.Create(key);
     ChainedStream = chainedStream;
 }
        //
        // Helpers
        //

        private static MacRequestSigner MakeSigner()
        {
            // The test data is generated with the actual web page JS.
            var key = new AesKey("PBXONDZUWVCJFAV25C7XR7IYDQ",
                                 "WyICHHlP5lPigZUGZYoivbJMqgHjSti86UKwdjCryYM".Decode64Loose());
            var seed = 842346063u;

            return(new MacRequestSigner(key, seed));
        }
 public SimulatorFactory(IMemoryCache cache, IHttpContextAccessor context, Settings settings)
 {
     _key     = settings.Instance.GetSecretKey();
     _private = settings.Instance.GetPrivateKey();
     _config  = settings.Endpoints.Simulator;
     _orkId   = settings.Instance.Username;
     _cache   = cache;
     _context = context.HttpContext;
 }
示例#14
0
 public static void TestAddSameKeyTwice()
 {
     KnownKeys knownKeys = new KnownKeys();
     AesKey key = new AesKey();
     knownKeys.Add(key);
     knownKeys.Add(key);
     Assert.That(knownKeys.Keys.Count(), Is.EqualTo(1), "Only one key should be in the collection even if added twice.");
     Assert.That(knownKeys.Keys.First(), Is.EqualTo(key), "The first and only key should be the one just added.");
 }
示例#15
0
 /// <summary>
 /// An AxCrypt HMAC SHA1-calculating stream. This uses the AxCrypt variant with a block size of 20 for the key.
 /// </summary>
 /// <param name="key">The key for the HMAC</param>
 /// <param name="chainedStream">A stream where data is chain-written to. This stream is not disposed of when this instance is disposed.</param>
 public HmacStream(AesKey key, Stream chainedStream)
 {
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     _hmac         = AxCryptHMACSHA1.Create(key);
     ChainedStream = chainedStream;
 }
示例#16
0
        public void ImportKey(AesKey aesKey, string key)
        {
            switch (aesKey)
            {
            case AesKey.Base64String: WrappedAes.FromBase64String(key); return;

            case AesKey.HexString: WrappedAes.FromHexString(key); return;
            }
        }
示例#17
0
        /// <summary>
        /// Check if a provided key matches the thumbprint of this instance.
        /// </summary>
        /// <param name="key">A key to check against this instances thumbprint.</param>
        /// <returns>true if the thumbprint matches the provided key.</returns>
        public bool ThumbprintMatch(AesKey key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            return(key.Thumbprint == Thumbprint);
        }
示例#18
0
        public void RewrapMasterKey(AesKey masterKey, AesKey keyEncryptingKey)
        {
            KeyWrapSalt salt = new KeyWrapSalt(keyEncryptingKey.Length);

            using (KeyWrap keyWrap = new KeyWrap(keyEncryptingKey, salt, Iterations, KeyWrapMode.AxCrypt))
            {
                byte[] wrappedKeyData = keyWrap.Wrap(masterKey);
                Set(wrappedKeyData, salt, Iterations);
            }
        }
示例#19
0
        public static void TestDefaultEncryptionKey()
        {
            KnownKeys knownKeys = new KnownKeys();
            AesKey    key       = new AesKey();

            knownKeys.DefaultEncryptionKey = key;
            Assert.That(knownKeys.DefaultEncryptionKey, Is.EqualTo(key), "The DefaultEncryptionKey should be the one just set as it.");
            Assert.That(knownKeys.Keys.Count(), Is.EqualTo(1), "Only one key should be in the collection.");
            Assert.That(knownKeys.Keys.First(), Is.EqualTo(key), "The first and only key should be the one just set as DefaultEncryptionKey.");
        }
示例#20
0
 public static void TestAddTwoNewKnownKeys()
 {
     KnownKeys knownKeys = new KnownKeys();
     AesKey key1 = new AesKey();
     knownKeys.Add(key1);
     AesKey key2 = new AesKey();
     knownKeys.Add(key2);
     Assert.That(knownKeys.Keys.First(), Is.EqualTo(key2), "The first key should be the last one added.");
     Assert.That(knownKeys.Keys.Last(), Is.EqualTo(key1), "The last key should be the first one added.");
 }
示例#21
0
        public static void TestAddSameKeyTwice()
        {
            KnownKeys knownKeys = new KnownKeys();
            AesKey    key       = new AesKey();

            knownKeys.Add(key);
            knownKeys.Add(key);
            Assert.That(knownKeys.Keys.Count(), Is.EqualTo(1), "Only one key should be in the collection even if added twice.");
            Assert.That(knownKeys.Keys.First(), Is.EqualTo(key), "The first and only key should be the one just added.");
        }
示例#22
0
        public static void TestEquals()
        {
            AesKey key1 = new AesKey(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });
            AesKey key2 = new AesKey(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });
            AesKey key3 = new AesKey();

            Assert.That(!key1.Equals(null), "A key is never equal to a null reference.");
            Assert.That(key1.Equals(key2), "Two different, but equivalent keys should compare equal.");
            Assert.That(!key1.Equals(key3), "Two really different keys should not compare equal.");
        }
示例#23
0
        public static void TestEquals()
        {
            AesKey key1 = new AesKey(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });
            AesKey key2 = new AesKey(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });
            AesKey key3 = new AesKey();

            Assert.That(!key1.Equals(null), "A key is never equal to a null reference.");
            Assert.That(key1.Equals(key2), "Two different, but equivalent keys should compare equal.");
            Assert.That(!key1.Equals(key3), "Two really different keys should not compare equal.");
        }
示例#24
0
        static bool TryDecrypt(IRuntimeFileInfo file, string filePath, AesKey key, ProgressContext progress, out string encryptedFileName)
        {
            encryptedFileName = AxCryptFile.Decrypt(file, filePath, key, AxCryptOptions.EncryptWithCompression, progress);

            if (encryptedFileName == null)
            {
                return(false);
            }
            return(true);
        }
示例#25
0
        /// <summary>
        ///
        /// </summary>
        public static AesKey WriteNewKey(string path, RijndaelManaged managed)
        {
            var key = new AesKey(managed);

            using (var stream = new FileStream(path, FileMode.CreateNew))
            {
                new BinaryFormatter().Serialize(stream, key);
            }
            return(key);
        }
示例#26
0
        public static void Run()
        {
            var cipherText = Convert.FromBase64String(
                "yptyoDdVBdQtGhgoePppYHnWyugGmy0j81sf3zBeUXEO/LYRw+2XmVa0/v6YiSy9Kj8gMn/gNu2I7dPmfgSEHPUDJpNpiOWmmW1/jw/Pt29Are5tumWmnfkazcAb23xe7B4ruPZVxUEhfn/IrZPNZdr4cQNrHNgEv2ts8gVFuOBU+p792UPy8/mEIhW5ECppxGIb7Yrpg4w7IYNeFtX5d9W4W1t2e+6PcdcjkBK4a8y1cjEtuQ07RpPChOvLcSzlB/Bg7UKntzorRsn+y/d72qD2QxRzcXgbynCNalF7zaT6pEnwKB4i05fTQw6nB7SU1w2/EvCGlfiyR2Ia08mA0GikqegYA6xG/EAGs3ZJ0aQUGt0YZz0P7uBsQKdmCg7jzzEMHyGZDNGTj0F2dOFHLSOTT2/GGSht8eD/Ae7u/xnJj0bGgAKMtNttGFlNyvKpt2vDDT3Orfk6Jk/rD4CIz6O/Tnt0NkJLucHtIyvBYGtQR4+mhbfUELkczeDSxTXGDLaiU3de6tPaa0/vjzizoUbNFdfkIly/HWINdHoO83E=").AsSpan();
            var iv = Convert.FromBase64String("DkBbcmQo1QH+ed1wTyBynA==").AsSpan();

            var plaintext = new byte[cipherText.Length].AsSpan();
            var keyBuffer = new byte[32].AsSpan();
            var key       = AesKey.Create(keyBuffer);

            ref var a = ref keyBuffer[0];
示例#27
0
 private void Initialize(IRuntimeFileInfo encryptedFileInfo, IRuntimeFileInfo decryptedFileInfo, DateTime lastWriteTimeUtc, AesKey key, AesKeyThumbprint thumbprint, ActiveFileStatus status, ILauncher process)
 {
     EncryptedFileInfo = OS.Current.FileInfo(encryptedFileInfo.FullName);
     DecryptedFileInfo = OS.Current.FileInfo(decryptedFileInfo.FullName);
     Key                        = key;
     Thumbprint                 = thumbprint;
     Status                     = status;
     LastActivityTimeUtc        = OS.Current.UtcNow;
     Process                    = process;
     LastEncryptionWriteTimeUtc = lastWriteTimeUtc;
 }
示例#28
0
        private static void DerivePerConsoleKeys(KeySet s)
        {
            // Todo: Dev and newer key generations
            var kek = new AesKey();

            // Derive the device key
            if (!s.PerConsoleKeySource.IsZeros() && !s.KeyBlobKeys[0].IsZeros())
            {
                Aes.DecryptEcb128(s.PerConsoleKeySource, s.DeviceKey, s.KeyBlobKeys[0]);
            }

            // Derive device-unique save keys
            for (int i = 0; i < s.DeviceUniqueSaveMacKeySources.Length; i++)
            {
                if (!s.DeviceUniqueSaveMacKekSource.IsZeros() && !s.DeviceUniqueSaveMacKeySources[i].IsZeros() &&
                    !s.DeviceKey.IsZeros())
                {
                    GenerateKek(s.DeviceKey, s.DeviceUniqueSaveMacKekSource, kek, s.AesKekGenerationSource, null);
                    Aes.DecryptEcb128(s.DeviceUniqueSaveMacKeySources[i], s.DeviceUniqueSaveMacKeys[i], kek);
                }
            }

            // Derive BIS keys
            if (s.DeviceKey.IsZeros() ||
                s.BisKekSource.IsZeros() ||
                s.AesKekGenerationSource.IsZeros() ||
                s.AesKeyGenerationSource.IsZeros() ||
                s.RetailSpecificAesKeySource.IsZeros())
            {
                return;
            }

            // If the user doesn't provide bis_key_source_03 we can assume it's the same as bis_key_source_02
            if (s.BisKeySources[3].IsZeros() && !s.BisKeySources[2].IsZeros())
            {
                s.BisKeySources[3] = s.BisKeySources[2];
            }

            Aes.DecryptEcb128(s.RetailSpecificAesKeySource, kek, s.DeviceKey);
            if (!s.BisKeySources[0].IsZeros())
            {
                Aes.DecryptEcb128(s.BisKeySources[0], s.BisKeys[0], kek);
            }

            GenerateKek(s.DeviceKey, s.BisKekSource, kek, s.AesKekGenerationSource, s.AesKeyGenerationSource);

            for (int i = 1; i < 4; i++)
            {
                if (!s.BisKeySources[i].IsZeros())
                {
                    Aes.DecryptEcb128(s.BisKeySources[i], s.BisKeys[i], kek);
                }
            }
        }
示例#29
0
        public string ExportKey(AesKey aesKey)
        {
            switch (aesKey)
            {
            case AesKey.Base64String: return(WrappedAes.ToBase64String());

            case AesKey.HexString: return(WrappedAes.ToHexString());

            default: throw new NotSupportedException();
            }
        }
示例#30
0
        public static void TestMethods()
        {
            AesKey key = new AesKey();

            Assert.That(key.GetBytes().Length, Is.EqualTo(16), "The default key length is 128 bits.");
            Assert.That(key.GetBytes(), Is.Not.EquivalentTo(new byte[16]), "A random key cannot be expected to be all zeros.");

            AesKey specifiedKey = new AesKey(key.GetBytes());

            Assert.That(specifiedKey.GetBytes(), Is.EquivalentTo(key.GetBytes()), "The specified key should contain the bits given to it.");
        }
示例#31
0
        /// <summary>
        /// Initializes a new instance of the AxCryptHMACSHA1 class
        /// with a provided key.
        /// </summary>
        /// <param name="key">The key</param>
        public static HMAC Create(AesKey key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            AxCryptHMACSHA1 hmac = new AxCryptHMACSHA1();
            hmac.BlockSizeValue = 20;
            hmac.Key = key.GetBytes();

            return hmac;
        }
示例#32
0
 /// <summary>
 /// Add a thumb print to the list of known thumb prints
 /// </summary>
 /// <param name="thumbprint">The key to add the fingerprint of</param>
 /// <returns>True if a new thumb print was added, false if it was already known.</returns>
 private bool AddKnownThumbprint(AesKey key)
 {
     lock (_knownThumbprints)
     {
         if (_knownThumbprints.Contains(key.Thumbprint))
         {
             return(false);
         }
         _knownThumbprints.Add(key.Thumbprint);
         return(true);
     }
 }
示例#33
0
        public static void TestAddTwoNewKnownKeys()
        {
            KnownKeys knownKeys = new KnownKeys();
            AesKey    key1      = new AesKey();

            knownKeys.Add(key1);
            AesKey key2 = new AesKey();

            knownKeys.Add(key2);
            Assert.That(knownKeys.Keys.First(), Is.EqualTo(key2), "The first key should be the last one added.");
            Assert.That(knownKeys.Keys.Last(), Is.EqualTo(key1), "The last key should be the first one added.");
        }
示例#34
0
        public DocumentHeaders(DocumentHeaders documentHeaders)
        {
            List <HeaderBlock> headerBlocks = new List <HeaderBlock>();

            foreach (HeaderBlock headerBlock in documentHeaders._headerBlocks)
            {
                headerBlocks.Add((HeaderBlock)headerBlock.Clone());
            }
            _headerBlocks = headerBlocks;

            _keyEncryptingKey = documentHeaders._keyEncryptingKey;
        }
        public Task CreateUser(Guid vuid, AesKey auth, List <string> orks)
        {
            _items[vuid] = new Account
            {
                Vuid  = vuid,
                Key   = auth,
                Orks  = orks,
                State = TransactionState.New
            };

            return(Task.CompletedTask);
        }
示例#36
0
        public void Constructor_Contructs256BitKeyWithExpansion_Expanded()
        {
            byte[] keyBytes =
            {
                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
                0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25
            };
            AesKey key = new AesKey(keyBytes);

            byte[] expected = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x27, 0x37, 0x3D, 0x90, 0x23, 0x32, 0x3B, 0x97, 0x2B, 0x3B, 0x31, 0x9C, 0x27, 0x36, 0x3F, 0x93, 0xDC, 0x14, 0x67, 0xCF, 0xC8, 0x01, 0x71, 0xD8, 0xD0, 0x18, 0x51, 0xF9, 0xF2, 0x3B, 0x75, 0xDC, 0xC7, 0xAA, 0xBB, 0x19, 0xE4, 0x98, 0x80, 0x8E, 0xCF, 0xA3, 0xB1, 0x12, 0xE8, 0x95, 0x8E, 0x81, 0x47, 0x3E, 0x7E, 0xC3, 0x8F, 0x3F, 0x0F, 0x1B, 0x5F, 0x27, 0x5E, 0xE2, 0xAD, 0x1C, 0x2B, 0x3E, 0x5F, 0x5B, 0x09, 0x8C, 0xBB, 0xC3, 0x89, 0x02, 0x74, 0x60, 0x38, 0x10, 0x9C, 0xF5, 0xB6, 0x91, 0x99, 0xD8, 0x30, 0x42, 0x16, 0xE7, 0x3F, 0x59, 0x49, 0xC0, 0x61, 0xBB, 0xE4, 0xDC, 0x4A, 0x85, 0xD1, 0x8D, 0x9E, 0xE5, 0x6A, 0x4E, 0x17, 0xE7, 0x1E, 0x2E, 0x2F, 0xF7, 0x82, 0xDB, 0x99, 0x66, 0x8A, 0x61, 0xDE, 0x71, 0x9C, 0x86, 0xE1, 0x28, 0xD5, 0x46, 0x80, 0x93, 0x31, 0x9A, 0xCA, 0x16, 0x79, 0xF9, 0xD9, 0x22, 0x13, 0xB7, 0xCE, 0xC5, 0x0D, 0x99, 0xE1, 0x32, 0x8F, 0x42, 0x78, 0x54, 0xF9, 0x4D, 0x62, 0x51, 0x65, 0xCB, 0x83, 0x79, 0xB0, 0x8D, 0x03, 0xEA, 0x81, 0x17, 0xC9, 0xFC, 0xA9, 0x24, 0x69, 0x2E, 0xBA, 0x93, 0xA7, 0xEB, 0xB7, 0x0A, 0x46, 0xD9, 0x38, 0x48, 0x3E, 0x8D, 0xFE, 0x1F, 0xD0, 0x0C, 0x9B, 0xD4, 0x53, 0x75, 0x2B, 0x59, 0x50, 0x9F, 0xAA, 0x4E, 0x99, 0x63, 0xC6, 0xCA, 0x92, 0x82, 0x7C, 0x59, 0x35, 0x69, 0xCB, 0x53, 0x73, 0xB0, 0xF3, 0x1B, 0x4D, 0x3D };
            CollectionAssert.AreEqual(expected, key.Bytes);
        }
示例#37
0
        public void Constructor_Contructs192BitKeyWithExpansion_Expanded()
        {
            byte[] keyBytes =
            {
                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
                0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17
            };
            AesKey key = new AesKey(keyBytes);

            byte[] expected = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x58, 0x46, 0xF2, 0xF9, 0x5C, 0x43, 0xF4, 0xFE, 0x54, 0x4A, 0xFE, 0xF5, 0x58, 0x47, 0xF0, 0xFA, 0x48, 0x56, 0xE2, 0xE9, 0x5C, 0x43, 0xF4, 0xFE, 0x40, 0xF9, 0x49, 0xB3, 0x1C, 0xBA, 0xBD, 0x4D, 0x48, 0xF0, 0x43, 0xB8, 0x10, 0xB7, 0xB3, 0x42, 0x58, 0xE1, 0x51, 0xAB, 0x04, 0xA2, 0xA5, 0x55, 0x7E, 0xFF, 0xB5, 0x41, 0x62, 0x45, 0x08, 0x0C, 0x2A, 0xB5, 0x4B, 0xB4, 0x3A, 0x02, 0xF8, 0xF6, 0x62, 0xE3, 0xA9, 0x5D, 0x66, 0x41, 0x0C, 0x08, 0xF5, 0x01, 0x85, 0x72, 0x97, 0x44, 0x8D, 0x7E, 0xBD, 0xF1, 0xC6, 0xCA, 0x87, 0xF3, 0x3E, 0x3C, 0xE5, 0x10, 0x97, 0x61, 0x83, 0x51, 0x9B, 0x69, 0x34, 0x15, 0x7C, 0x9E, 0xA3, 0x51, 0xF1, 0xE0, 0x1E, 0xA0, 0x37, 0x2A, 0x99, 0x53, 0x09, 0x16, 0x7C, 0x43, 0x9E, 0x77, 0xFF, 0x12, 0x05, 0x1E, 0xDD, 0x7E, 0x0E, 0x88, 0x7E, 0x2F, 0xFF, 0x68, 0x60, 0x8F, 0xC8, 0x42, 0xF9, 0xDC, 0xC1, 0x54, 0x85, 0x9F, 0x5F, 0x23, 0x7A, 0x8D, 0x5A, 0x3D, 0xC0, 0xC0, 0x29, 0x52, 0xBE, 0xEF, 0xD6, 0x3A, 0xDE, 0x60, 0x1E, 0x78, 0x27, 0xBC, 0xDF, 0x2C, 0xA2, 0x23, 0x80, 0x0F, 0xD8, 0xAE, 0xDA, 0x32, 0xA4, 0x97, 0x0A, 0x33, 0x1A, 0x78, 0xDC, 0x09, 0xC4, 0x18, 0xC2, 0x71, 0xE3, 0xA4, 0x1D, 0x5D };
            CollectionAssert.AreEqual(expected, key.Bytes);
        }
示例#38
0
        /// <summary>
        /// Loads an AxCrypt file from the specified reader. After this, the reader is positioned to
        /// read encrypted data.
        /// </summary>
        /// <param name="stream">The stream to read from. Will be disposed when this instance is disposed.</param>
        /// <returns>True if the key was valid, false if it was wrong.</returns>
        public bool Load(Stream stream, AesKey key)
        {
            _reader = AxCryptReader.Create(stream);
            DocumentHeaders documentHeaders = new DocumentHeaders(key);

            PassphraseIsValid = documentHeaders.Load(_reader);
            if (PassphraseIsValid)
            {
                DocumentHeaders = documentHeaders;
            }
            return(PassphraseIsValid);
        }
示例#39
0
        /// <summary>
        ///
        /// </summary>
        public static void DecryptFile(AesKey aesKey, string inputPath, string outputPath, int bufferLength = BufferLength)
        {
            if (aesKey == null)
            {
                throw new ArgumentNullException(nameof(aesKey));
            }

            var key       = aesKey.GetKey();
            var iv        = aesKey.GetIv();
            var keyLength = aesKey.KeySize;

            if (!key.Any() || keyLength <= 0)
            {
                throw new KeyLengthException(Resources.key);
            }
            if (iv == null)
            {
                throw new ArgumentNullException(Resources.iv);
            }
            if (!iv.Any())
            {
                throw new ByteArrayLengthException(Resources.iv);
            }

            using (var rif = new RijndaelManaged())
            {
                rif.Key       = key;
                rif.IV        = iv;
                rif.KeySize   = keyLength;
                rif.BlockSize = aesKey.BlockSize;
                rif.Mode      = aesKey.Mode;
                rif.Padding   = aesKey.Padding;

                using (var decryptor = rif.CreateDecryptor(key, iv))
                {
                    using (var inStream = new FileStream(inputPath, FileMode.Open))
                    {
                        using (var csDecrypt = new CryptoStream(inStream, decryptor, CryptoStreamMode.Read))
                        {
                            using (var outFile = new FileStream(outputPath, FileMode.CreateNew))
                            {
                                var buffer = new byte[bufferLength];
                                int read;
                                while ((read = csDecrypt.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    outFile.Write(buffer, 0, read);
                                }
                            }
                        }
                    }
                }
            }
        }
示例#40
0
        public static void TestObjectEquals()
        {
            object key1 = new AesKey(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });
            object key2 = new AesKey(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });
            object key3 = new AesKey();

            Assert.That(!key1.Equals(null), "A key is never equal to a null reference.");
            Assert.That(key1.Equals(key2), "Two different, but equivalent keys should compare equal.");
            Assert.That(!key1.Equals(key3), "Two really different keys should not compare equal.");

            Assert.That(key1.GetHashCode(), Is.EqualTo(key2.GetHashCode()), "The hashcodes should be the same for two different but equivalent keys.");
        }
示例#41
0
        public static void TestPassphraseConstructor()
        {
            Passphrase passphrase = new Passphrase("A Passphrase");
            AesKey     derivedKey = passphrase.DerivedPassphrase;

            Assert.That(derivedKey.Length, Is.EqualTo(16), "The default derived key is 128 bits.");

            Assert.Throws <ArgumentNullException>(() =>
            {
                passphrase = new Passphrase(null);
            });
        }
示例#42
0
        public static void TestThumbprint()
        {
            AesKey key1 = new AesKey(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });

            AesKeyThumbprint originalThumbprint = key1.Thumbprint;

            Assert.That(originalThumbprint, Is.EqualTo(key1.Thumbprint), "The thumbprints should be the same.");

            key1.Thumbprint = new AesKeyThumbprint(key1, new KeyWrapSalt(AesKey.DefaultKeyLength), OS.Current.KeyWrapIterations);

            Assert.That(originalThumbprint, Is.Not.EqualTo(key1.Thumbprint), "The thumbprints should differ.");
        }
示例#43
0
        private void Initialize(AesKey keyEncryptingKey)
        {
            AesKey      masterKey  = new AesKey();
            long        iterations = OS.Current.KeyWrapIterations;
            KeyWrapSalt salt       = new KeyWrapSalt(keyEncryptingKey.Length);

            using (KeyWrap keyWrap = new KeyWrap(keyEncryptingKey, salt, iterations, KeyWrapMode.AxCrypt))
            {
                byte[] wrappedKeyData = keyWrap.Wrap(masterKey);
                Set(wrappedKeyData, salt, iterations);
            }
        }
示例#44
0
        /// <summary>
        ///
        /// </summary>
        public static void EncryptFile(AesKey aesKey, string filePath, int bufferLength = BufferLength)
        {
            if (aesKey == null)
            {
                throw new ArgumentNullException(nameof(aesKey));
            }

            var key       = aesKey.GetKey();
            var iv        = aesKey.GetIv();
            var keyLength = aesKey.KeySize;

            if (!key.Any() || keyLength <= 0)
            {
                throw new KeyLengthException(Resources.key);
            }
            if (iv == null)
            {
                throw new ArgumentNullException(Resources.iv);
            }
            if (!iv.Any())
            {
                throw new ByteArrayLengthException(Resources.iv);
            }

            using (var rif = new RijndaelManaged())
            {
                rif.Key       = key;
                rif.IV        = iv;
                rif.KeySize   = keyLength;
                rif.BlockSize = aesKey.BlockSize;
                rif.Mode      = aesKey.Mode;
                rif.Padding   = aesKey.Padding;

                using (var encryptor = rif.CreateEncryptor(key, iv))
                {
                    var readWriter = new SynchronizedReadWriter(filePath);
                    while (!readWriter.WriteComplete)
                    {
                        readWriter.Read(bufferLength);
                        using (var ms = new MemoryStream())
                        {
                            using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                            {
                                cs.Write(readWriter.GetBuffer(), 0, readWriter.GetBuffer().Length);
                            }
                            readWriter.SetBuffer(ms.ToArray());
                            readWriter.Write();
                        }
                    }
                }
            }
        }
示例#45
0
        public static void TestInvalidArguments()
        {
            IRuntimeFileInfo sourceFileInfo      = OS.Current.FileInfo(_testTextPath);
            IRuntimeFileInfo destinationFileInfo = sourceFileInfo.CreateEncryptedName();
            AxCryptDocument  document            = new AxCryptDocument();
            IRuntimeFileInfo decryptedFileInfo   = OS.Current.FileInfo(Path.Combine(_rootPath, "decrypted test.txt"));

            AxCryptDocument  nullDocument     = null;
            IRuntimeFileInfo nullFileInfo     = null;
            AesKey           nullKey          = null;
            ProgressContext  nullProgress     = null;
            Passphrase       nullPassphrase   = null;
            Stream           nullStream       = null;
            string           nullString       = null;
            Action <Stream>  nullStreamAction = null;

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(nullFileInfo, destinationFileInfo, new Passphrase("axcrypt"), AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, nullFileInfo, new Passphrase("axcrypt"), AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, destinationFileInfo, nullPassphrase, AxCryptOptions.EncryptWithCompression, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, destinationFileInfo, new Passphrase("axcrypt"), AxCryptOptions.EncryptWithCompression, nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(nullFileInfo, new MemoryStream(), new AesKey(), AxCryptOptions.None, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, nullStream, new AesKey(), AxCryptOptions.None, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, new MemoryStream(), nullKey, AxCryptOptions.None, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Encrypt(sourceFileInfo, new MemoryStream(), new AesKey(), AxCryptOptions.None, nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(nullDocument, decryptedFileInfo, AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(document, nullFileInfo, AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(document, decryptedFileInfo, AxCryptOptions.SetFileTimes, nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(nullFileInfo, decryptedFileInfo, new AesKey(), AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, nullFileInfo, new AesKey(), AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, decryptedFileInfo, nullKey, AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, decryptedFileInfo, new AesKey(), AxCryptOptions.SetFileTimes, nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(nullFileInfo, Path.Combine(_rootPath, "Directory"), new AesKey(), AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, nullString, new AesKey(), AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, Path.Combine(_rootPath, "Directory"), nullKey, AxCryptOptions.SetFileTimes, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Decrypt(sourceFileInfo, Path.Combine(_rootPath, "Directory"), new AesKey(), AxCryptOptions.SetFileTimes, nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Document(nullFileInfo, new AesKey(), new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Document(sourceFileInfo, nullKey, new ProgressContext()); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Document(sourceFileInfo, new AesKey(), nullProgress); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.WriteToFileWithBackup(null, (Stream stream) => { }, new ProgressContext()); });
            IRuntimeFileInfo fileInfo = OS.Current.FileInfo(_testTextPath);

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.WriteToFileWithBackup(fileInfo, nullStreamAction, new ProgressContext()); });

            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.MakeAxCryptFileName(nullFileInfo); });
            Assert.Throws <ArgumentNullException>(() => { AxCryptFile.Wipe(nullFileInfo, new ProgressContext()); });
        }
示例#46
0
 public ActiveFile(ActiveFile activeFile, AesKey key)
 {
     if (activeFile == null)
     {
         throw new ArgumentNullException("activeFile");
     }
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     Initialize(activeFile);
     LastActivityTimeUtc = activeFile.LastActivityTimeUtc;
     Key = key;
 }
示例#47
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Passphrase"/> class.
        /// </summary>
        /// <param name="passphrase">The passphrase.</param>
        public Passphrase(string passphrase)
        {
            if (passphrase == null)
            {
                throw new ArgumentNullException("passphrase");
            }

            HashAlgorithm hashAlgorithm = new SHA1Managed();
            byte[] ansiBytes = Encoding.GetEncoding(1252).GetBytes(passphrase);
            byte[] hash = hashAlgorithm.ComputeHash(ansiBytes);
            byte[] derivedPassphrase = new byte[16];
            Array.Copy(hash, derivedPassphrase, derivedPassphrase.Length);

            _derivedPassphrase = new AesKey(derivedPassphrase);
        }
        public static void TestAesKeyThumbprintMethods()
        {
            AesKey key1 = new AesKey(new byte[] { 5, 6, 7, 8, 2, 4, 55, 77, 34, 65, 89, 12, 45, 87, 54, 255 });
            AesKey key2 = new AesKey(new byte[] { 5, 6, 7, 8, 2, 4, 55, 77, 34, 65, 89, 12, 45, 87, 54, 255 });
            KeyWrapSalt salt1 = new KeyWrapSalt(16);
            KeyWrapSalt salt2 = new KeyWrapSalt(salt1.GetBytes());

            AesKeyThumbprint thumbprint1 = new AesKeyThumbprint(key1, salt1, 10);
            AesKeyThumbprint thumbprint2 = new AesKeyThumbprint(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.");

            AesKeyThumbprint thumbprint3 = new AesKeyThumbprint(new AesKey(), new KeyWrapSalt(AesKey.DefaultKeyLength), 10);
            Assert.That(thumbprint2 != thumbprint3, "Two very different keys and salts should not be equivalent.");
        }
示例#49
0
 /// <summary>
 /// Instantiate a transformation
 /// </summary>
 /// <param name="key">The key</param>
 /// <param name="iv">Initial Vector</param>
 /// <param name="cipherMode">Mode of operation, typically CBC</param>
 /// <param name="paddingMode">Padding mode, typically PCS7</param>
 public AesCrypto(AesKey key, AesIV iv, CipherMode cipherMode, PaddingMode paddingMode)
 {
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     if (iv == null)
     {
         throw new ArgumentNullException("iv");
     }
     _aes = new AesManaged();
     _aes.Key = key.GetBytes();
     _aes.Mode = cipherMode;
     _aes.IV = iv.GetBytes();
     _aes.Padding = paddingMode;
 }
示例#50
0
 static TokenCrypt()
 {
     try
     {
         CryptKey = JsonHelper.ParseJson<AesKey>(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, KeyFile)).Trim());
     }
     catch(FileNotFoundException)
     {
         using(var aes = new AesManaged())
         {
             aes.GenerateKey();
             aes.GenerateIV();
             CryptKey = new AesKey { Key = aes.Key, IV = aes.IV };
             File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, KeyFile), CryptKey.ToJsonString());
         }
     }
 }
示例#51
0
        public static void TestDoubleDispose()
        {
            AesKey key = new AesKey();
            AesIV iv = new AesIV();

            AesCrypto crypto = new AesCrypto(key, iv, CipherMode.CBC, PaddingMode.None);
            crypto.Dispose();
            Assert.Throws<ObjectDisposedException>(() =>
            {
                crypto.CreateDecryptingTransform();
            });
            crypto.Dispose();
            Assert.Throws<ObjectDisposedException>(() =>
            {
                crypto.CreateDecryptingTransform();
            });
        }
示例#52
0
        public static void TestConstructor()
        {
            AesKey key = new AesKey();
            ILauncher process = new FakeLauncher(String.Empty);
            IRuntimeFileInfo decryptedFileInfo = OS.Current.FileInfo(_testTextPath);
            IRuntimeFileInfo encryptedFileInfo = OS.Current.FileInfo(_helloWorldAxxPath);
            using (ActiveFile activeFile = new ActiveFile(encryptedFileInfo, decryptedFileInfo, key, ActiveFileStatus.None, process))
            {
                decryptedFileInfo = activeFile.DecryptedFileInfo;
                Assert.That(decryptedFileInfo.Exists, Is.True, "The file should exist in the fake file system.");
                Assert.That(decryptedFileInfo.FullName, Is.EqualTo(_testTextPath), "The file should be named as it was in the constructor");
                Assert.That(decryptedFileInfo.LastWriteTimeUtc, Is.EqualTo(decryptedFileInfo.LastWriteTimeUtc), "When a LastWriteTime is not specified, the decrypted file should be used to determine the value.");
                Assert.That(activeFile.Process, Is.EqualTo(process), "The process should be set from the constructor.");
                SetupAssembly.FakeRuntimeEnvironment.TimeFunction = (() => { return DateTime.UtcNow.AddMinutes(1); });
                using (ActiveFile otherFile = new ActiveFile(activeFile, ActiveFileStatus.AssumedOpenAndDecrypted))
                {
                    Assert.That(otherFile.Status, Is.EqualTo(ActiveFileStatus.AssumedOpenAndDecrypted), "The status should be as given in the constructor.");
                    Assert.That(otherFile.DecryptedFileInfo.FullName, Is.EqualTo(activeFile.DecryptedFileInfo.FullName), "This should be copied from the original instance.");
                    Assert.That(otherFile.EncryptedFileInfo.FullName, Is.EqualTo(activeFile.EncryptedFileInfo.FullName), "This should be copied from the original instance.");
                    Assert.That(otherFile.Key, Is.EqualTo(activeFile.Key), "This should be copied from the original instance.");
                    Assert.That(otherFile.LastActivityTimeUtc, Is.GreaterThan(activeFile.LastActivityTimeUtc), "This should not be copied from the original instance, but should be a later time.");
                    Assert.That(otherFile.Process, Is.EqualTo(process), "This should be copied from the original instance.");
                    Assert.That(activeFile.Process, Is.Null, "The process should only be owned by one instance at a time.");
                    Assert.That(otherFile.ThumbprintMatch(activeFile.Key), Is.True, "The thumbprints should match.");
                }

                using (ActiveFile otherFile = new ActiveFile(activeFile, ActiveFileStatus.AssumedOpenAndDecrypted, process))
                {
                    Assert.That(otherFile.Process, Is.EqualTo(process), "This should be copied from the instance provided in the constructor.");
                }

                activeFile.DecryptedFileInfo.LastWriteTimeUtc = activeFile.DecryptedFileInfo.LastWriteTimeUtc.AddDays(1);
                using (ActiveFile otherFile = new ActiveFile(activeFile, OS.Current.UtcNow, ActiveFileStatus.AssumedOpenAndDecrypted))
                {
                    Assert.That(activeFile.IsModified, Is.True, "The original instance has not been encrypted since the last change.");
                    Assert.That(otherFile.IsModified, Is.False, "The copy indicates that it has been encrypted and thus is not modified.");
                }
            }
        }
示例#53
0
        /// <summary>
        /// Create a KeyWrap instance for wrapping or unwrapping
        /// </summary>
        /// <param name="key">The key wrapping key</param>
        /// <param name="salt">An optional salt, or null if none. AxCrypt uses a salt.</param>
        /// <param name="iterations">The number of wrapping iterations, at least 6</param>
        /// <param name="mode">Use original specification mode or AxCrypt mode (only difference is that 't' is little endian in AxCrypt mode)</param>
        public KeyWrap(AesKey key, KeyWrapSalt salt, long iterations, KeyWrapMode mode)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (salt == null)
            {
                throw new ArgumentNullException("salt");
            }
            if (salt.Length != 0 && salt.Length != key.Length)
            {
                throw new InternalErrorException("salt length is incorrect");
            }
            if (iterations < 6)
            {
                throw new InternalErrorException("iterations");
            }
            if (mode != KeyWrapMode.Specification && mode != KeyWrapMode.AxCrypt)
            {
                throw new InternalErrorException("mode");
            }
            _mode = mode;

            _key = key;
            _salt = salt;

            _iterations = iterations;

            byte[] saltedKey = _key.GetBytes();
            saltedKey.Xor(_salt.GetBytes());

            _aes.Mode = CipherMode.ECB;
            _aes.KeySize = _key.Length * 8;
            _aes.Key = saltedKey;
            _aes.Padding = PaddingMode.None;
        }
示例#54
0
 /// <summary>
 /// Loads an AxCrypt file from the specified reader. After this, the reader is positioned to
 /// read encrypted data.
 /// </summary>
 /// <param name="stream">The stream to read from. Will be disposed when this instance is disposed.</param>
 /// <returns>True if the key was valid, false if it was wrong.</returns>
 public bool Load(Stream stream, AesKey key)
 {
     _reader = AxCryptReader.Create(stream);
     DocumentHeaders documentHeaders = new DocumentHeaders(key);
     PassphraseIsValid = documentHeaders.Load(_reader);
     if (PassphraseIsValid)
     {
         DocumentHeaders = documentHeaders;
     }
     return PassphraseIsValid;
 }
 public void RewrapMasterKey(AesKey masterKey, AesKey keyEncryptingKey)
 {
     KeyWrapSalt salt = new KeyWrapSalt(keyEncryptingKey.Length);
     using (KeyWrap keyWrap = new KeyWrap(keyEncryptingKey, salt, Iterations, KeyWrapMode.AxCrypt))
     {
         byte[] wrappedKeyData = keyWrap.Wrap(masterKey);
         Set(wrappedKeyData, salt, Iterations);
     }
 }
 public KeyWrap1HeaderBlock(AesKey keyEncryptingKey)
     : this(new byte[44])
 {
     Initialize(keyEncryptingKey);
 }
 private void Initialize(AesKey keyEncryptingKey)
 {
     AesKey masterKey = new AesKey();
     long iterations = OS.Current.KeyWrapIterations;
     KeyWrapSalt salt = new KeyWrapSalt(keyEncryptingKey.Length);
     using (KeyWrap keyWrap = new KeyWrap(keyEncryptingKey, salt, iterations, KeyWrapMode.AxCrypt))
     {
         byte[] wrappedKeyData = keyWrap.Wrap(masterKey);
         Set(wrappedKeyData, salt, iterations);
     }
 }
        public byte[] UnwrapMasterKey(AesKey keyEncryptingKey, byte fileVersionMajor)
        {
            byte[] wrappedKeyData = GetKeyData();
            KeyWrapSalt salt = Salt;
            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[keyEncryptingKey.Length];
                Array.Copy(keyEncryptingKey.GetBytes(), 0, badKey, 0, 4);
                keyEncryptingKey = new AesKey(badKey);

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

            byte[] unwrappedKeyData;
            using (KeyWrap keyWrap = new KeyWrap(keyEncryptingKey, salt, Iterations, KeyWrapMode.AxCrypt))
            {
                unwrappedKeyData = keyWrap.Unwrap(wrappedKeyData);
            }
            return unwrappedKeyData;
        }
示例#59
0
 /// <summary>
 /// Instantiate an AES transform with zero IV, CBC and no padding.
 /// </summary>
 /// <param name="key">The key</param>
 public AesCrypto(AesKey key)
     : this(key, AesIV.Zero, CipherMode.CBC, PaddingMode.None)
 {
 }
 public KeyWrap1HeaderBlockForTest(AesKey key)
     : base(key)
 {
 }