Beispiel #1
0
        public static void ValidatePaddingMode_ISO10126(int expectedPaddingSize, string plainTextStr)
        {
            byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray();
            byte[] iv  = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray();

            byte[] plainText = plainTextStr.HexToByteArray();

            using (Aes a = Aes.Create())
            {
                a.Key     = key;
                a.IV      = iv;
                a.Mode    = CipherMode.CBC;
                a.Padding = PaddingMode.ISO10126;

                // for ISO10126 we are going to encrypt it twice and assert that the ciphers produced are going to be different
                byte[] cipher       = a.Encrypt(plainText);
                byte[] secondCipher = a.Encrypt(plainText);

                // decrypt it with PaddingMode.None so that we can inspect the padding manually
                a.Padding = PaddingMode.None;
                byte[] decrypted = a.Decrypt(cipher);

                if (expectedPaddingSize >= 5)
                {
                    byte[] secondDecrypted = a.Decrypt(secondCipher);

                    // after we decrypted, the two ciphers are going to be different
                    Assert.NotEqual(decrypted.ByteArrayToHex(), secondDecrypted.ByteArrayToHex());
                }

                ValidatePadding(decrypted, PaddingMode.ISO10126, expectedPaddingSize);
            }
        }
 private void DecryptMessage(XmlNode doc, ref byte[] iv)
 {
     foreach (XmlNode childNode in doc.ChildNodes[0].ChildNodes)
     {
         childNode.InnerXml = _aes.Decrypt(childNode.InnerXml);
     }
 }
Beispiel #3
0
        private static void ValidatePaddingMode(byte[] plainText, byte[] expectedCipher, PaddingMode paddingMode, int expectedPaddingSize)
        {
            byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray();
            byte[] iv  = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray();

            using (Aes a = Aes.Create())
            {
                a.Key     = key;
                a.IV      = iv;
                a.Mode    = CipherMode.CBC;
                a.Padding = paddingMode;

                byte[] cipher = a.Encrypt(plainText);

                // we cannot validate the cipher in this padding mode as it consists of random data
                if (paddingMode != PaddingMode.ISO10126)
                {
                    Assert.Equal <byte>(expectedCipher, cipher);
                }

                // decrypt it with PaddingMode.None so that we can inspect the padding manually
                a.Padding = PaddingMode.None;
                byte[] decrypted = a.Decrypt(cipher);
                ValidatePadding(decrypted, paddingMode, expectedPaddingSize);
            }
        }
Beispiel #4
0
        public void DecryptThrowsInvalidOperationExceptionIfDataToDecryptIsOfSizeZero()
        {
            IAes aes  = new Aes();
            var  data = new byte[0];

            aes.Decrypt(data, null, null, 1000);
        }
Beispiel #5
0
        public void AesTest()
        {
            Aes aes = new Aes();

            aes.Key = Encoding.UTF8.GetBytes("1234567890abcdef1234567890abcdef");
            aes.IV  = Encoding.UTF8.GetBytes("1234567890abcdef");

            string sd = "Hello World! ppppppppppppppppppppppppppppp" +
                        "pppppppppppppppppppppppppppppppppppppppppp" +
                        "pppppppppppppppppppppppppppppppppppppppppp" +
                        "pppppppppppppppppppppppppppppppppppppppppp" +
                        "pppppppppppppppppppppppppppppppppppppppppp" +
                        "pppppppppppppppppppppppppppppppppppppppppp" +
                        "pppppppppppppppppppppppppppppppppppppppppp" +
                        "pppppppppppppppppppppppppppppppppppppppppp" +
                        "pppppppppppppppppppppppppppppppppppppppppp" +
                        "pppppppppppppppppppppppppppppppppppppppppp" +
                        "pppppppppppppppppppppppppppppppppppppppppp" +
                        "pppppppppppppppppppppp";

            byte[] data = Encoding.UTF8.GetBytes(sd);

            aes.Init();

            byte[] e = aes.Encrypt(data);

            Assert.True(Encoding.UTF8.GetString(aes.Decrypt(e)) == sd);
        }
Beispiel #6
0
        public static void ValidatePaddingMode_NonISO10126(PaddingMode paddingMode, int expectedPaddingSize, string plainTextStr, string expectedCipherStr)
        {
            Assert.True(paddingMode != PaddingMode.ISO10126, "This tests only non-ISO10126 padding");

            byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray();
            byte[] iv  = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray();

            byte[] plainText      = plainTextStr.HexToByteArray();
            byte[] expectedCipher = expectedCipherStr == null?Array.Empty <byte>() : expectedCipherStr.HexToByteArray();

            using (Aes a = Aes.Create())
            {
                a.Key     = key;
                a.IV      = iv;
                a.Mode    = CipherMode.CBC;
                a.Padding = paddingMode;

                byte[] cipher = a.Encrypt(plainText);

                Assert.Equal(expectedCipherStr, cipher.ByteArrayToHex());

                // decrypt it with PaddingMode.None so that we can inspect the padding manually
                a.Padding = PaddingMode.None;
                byte[] decrypted = a.Decrypt(cipher);
                ValidatePadding(decrypted, paddingMode, expectedPaddingSize);
            }
        }
Beispiel #7
0
        public async Task LoadAccessTokensAsync(string clientId, string secretKey)
        {
            if (!await ApplicationData.Current.LocalFolder.ExistsAsync(TokenFilename))
            {
                return;
            }
            try
            {
                var file = await ApplicationData.Current.LocalFolder.GetFileAsync(TokenFilename);

                var content = await file.ReadBytesAsync();

                if (content.Length < 16)
                {
                    return;
                }

                var passphrase = (SystemInfo.HardwareIdentifier + clientId + secretKey).ToSecureString();
                var json       = Encoding.UTF8.GetString(Aes.Decrypt(passphrase, 10000, content));

                this.tokenInfos = JsonConvert.DeserializeObject <List <TokenKey> >(json);
            }
            catch (Exception)
            {
                // no need... this just means something is wrong with the cache and should be thrown away
            }
        }
Beispiel #8
0
        private void PackageReceivedEventArgs(object sender, PackageReceivedEventArgs <IPEndPoint> e)
        {
            var data  = e.Payload;
            var count = e.Count;

            PeerInfo peerInfo;

            if (_peerList.TryGet(e.Proto, out peerInfo) && peerInfo.EncryptionKey != null)
            {
                data = Aes.Decrypt(data, 0, count, peerInfo.EncryptionKey);
            }

            var botHeader = BotHeader.Decode(data);

            if (!IsValidHeader(botHeader))
            {
                Logger.Warn("Invalid message received by bot {0} from {1}", botHeader.BotId, e.Proto);
                _peerList.Punish(botHeader.BotId);
                return;
            }

            botHeader.EndPoint = e.Proto;
            _peerList.UpdatePeer(botHeader.BotId);

            var args = new PackageReceivedEventArgs <BotHeader>(botHeader, data, count);

            Events.Raise(BotPackageReceivedEventArgs, this, args);
        }
Beispiel #9
0
        public string GetPassword(string answer)
        {
            PasswordQuestion question = PasswordQuestionsByUserId.FirstOrDefault();
            string           result   = string.Empty;

            if (question == null)
            {
                Log.AddEntry("Unable to retrieve password for {0}, password question not set", UserName);
            }

            if (question.Answer.Equals(answer))
            {
                Password password = PasswordsByUserId.FirstOrDefault();
                if (password == null)
                {
                    Log.AddEntry("Unable to retrieve password for {0}, password not set", UserName);
                }

                result = Aes.Decrypt(password.Value);
            }
            else
            {
                Log.AddEntry("Unable to retrieve password for {0}, invalid password ", UserName);
            }
            return(result);
        }
Beispiel #10
0
        public bool ChangePasswordQuestionAndAnswer(string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            Password pass   = PasswordsByUserId.FirstOrDefault();
            bool     result = false;

            if (pass == null)
            {
                Log.AddEntry("Unable to change password question and answer, user password was not set");
            }
            else
            {
                string decrypted = Aes.Decrypt(pass.Value);
                if (decrypted.Equals(password))
                {
                    PasswordQuestion question = PasswordQuestionsByUserId.FirstOrDefault();
                    if (question == null)
                    {
                        question = PasswordQuestionsByUserId.AddNew();
                    }

                    question.Value  = newPasswordQuestion;
                    question.Answer = newPasswordAnswer;
                    question.Save();

                    result = true;
                }
            }
            return(result);
        }
Beispiel #11
0
        public static object LoadFromFile(
            string pathToFile,
            SecureString password)
        {
            var passwordHash   = SessionPasswordHelper.GetSessionPasswordBytes(password, hashIterationsCount: 5);
            var encryptedBytes = File.ReadAllBytes(pathToFile);

            var decryptedBytes = Aes.Decrypt(
                encryptedBytes: encryptedBytes,
                keyBytes: passwordHash);

            var json = Encoding.UTF8.GetString(decryptedBytes);

            var storage = JsonConvert.DeserializeObject <JObject>(json);

            var encryptedSeed = storage["Keys"]["1729"]["EncryptedSeed"].ToString();

            var seedPasswordHash = SessionPasswordHelper.GetSessionPasswordBytes(password);

            var seed = Aes.Decrypt(
                encryptedBytes: Hex.FromString(encryptedSeed),
                keyBytes: seedPasswordHash);

            storage["Seed"] = seed.ToHexString();

            return(storage);
        }
Beispiel #12
0
        protected Vector128 <byte> DecryptAes(Vector128 <byte> data)
        {
            if (DecryptionKey == null)
            {
                DecryptionKey = GenerateWorkingKey(Key, false);
            }

            data = Sse2.Xor(data, DecryptionKey[Rounds]);
            // unrolled for performance
            if (Rounds > 12)
            {
                data = Aes.Decrypt(data, DecryptionKey[13]);
                data = Aes.Decrypt(data, DecryptionKey[12]);
            }

            if (Rounds > 10)
            {
                data = Aes.Decrypt(data, DecryptionKey[11]);
                data = Aes.Decrypt(data, DecryptionKey[10]);
            }

            data = Aes.Decrypt(data, DecryptionKey[9]);
            data = Aes.Decrypt(data, DecryptionKey[8]);
            data = Aes.Decrypt(data, DecryptionKey[7]);
            data = Aes.Decrypt(data, DecryptionKey[6]);
            data = Aes.Decrypt(data, DecryptionKey[5]);
            data = Aes.Decrypt(data, DecryptionKey[4]);
            data = Aes.Decrypt(data, DecryptionKey[3]);
            data = Aes.Decrypt(data, DecryptionKey[2]);
            data = Aes.Decrypt(data, DecryptionKey[1]);
            return(Aes.DecryptLast(data, DecryptionKey[0]));
        }
Beispiel #13
0
        private static DataSettingsSmtpSettingsProvider LoadSmtpSettings()
        {
            FileInfo smtpSettingsFile = new FileInfo(Path.Combine(Paths.Local, SmtpSettingsFileName));

            Console.WriteLine("Trying to load smtp settings from file: {0}", smtpSettingsFile.FullName);
            if (smtpSettingsFile.Exists)
            {
                try
                {
                    SmtpSettings smtpSettings = smtpSettingsFile.FromJsonFile <SmtpSettings>();
                    smtpSettings.Password = Aes.Decrypt(smtpSettings.Password);
                    DefaultSender         = smtpSettings.From;
                    return(new DataSettingsSmtpSettingsProvider(smtpSettings));
                }
                catch (Exception ex)
                {
                    Log.Warn("Failed to load smtp settings file {0}: {1}", smtpSettingsFile.FullName, ex.Message);
                    Console.WriteLine("failed to load smtp settings: {0}", ex.Message);
                }
            }
            else
            {
                Log.Warn("The system smtp settings file was not present, notifications may not send correctly: {0}", smtpSettingsFile.FullName);
                Console.WriteLine("failed to load smtp settings, settings file not present: {0}", smtpSettingsFile.FullName);
            }
            return(new DataSettingsSmtpSettingsProvider());
        }
Beispiel #14
0
        public override unsafe void Decrypt(ReadOnlySpan <byte> source, Span <byte> destination)
        {
            base.Decrypt(source, destination);

            Vector128 <byte> t;

            fixed(byte *s = source)
            {
                t = Sse2.LoadVector128(s);
            }

            t = Sse2.Xor(t, _k14);
            t = Aes.Decrypt(t, _k15);
            t = Aes.Decrypt(t, _k16);
            t = Aes.Decrypt(t, _k17);
            t = Aes.Decrypt(t, _k18);
            t = Aes.Decrypt(t, _k19);
            t = Aes.Decrypt(t, _k20);
            t = Aes.Decrypt(t, _k21);
            t = Aes.Decrypt(t, _k22);
            t = Aes.Decrypt(t, _k23);
            t = Aes.Decrypt(t, _k24);
            t = Aes.Decrypt(t, _k25);
            t = Aes.Decrypt(t, _k26);
            t = Aes.Decrypt(t, _k27);
            t = Aes.DecryptLast(t, _k0);

            fixed(byte *d = destination)
            {
                Sse2.Store(d, t);
            }
        }
        private void generateButton_Click(object sender, EventArgs e)
        {
            MyFile       myFile       = new MyFile();
            WalletDotDat walletDotDat = new WalletDotDat();
            string       text         = myFile.ReadFile(path);

            string[] splitted = text.Split(' ');
            string   seed;
            int      i;

            if (splitted.Length != 12)
            {
                Aes aes = new Aes();
                walletDotDat.FromString(aes.Decrypt(text, password));
                seed = walletDotDat.mnemonics;
                i    = walletDotDat.bitcoinSecrets.Count;
            }
            else
            {
                walletDotDat.FromString(myFile.ReadFile(path));
                seed = walletDotDat.mnemonics;
                i    = walletDotDat.bitcoinSecrets.Count;
            }
            ExtKey extKey = Wallet.generateMasterAdress(seed);

            bitcoinSecret = Wallet.generateDerivedAdress(extKey, walletDotDat.bitcoinSecrets.Count());

            inputReceiving.Text = bitcoinSecret.PubKey.GetAddress(Network.TestNet).ToString(); //
            generateQRCode();
        }
Beispiel #16
0
        public string DecryptData(EncryptedData encryptedData, byte[] masterKey)
        {
            var dataKey = _pbkdf2.Compute(masterKey, encryptedData.Salt, encryptedData.Iterations);
            var message = _aes.Decrypt(encryptedData.Ciphertext, dataKey, encryptedData.InitializationVector);

            return(message);
        }
 private void saveButton_Click(object sender, EventArgs e)
 {
     if (inputReceiving.Text != "")
     {
         MyFile   myFile   = new MyFile();
         string   text     = myFile.ReadFile(path);
         string[] splitted = text.Split(' ');
         if (splitted.Length != 12)
         {
             Aes          aes          = new Aes();
             WalletDotDat walletDotDat = new WalletDotDat();
             //aes.Decrypt(f.ReadFile(ucChooseYourWallet.FilePath), ucChooseYourWallet.Password)
             walletDotDat.FromString(aes.Decrypt(text, password));
             walletDotDat.addPrivateKey(bitcoinSecret);
             MessageBox.Show(walletDotDat.ToString());
             myFile.SaveEncryptedFile(walletDotDat.ToString(), password, path);
         }
         else
         {
             WalletDotDat walletDotDat = new WalletDotDat();
             walletDotDat.FromString(myFile.ReadFile(path));
             walletDotDat.addPrivateKey(bitcoinSecret);
             myFile.SaveUnecryptedFile(walletDotDat.ToString(), path);
         }
     }
     else
     {
         MessageBox.Show("Generate adress and input needed info!");
     }
 }
Beispiel #18
0
        public void DecryptThrowsArgumentNullExceptionIfPasswordIsNullOrEmpty()
        {
            IAes aes  = new Aes();
            var  data = new byte[2];

            aes.Decrypt(data, null, null, 1000);
        }
Beispiel #19
0
 public static string Decrypt(this string cipherText, string key)
 {
     using (Aes aes = Aes.Create())
     {
         return(aes.Decrypt(key, new byte[16], Convert.FromBase64String(cipherText)));
     }
 }
Beispiel #20
0
            public void RunStructFldScenario(AesBinaryOpTest__DecryptByte testClass)
            {
                var result = Aes.Decrypt(_fld1, _fld2);

                Unsafe.Write(testClass._dataTable.outArrayPtr, result);
                testClass.ValidateResult(testClass._dataTable.outArrayPtr);
            }
Beispiel #21
0
 private static bool LicenceIsValid()
 {
     return(RegistryOperator.IsKeyExist("ActivationKey") &&
            RegistryOperator.IsKeyExist("SerialNumber") &&
            Aes.Decrypt(RegistryOperator.GetKey("ActivationKey"),
                        HardwareInfo.GetHddSerialNo(), 256)
            .Equals(RegistryOperator.GetKey("SerialNumber")));
 }
Beispiel #22
0
        public void Aes128_decrypt()
        {
            var(data, expected) = TestVectors["AES-128 Decryption"];

            var plaintext = Aes128.Decrypt(data);

            CustomAssert.MatchArrays(plaintext, expected);
        }
Beispiel #23
0
 public static MemoryStream DownloadStage(Uri url, int sleep = 1, int retries = 10)
 {
     return(Retry.Do(() =>
     {
         var key = GetSharedKey(url);
         var stage = Aes.Decrypt(key, Http.Get(url));
         return new MemoryStream(stage);
     }, TimeSpan.FromSeconds(sleep), retries));
 }
        public void AES_Encrypt_Decrypt_Test()
        {
            var password  = CryptoUtils.BrewPassword(10).ToSecureString();
            var testData  = "Test Test Hello";
            var encrypted = Aes.Encrypt(password, testData);
            var decrypted = Encoding.UTF8.GetString(Aes.Decrypt(password, encrypted));

            Assert.AreEqual(testData, decrypted);
        }
Beispiel #25
0
        public void RunClassFldScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));

            var result = Aes.Decrypt(_fld1, _fld2);

            Unsafe.Write(_dataTable.outArrayPtr, result);
            ValidateResult(_dataTable.outArrayPtr);
        }
Beispiel #26
0
        public void Decrypt(byte[] input, byte[] output)
        {
            int position = 0;
            int left     = input.Length;

            var key0  = Unsafe.ReadUnaligned <Vector128 <byte> >(ref dec[0 * BlockSize]);
            var key1  = Unsafe.ReadUnaligned <Vector128 <byte> >(ref dec[1 * BlockSize]);
            var key2  = Unsafe.ReadUnaligned <Vector128 <byte> >(ref dec[2 * BlockSize]);
            var key3  = Unsafe.ReadUnaligned <Vector128 <byte> >(ref dec[3 * BlockSize]);
            var key4  = Unsafe.ReadUnaligned <Vector128 <byte> >(ref dec[4 * BlockSize]);
            var key5  = Unsafe.ReadUnaligned <Vector128 <byte> >(ref dec[5 * BlockSize]);
            var key6  = Unsafe.ReadUnaligned <Vector128 <byte> >(ref dec[6 * BlockSize]);
            var key7  = Unsafe.ReadUnaligned <Vector128 <byte> >(ref dec[7 * BlockSize]);
            var key8  = Unsafe.ReadUnaligned <Vector128 <byte> >(ref dec[8 * BlockSize]);
            var key9  = Unsafe.ReadUnaligned <Vector128 <byte> >(ref dec[9 * BlockSize]);
            var key10 = Unsafe.ReadUnaligned <Vector128 <byte> >(ref dec[10 * BlockSize]);

            while (left >= BlockSize)
            {
                var block = Unsafe.ReadUnaligned <Vector128 <byte> >(ref input[position]);

                block = Aes.Decrypt(block, key0);
                block = Aes.InverseMixColumns(block);

                block = Aes.Decrypt(block, key1);
                block = Aes.InverseMixColumns(block);

                block = Aes.Decrypt(block, key2);
                block = Aes.InverseMixColumns(block);

                block = Aes.Decrypt(block, key3);
                block = Aes.InverseMixColumns(block);

                block = Aes.Decrypt(block, key4);
                block = Aes.InverseMixColumns(block);

                block = Aes.Decrypt(block, key5);
                block = Aes.InverseMixColumns(block);

                block = Aes.Decrypt(block, key6);
                block = Aes.InverseMixColumns(block);

                block = Aes.Decrypt(block, key7);
                block = Aes.InverseMixColumns(block);

                block = Aes.Decrypt(block, key8);
                block = Aes.InverseMixColumns(block);

                block = Aes.Decrypt(block, key9);
                block = Simd.Xor(block, key10);

                Unsafe.WriteUnaligned(ref output[position], block);

                position += BlockSize;
                left     -= BlockSize;
            }
        }
Beispiel #27
0
        public void DecryptDataThatHasBeenEncrypted()
        {
            IAes aes           = new Aes();
            var  originalData  = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
            var  encryptedData = aes.Encrypt(originalData, "password", Encoding.ASCII.GetBytes("eryryn78ynr78yn"), 1000);
            var  decryptedData = aes.Decrypt(encryptedData, "password", Encoding.ASCII.GetBytes("eryryn78ynr78yn"), 1000);

            Assert.IsFalse(ByteArrayCompare(originalData, decryptedData));
        }
Beispiel #28
0
 private static void MEOW_SHUFFLE(ref Vector128 <byte> r1, ref Vector128 <byte> r2, Vector128 <byte> r3, ref Vector128 <byte> r4, ref Vector128 <byte> r5, Vector128 <byte> r6)
 {
     r1 = Aes.Decrypt(r1, r4);
     r2 = AddQ(r2, r5);
     r4 = Sse2.Xor(r4, r6);
     r4 = Aes.Decrypt(r4, r2);
     r5 = AddQ(r5, r6);
     r2 = Sse2.Xor(r2, r3);
 }
Beispiel #29
0
        public void RunStructLclFldScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));

            var test   = TestStruct.Create();
            var result = Aes.Decrypt(test._fld1, test._fld2);

            Unsafe.Write(_dataTable.outArrayPtr, result);
            ValidateResult(_dataTable.outArrayPtr);
        }
Beispiel #30
0
        public void RunClassLclFldScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));

            var test   = new AesBinaryOpTest__DecryptByte();
            var result = Aes.Decrypt(test._fld1, test._fld2);

            Unsafe.Write(_dataTable.outArrayPtr, result);
            ValidateResult(_dataTable.outArrayPtr);
        }
Beispiel #31
0
        public void TestEncryptString()
        {
            var encryptor = new Aes();
            string raw = "Đây là Unicode string", key = "password", salt = "this_is_salt";
            byte[] encrypted; byte[] decrypted;

            // without salt
            encrypted = encryptor.Encrypt(raw, key);
            Assert.NotNull(encrypted);
            decrypted = encryptor.Decrypt(encrypted, key);
            Assert.NotNull(decrypted);
            Assert.Equal(raw, decrypted.GetString());

            // with salt
            encrypted = encryptor.Encrypt(raw, key, salt);
            Assert.NotNull(encrypted);
            decrypted = encryptor.Decrypt(encrypted, key);
            Assert.NotNull(decrypted);
            Assert.Equal(raw, decrypted.GetString());
        }