Ejemplo n.º 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);
            }
        }
Ejemplo n.º 2
0
        public void AesEncryptedSize()
        {
            var aesKey        = _aes.GenerateKey();
            var encryptedData = _aes.Encrypt("test data", aesKey);

            Assert.AreEqual(44, encryptedData.Length);
            Assert.AreEqual("=", encryptedData.Substring(43, 1));
            Assert.AreNotEqual("=", encryptedData.Substring(42, 1));
        }
Ejemplo n.º 3
0
        public override unsafe void Encrypt(ReadOnlySpan <byte> source, Span <byte> destination)
        {
            base.Encrypt(source, destination);

            Vector128 <byte> t;

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

            t = Sse2.Xor(t, _k0);
            t = Aes.Encrypt(t, _k1);
            t = Aes.Encrypt(t, _k2);
            t = Aes.Encrypt(t, _k3);
            t = Aes.Encrypt(t, _k4);
            t = Aes.Encrypt(t, _k5);
            t = Aes.Encrypt(t, _k6);
            t = Aes.Encrypt(t, _k7);
            t = Aes.Encrypt(t, _k8);
            t = Aes.Encrypt(t, _k9);
            t = Aes.Encrypt(t, _k10);
            t = Aes.Encrypt(t, _k11);
            t = Aes.Encrypt(t, _k12);
            t = Aes.Encrypt(t, _k13);
            t = Aes.EncryptLast(t, _k14);

            fixed(byte *d = destination)
            {
                Sse2.Store(d, t);
            }
        }
Ejemplo n.º 4
0
 public static string Encrypt(this string plainText, string key)
 {
     using (Aes aes = Aes.Create())
     {
         return(Convert.ToBase64String(aes.Encrypt(plainText, key, new byte[16])));
     }
 }
Ejemplo n.º 5
0
        public void EncryptThrowsInvalidOperationExceptionIfDataToEncryptIsOfSizeZero()
        {
            IAes aes  = new Aes();
            var  data = new byte[0];

            aes.Encrypt(data, null, null, 1000);
        }
Ejemplo n.º 6
0
        public static void SetDefaultSmtpSettings(SmtpSettings settings)
        {
            FileInfo smtpSettingsFile = new FileInfo(Path.Combine(Paths.Local, SmtpSettingsFileName));

            settings.Password = Aes.Encrypt(settings.Password);
            settings.ToJsonFile(smtpSettingsFile);
        }
Ejemplo n.º 7
0
        public void EncryptThrowsArgumentNullExceptionIfPasswordIsNullOrEmpty()
        {
            IAes aes  = new Aes();
            var  data = new byte[2];

            aes.Encrypt(data, null, null, 1000);
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
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);
            }
        }
Ejemplo n.º 10
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);
            }
        }
Ejemplo n.º 11
0
        private void SignIn()
        {
            ToggleProgressRingAndButton();

            CreateContext();
            string encrypted = string.Empty;

            if (AppPassword != null)
            {
                encrypted = Aes.Encrypt(AppPassword, UserSalts.Default);
            }

            if (!_context.Database.Exists() ||
                !_context.Users.Any(user =>
                                    user.Name == AppLogin &&
                                    user.Password == encrypted &&
                                    user.Role == UserRole.Manager))
            {
                Messenger.Default.Send(new NotificationMessage <string>
                                           ("Connection failed! Please make sure your data is correct and try again.", "ShowErrorBox"));
                ToggleProgressRingAndButton();
            }
            else
            {
                SetConfigData();
                SetEntitiesData();
                Messenger.Default.Send(new NotificationMessage <string>(string.Empty, "ShowMainWindow"));
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// A message is generated by encrypting a hard coded value with the provided Master Key and
        /// Initialization Vector.
        /// The message is then passed to the hashing function and the key used is the provided Master Key.
        /// </summary>
        public Authorization(MasterKey masterKey, byte[] initializationVector, Aes aes, HmacSha256 hmacSha256)
        {
            InitializationVector = initializationVector;
            var ciphertext = aes.Encrypt(AuthorizedMessage, masterKey.SecretKey, initializationVector);

            Hmac = hmacSha256.Compute(ciphertext, masterKey.SecretKey);
        }
Ejemplo n.º 13
0
        protected Vector128 <byte> EncryptAes(Vector128 <byte> data)
        {
            if (EncryptionKey == null)
            {
                EncryptionKey = GenerateWorkingKey(Key, true);
            }

            data = Sse2.Xor(data, EncryptionKey[0]);
            // unrolled for performance
            data = Aes.Encrypt(data, EncryptionKey[1]);
            data = Aes.Encrypt(data, EncryptionKey[2]);
            data = Aes.Encrypt(data, EncryptionKey[3]);
            data = Aes.Encrypt(data, EncryptionKey[4]);
            data = Aes.Encrypt(data, EncryptionKey[5]);
            data = Aes.Encrypt(data, EncryptionKey[6]);
            data = Aes.Encrypt(data, EncryptionKey[7]);
            data = Aes.Encrypt(data, EncryptionKey[8]);
            data = Aes.Encrypt(data, EncryptionKey[9]);
            if (Rounds > 10)
            {
                data = Aes.Encrypt(data, EncryptionKey[10]);
                data = Aes.Encrypt(data, EncryptionKey[11]);
                if (Rounds > 12)
                {
                    data = Aes.Encrypt(data, EncryptionKey[12]);
                    data = Aes.Encrypt(data, EncryptionKey[13]);
                }
            }

            return(Aes.EncryptLast(data, EncryptionKey[Rounds]));
        }
Ejemplo n.º 14
0
            public void RunStructFldScenario(AesBinaryOpTest__EncryptByte testClass)
            {
                var result = Aes.Encrypt(_fld1, _fld2);

                Unsafe.Write(testClass._dataTable.outArrayPtr, result);
                testClass.ValidateResult(testClass._dataTable.outArrayPtr);
            }
Ejemplo n.º 15
0
        public async Task <IActionResult> Register(string email, [FromHeader] string host)
        {
            // 判断该邮箱是否已经被注册
            if (DB.Users.Any(x => x.Email == email))
            {
                return(Prompt(x =>
                {
                    x.Title = "注册失败";
                    x.Details = $"电子邮箱{email}已经被注册,请更换后重试!";
                    x.StatusCode = 400;
                }));
            }

            // 发送激活信
            var aes_email = Aes.Encrypt(email);
            //var url = Url.Link("default", new { action = "RegisterDetail", controller = "Account", key = aes_email });
            var url = $"http://*****:*****@"<html>
            <head></head>
            <body>
            <p><a href=""{url}"">点击继续注册</a></p>
            </body>
            </html>");

            return(Prompt(x =>
            {
                x.Title = "请验证您的邮箱";
                x.Details = $"我们向您的邮箱{email}中发送了一条包含验证链接的邮件,请通过邮件打开链接继续完成注册操作";
                x.RedirectText = "进入邮箱";
                x.RedirectUrl = "http://mail." + email.Split('@')[1];
            }));
        }
Ejemplo n.º 16
0
        public void Aes128_encrypt()
        {
            var(data, expected) = TestVectors["AES-128 Encryption"];

            var ciphertext = Aes128.Encrypt(data);

            CustomAssert.MatchArrays(ciphertext, expected);
        }
Ejemplo n.º 17
0
        public void EncryptEncryptsDataUsingThePasswordAndTheResultIsDifferentToTheInput()
        {
            IAes aes           = new Aes();
            var  data          = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
            var  encryptedData = aes.Encrypt(data, "password", Encoding.ASCII.GetBytes("eryryn78ynr78yn"), 1000);

            Assert.IsTrue(ByteArrayCompare(data, encryptedData));
        }
Ejemplo n.º 18
0
        public void RunClassFldScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));

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

            Unsafe.Write(_dataTable.outArrayPtr, result);
            ValidateResult(_dataTable.outArrayPtr);
        }
Ejemplo n.º 19
0
        public void Encrypt(byte[] input, byte[] output)
        {
            int position = 0;
            int left     = input.Length;

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

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

                block = Aes.Encrypt(block, key0);
                block = Aes.MixColumns(block);

                block = Aes.Encrypt(block, key1);
                block = Aes.MixColumns(block);

                block = Aes.Encrypt(block, key2);
                block = Aes.MixColumns(block);

                block = Aes.Encrypt(block, key3);
                block = Aes.MixColumns(block);

                block = Aes.Encrypt(block, key4);
                block = Aes.MixColumns(block);

                block = Aes.Encrypt(block, key5);
                block = Aes.MixColumns(block);

                block = Aes.Encrypt(block, key6);
                block = Aes.MixColumns(block);

                block = Aes.Encrypt(block, key7);
                block = Aes.MixColumns(block);

                block = Aes.Encrypt(block, key8);
                block = Aes.MixColumns(block);

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

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

                position += BlockSize;
                left     -= BlockSize;
            }
        }
Ejemplo n.º 20
0
        public EncryptedData EncryptData(string message, byte[] masterKey, int dataKeyIterations)
        {
            var salt    = _pbkdf2.GenerateSalt();
            var dataKey = _pbkdf2.Compute(masterKey, salt, dataKeyIterations);
            var initializationVector = _aes.GenerateInitializationVector();
            var ciphertext           = _aes.Encrypt(message, dataKey, initializationVector);

            return(new EncryptedData(salt, initializationVector, dataKeyIterations, ciphertext));
        }
Ejemplo n.º 21
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));
        }
        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);
        }
Ejemplo n.º 23
0
        public static unsafe void AESBSingleRoundNative(byte[] keys, byte[] input)
        {
            fixed(byte *roundKeyPtr = keys, valPtr = input)
            {
                Vector128 <byte> roundKey = Sse2.LoadVector128(roundKeyPtr);
                Vector128 <byte> val      = Sse2.LoadVector128(valPtr);

                Sse2.Store(valPtr, Aes.Encrypt(val, roundKey));
            }
        }
Ejemplo n.º 24
0
        public void RunStructLclFldScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));

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

            Unsafe.Write(_dataTable.outArrayPtr, result);
            ValidateResult(_dataTable.outArrayPtr);
        }
Ejemplo n.º 25
0
        public void RunClassLclFldScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));

            var test   = new AesBinaryOpTest__EncryptByte();
            var result = Aes.Encrypt(test._fld1, test._fld2);

            Unsafe.Write(_dataTable.outArrayPtr, result);
            ValidateResult(_dataTable.outArrayPtr);
        }
Ejemplo n.º 26
0
        private Vector128 <byte> EncryptBlock(Vector128 <byte> data)
        {
            data = Sse2.Xor(data, _roundKeys[0]);
            for (int i = 1; i < _roundKeys.Length - 1; i++)
            {
                data = Aes.Encrypt(data, _roundKeys[i]);
            }

            return(Aes.EncryptLast(data, _roundKeys.Last()));
        }
Ejemplo n.º 27
0
        public void EncryptDecryptTest()
        {
            var password   = CreatePassword();
            var plainBytes = Encoding.ASCII.GetBytes("testdata");

            var encryptedBytes = Aes.Encrypt(plainBytes, password);
            var decryptedBytes = Aes.Decrypt(encryptedBytes, password);

            Assert.Equal(plainBytes, decryptedBytes);
        }
Ejemplo n.º 28
0
        public void RunLclVarScenario_LoadAligned()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));

            var left   = Aes.LoadAlignedVector128((Byte *)(_dataTable.inArray1Ptr));
            var right  = Aes.LoadAlignedVector128((Byte *)(_dataTable.inArray2Ptr));
            var result = Aes.Encrypt(left, right);

            Unsafe.Write(_dataTable.outArrayPtr, result);
            ValidateResult(_dataTable.outArrayPtr);
        }
Ejemplo n.º 29
0
        public void RunLclVarScenario_UnsafeRead()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));

            var left   = Unsafe.Read <Vector128 <Byte> >(_dataTable.inArray1Ptr);
            var right  = Unsafe.Read <Vector128 <Byte> >(_dataTable.inArray2Ptr);
            var result = Aes.Encrypt(left, right);

            Unsafe.Write(_dataTable.outArrayPtr, result);
            ValidateResult(_dataTable.outArrayPtr);
        }
Ejemplo n.º 30
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());
        }
Ejemplo n.º 31
0
        public void RunBasicScenario_Load()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));

            var result = Aes.Encrypt(
                Aes.LoadVector128((Byte *)(_dataTable.inArray1Ptr)),
                Aes.LoadVector128((Byte *)(_dataTable.inArray2Ptr))
                );

            Unsafe.Write(_dataTable.outArrayPtr, result);
            ValidateResult(_dataTable.outArrayPtr);
        }