Example #1
0
        public AES(AesKeySize keySize, string key, string iv)
        {
            algorithm         = new AesCryptoServiceProvider();
            algorithm.KeySize = (int)keySize;

            Initialize(key, iv, CipherMode.CBC);
        }
Example #2
0
 public AesKey GenerateAesKey(AesKeySize keySizeInBits)
 {
     return(new AesKey()
     {
         Key = GetRandomStr((int)keySizeInBits / 8), //xx bytes = xx * 8 bit
         IV = GetRandomStr(16)                       //16 bytes = 128bit
     });
 }
        public void GenerateAesKeyTest(AesKeySize keySize)
        {
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize);

            Assert.NotNull(encryptionKeyInfo.Key);
            Assert.NotNull(encryptionKeyInfo.IV);
            Assert.Equal((int)keySize / 8, encryptionKeyInfo.Key.Length);
        }
        /// <summary>
        ///     Decrypts the given encrypted text (cipher text) using the given key and key size.
        /// </summary>
        /// <param name="cipherText">The encrypted text to decrypt</param>
        /// <param name="key">The (HEXADECIMAL) key used to encrypt the text and that will be used to decrypt it</param>
        /// <param name="keySize">The size of the key for the creation of the cipher</param>
        public CommandResult <string> Decrypt(string cipherText, string key, AesKeySize keySize)
        {
            if (String.IsNullOrWhiteSpace(cipherText))
            {
                return(CommandResultFactory.Fail("There was no text given to decrypt", (string)null));
            }
            if (String.IsNullOrWhiteSpace(key))
            {
                return(CommandResultFactory.Fail("Could not decrypt the text. The given key was null or empty.", (string)null));
            }

            try
            {
                CommandResult <string> result;
                using (var aesCipher = Aes.Create())
                {
                    result = SetupCipher(aesCipher, key, keySize)
                             .Then(aes =>
                    {
                        var splitCipher = cipherText.Split('_');
                        if (splitCipher.Length != 2)
                        {
                            return(CommandResultFactory.Fail("The given cipher text was not in the correct encrypted format for decryption",
                                                             (string)null));
                        }
                        var initVector      = splitCipher[0];
                        var encryptedString = splitCipher[1];
                        if (initVector.Length % 2 != 0 || encryptedString.Length % 2 != 0)
                        {
                            return(CommandResultFactory.Fail("The given cipher text was not in the correct encrypted format for decryption",
                                                             (string)null));
                        }
                        aes.IV = initVector.ToHexBytes();
                        var cryptoTransform = aes.CreateDecryptor();
                        var cipherBytes     = encryptedString.ToHexBytes();
                        if (cipherBytes == null)
                        {
                            return(CommandResultFactory.Fail(
                                       "The encrypted string could not be converted into a Hexadecimal Byte Array and therefore could not be decrypted.",
                                       (string)null));
                        }
                        var resultTextBytes = cryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
                        var resultText      = resultTextBytes.ToUTF8String();

                        return(resultText == null
                                ? CommandResultFactory.Fail("Could not convert the decrypted bytes into a string.", (string)null)
                                : CommandResultFactory.Ok <string>(resultText));
                    });
                }

                return(result);
            }
            catch (Exception e)
            {
                var message = $"An exception was thrown while trying to decrypt the text. It is as follows:\n{e.Message}";
                return(CommandResultFactory.Fail(message, (string)null));
            }
        }
Example #5
0
        private ICryptoTransform CreateDecryptor(byte[] key, AesKeySize keySize = AesKeySize.Aes128, PaddingMode paddingMode = PaddingMode.PKCS7)
        {
            Aes aes = new Aes(key.Copy(), keySize);

            aes.PaddingMode           = paddingMode;
            aes.RemovePaddingFunction = PaddingFactory.GetRemovePaddingFunction(paddingMode);
            aes.InitializeRoundKey();
            return(new AesDecryptor(aes));
        }
Example #6
0
        private void ExecuteAesEncryptionTest <TContext>(AesKeySize aesKeyType) where TContext : DatabaseContext
        {
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(aesKeyType);
            var        provider          = new AesProvider(encryptionKeyInfo.Key, encryptionKeyInfo.IV, CipherMode.CBC, PaddingMode.Zeros);
            var        author            = new AuthorEntity("John", "Doe", 42)
            {
                Books = new List <BookEntity>()
                {
                    new BookEntity("Lorem Ipsum", 300),
                    new BookEntity("Dolor sit amet", 390)
                }
            };
            string authorEncryptedFirstName = provider.Encrypt(author.FirstName);
            string authorEncryptedLastName  = provider.Encrypt(author.LastName);
            string firstBookEncryptedName   = provider.Encrypt(author.Books.First().Name);
            string lastBookEncryptedName    = provider.Encrypt(author.Books.Last().Name);

            using (var contextFactory = new DatabaseContextFactory())
            {
                // Save data to an encrypted database context
                using (var dbContext = contextFactory.CreateContext <TContext>(provider))
                {
                    dbContext.Authors.Add(author);
                    dbContext.SaveChanges();
                }

                // Read encrypted data from normal context and compare with encrypted data.
                using (var dbContext = contextFactory.CreateContext <DatabaseContext>())
                {
                    var authorFromDb = dbContext.Authors.Include(x => x.Books).FirstOrDefault();

                    Assert.NotNull(authorFromDb);
                    Assert.Equal(authorEncryptedFirstName, authorFromDb.FirstName);
                    Assert.Equal(authorEncryptedLastName, authorFromDb.LastName);
                    Assert.NotNull(authorFromDb.Books);
                    Assert.NotEmpty(authorFromDb.Books);
                    Assert.Equal(2, authorFromDb.Books.Count);
                    Assert.Equal(firstBookEncryptedName, authorFromDb.Books.First().Name);
                    Assert.Equal(lastBookEncryptedName, authorFromDb.Books.Last().Name);
                }

                // Read decrypted data and compare with original data
                using (var dbContext = contextFactory.CreateContext <TContext>(provider))
                {
                    var authorFromDb = dbContext.Authors.Include(x => x.Books).FirstOrDefault();

                    Assert.NotNull(authorFromDb);
                    Assert.Equal(author.FirstName, authorFromDb.FirstName);
                    Assert.Equal(author.LastName, authorFromDb.LastName);
                    Assert.NotNull(authorFromDb.Books);
                    Assert.NotEmpty(authorFromDb.Books);
                    Assert.Equal(2, authorFromDb.Books.Count);
                    Assert.Equal(author.Books.First().Name, authorFromDb.Books.First().Name);
                    Assert.Equal(author.Books.Last().Name, authorFromDb.Books.Last().Name);
                }
            }
        }
Example #7
0
            public static ICryptoTransform CreateEncryptor(byte[] key, byte[] IV, AesKeySize keySize = AesKeySize.Aes128, PaddingMode paddingMode = PaddingMode.PKCS7)
            {
                Aes aes = new Aes(key.Copy(), IV.Copy(), keySize);

                aes.PaddingMode     = paddingMode;
                aes.PaddingFunction = PaddingFactory.GetPaddingFunction(paddingMode);
                aes.EncryptMode     = EncryptModeEnum.CBC;
                aes.InitializeRoundKey();
                return(new AesCBCEncryptor(aes));
            }
Example #8
0
            public Aes(byte[] byteKey, AesKeySize keySize = AesKeySize.Aes128)
            {
                this.KeySize = keySize;
                int kSz = GetKeySize();

                if (kSz != byteKey.Length)
                {
                    throw new ArgumentException($"Key length not equal {kSz}");
                }
                ByteKey = byteKey;
            }
Example #9
0
        private static Aes CreateAesGcm(byte[] key, byte[] IV, AesKeySize keySize)
        {
            byte[] newIV = new byte[IV.Length];
            Array.Copy(IV, 0, newIV, 0, IV.Length);

            Aes aes = new Aes(key.Copy(), newIV, keySize);

            aes.PaddingMode = PaddingMode.None;
            aes.EncryptMode = EncryptModeEnum.GCM;
            aes.InitializeRoundKey();
            return(aes);
        }
Example #10
0
        /// <summary>
        ///     Decrypts the cipher text by using the given key material, key size, and block size.
        /// </summary>
        /// <param name="cipherText">Encrypted text for decryption</param>
        /// <param name="key">The (HEXADECIMAL) key used for decryption</param>
        /// <param name="keySize">size of key used in the cipher creation</param>
        /// <param name="blockSize">block size used in the creation of the cipher</param>
        /// <returns></returns>
        public CommandResult <string> CustomDecrypt(string cipherText, string key, AesKeySize keySize, BlockSize blockSize)
        {
            if (String.IsNullOrWhiteSpace(cipherText))
            {
                return(CommandResultFactory.Fail("There was nothing to encrypt", (string)null));
            }
            if (String.IsNullOrWhiteSpace(key))
            {
                return(CommandResultFactory.Fail("The given encryption key was null or empty", cipherText));
            }

            try
            {
                var result = CreateCustomCipher(key, blockSize, keySize)
                             .Then(cipher =>
                {
                    var splitCipher = cipherText.Split('_');
                    if (splitCipher.Length != 2)
                    {
                        return(CommandResultFactory.Fail("The given cipher text was not in the correct encrypted format for decryption",
                                                         (string)null));
                    }
                    var initVector      = splitCipher[0];
                    var encryptedString = splitCipher[1];
                    if (initVector.Length % 2 != 0 || encryptedString.Length % 2 != 0)
                    {
                        return(CommandResultFactory.Fail("The given cipher text was not in the correct encrypted format for decryption",
                                                         (string)null));
                    }
                    cipher.IV           = initVector.ToHexBytes();
                    var cryptoTransform = cipher.CreateDecryptor();
                    var cipherBytes     = encryptedString.ToHexBytes();
                    if (cipherBytes == null)
                    {
                        return(CommandResultFactory.Fail(
                                   "The encrypted string could not be converted into a Hexadecimal Byte Array and therefore could not be decrypted.",
                                   (string)null));
                    }
                    var resultTextBytes = cryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
                    var resultText      = resultTextBytes.ToUTF8String();

                    return(resultText == null
                            ? CommandResultFactory.Fail("Could not convert the decrypted bytes into a string.", (string)null)
                            : CommandResultFactory.Ok <string>(resultText));
                });
                return(result);
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);
                return(CommandResultFactory.Fail($"An exception was thrown while attempting to decrypt the given text. It is as follows:\n\t{e.Message}", (string)null));
            }
        }
        /// <summary>
        /// Generates an AES key.
        /// </summary>
        /// <remarks>
        /// The key size of the Aes encryption must be 128, 192 or 256 bits.
        /// Please check https://blogs.msdn.microsoft.com/shawnfa/2006/10/09/the-differences-between-rijndael-and-aes/ for more informations.
        /// </remarks>
        /// <param name="keySize">AES Key size</param>
        /// <returns></returns>
        public static AesKeyInfo GenerateKey(AesKeySize keySize)
        {
            var crypto = new AesCryptoServiceProvider
            {
                KeySize   = (int)keySize,
                BlockSize = AesBlockSize
            };

            crypto.GenerateKey();
            crypto.GenerateIV();

            return(new AesKeyInfo(crypto.Key, crypto.IV));
        }
Example #12
0
        public void EncryptDecryptByteArrayTest(AesKeySize keySize)
        {
            byte[]     input             = DataHelper.RandomBytes(20);
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize);
            var        provider          = new AesProvider(encryptionKeyInfo.Key);

            byte[] encryptedData = provider.Encrypt(input, b => b, StandardConverters.StreamToBytes);
            Assert.NotNull(encryptedData);

            byte[] decryptedData = provider.Decrypt(encryptedData, b => b, StandardConverters.StreamToBytes);
            Assert.NotNull(decryptedData);

            Assert.Equal(input, decryptedData);
        }
Example #13
0
        public void EncryptDecryptStringTest(AesKeySize keySize)
        {
            string     input             = DataHelper.RandomString(20);
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize);
            var        provider          = new AesProvider(encryptionKeyInfo.Key);

            string encryptedData = provider.Encrypt(input, Encoding.UTF8.GetBytes, StandardConverters.StreamToBase64String);

            Assert.NotNull(encryptedData);

            string decryptedData = provider.Decrypt(encryptedData, Convert.FromBase64String, StandardConverters.StreamToString);

            Assert.NotNull(decryptedData);

            Assert.Equal(input, decryptedData);
        }
        public void CompareTwoAesKeysInstancesTest(AesKeySize keySize)
        {
            AesKeyInfo encryptionKeyInfo1    = AesProvider.GenerateKey(keySize);
            AesKeyInfo encryptionKeyInfo2    = AesProvider.GenerateKey(keySize);
            AesKeyInfo encryptionKeyInfoCopy = encryptionKeyInfo1;

            Assert.NotNull(encryptionKeyInfo1.Key);
            Assert.NotNull(encryptionKeyInfo1.IV);
            Assert.NotNull(encryptionKeyInfo2.Key);
            Assert.NotNull(encryptionKeyInfo2.IV);
            Assert.True(encryptionKeyInfo1 == encryptionKeyInfoCopy);
            Assert.True(encryptionKeyInfo1.Equals(encryptionKeyInfoCopy));
            Assert.True(encryptionKeyInfo1 != encryptionKeyInfo2);
            Assert.True(encryptionKeyInfo1.GetHashCode() != encryptionKeyInfo2.GetHashCode());
            Assert.False(encryptionKeyInfo1.Equals(0));
        }
        public void EncryptDecryptStringTest(AesKeySize keySize)
        {
            string     input             = StringHelper.RandomString(20);
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize);
            var        provider          = new AesProvider(encryptionKeyInfo.Key);

            string encryptedData = provider.Encrypt(input);

            Assert.NotNull(encryptedData);

            string decryptedData = provider.Decrypt(encryptedData);

            Assert.NotNull(decryptedData);

            Assert.Equal(input, decryptedData);
        }
Example #16
0
            public static ICryptoTransform CreateEncryptor(byte[] key, byte[] IV, AesKeySize keySize = AesKeySize.Aes128)
            {
                if (IV.Length != 12)
                {
                    throw new ArgumentException($"IV length not equal {12}");
                }

                byte[] newIV = new byte[16];
                Array.Copy(IV, 0, newIV, 0, IV.Length);

                Aes aes = new Aes(key.Copy(), newIV, keySize);

                aes.PaddingMode = PaddingMode.None;
                aes.EncryptMode = EncryptModeEnum.CTR;
                aes.InitializeRoundKey();
                return(new AesCTREncryptor(aes));
            }
        /// <summary>
        ///     Sets up all the parameters and properties for the AES cipher used in the encryption.
        /// </summary>
        /// <param name="cipher">
        ///     The already created AES cipher. This should be created within a using statement and then handed
        ///     off to this method.
        /// </param>
        /// <param name="key">The (HEXADECIMAL) key used for encryption inside the cipher</param>
        /// <param name="keySize">Key size used for setting up the cipher</param>
        public CommandResult <Aes> SetupCipher(Aes cipher, string key, AesKeySize keySize)
        {
            if (cipher == null)
            {
                return(CommandResultFactory.Fail("The given AES cipher object was null", (Aes)null));
            }
            if (String.IsNullOrWhiteSpace(key))
            {
                return(CommandResultFactory.Fail("The cipher creation key for the encryption was null or empty", (Aes)null));
            }

            byte[] keyBytes;
            try
            {
                keyBytes = key.ToHexBytes();
                if (keyBytes == null || keyBytes.Length != (int)keySize / 8)
                {
                    return(CommandResultFactory.Fail($"The cipher creation key for the encryption did not match the specified key size of {keySize}",
                                                     (Aes)null));
                }
            }
            catch (FormatException)
            {
                return(CommandResultFactory.Fail("The key was malformed and therefore threw a Format Exception when converting to a byte array.", (Aes)null));
            }
            catch (Exception e)
            {
                return(CommandResultFactory.Fail($"There was an exception thrown while trying to create the cipher. It is as follows:\n\t{e.Message}", (Aes)null));
            }

            cipher.KeySize   = (int)keySize;
            cipher.BlockSize = 128; // This is the default block size for AES encryption and apparently should not be changed according to what I'm reading
            cipher.Padding   = PaddingMode.PKCS7;
            cipher.Mode      = CipherMode.CBC;
            cipher.Key       = keyBytes;
            cipher.GenerateIV();
            return(CommandResultFactory.Ok(cipher));
        }
Example #18
0
        private static void ExecuteAesEncryptionTest <TContext>(AesKeySize aesKeyType) where TContext : DatabaseContext
        {
            AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(aesKeyType);
            var        provider          = new AesProvider(encryptionKeyInfo.Key, CipherMode.CBC, PaddingMode.Zeros);
            var        author            = new AuthorEntity("John", "Doe", 42)
            {
                Password = DataHelper.RandomSecureString(10),
                Books    = new List <BookEntity>
                {
                    new("Lorem Ipsum", 300),
                    new("Dolor sit amet", 390)
                }
            };

            using var contextFactory = new DatabaseContextFactory();

            // Save data to an encrypted database context
            using (var dbContext = contextFactory.CreateContext <TContext>(provider))
            {
                dbContext.Authors.Add(author);
                dbContext.SaveChanges();
            }

            // Read decrypted data and compare with original data
            using (var dbContext = contextFactory.CreateContext <TContext>(provider))
            {
                var authorFromDb = dbContext.Authors.Include(x => x.Books).FirstOrDefault();

                Assert.NotNull(authorFromDb);
                Assert.Equal(author.FirstName, authorFromDb.FirstName);
                Assert.Equal(author.LastName, authorFromDb.LastName);
                Assert.NotNull(authorFromDb.Books);
                Assert.NotEmpty(authorFromDb.Books);
                Assert.Equal(2, authorFromDb.Books.Count);
                Assert.Equal(author.Books.First().Name, authorFromDb.Books.First().Name);
                Assert.Equal(author.Books.Last().Name, authorFromDb.Books.Last().Name);
            }
        }
        /// <summary>
        ///     Encrypts the given text using the given key and key size for cipher creation.
        /// </summary>
        /// <param name="textForEncryption">Text to encrypt</param>
        /// <param name="key">The (HEXADECIMAL) encryption key to use for creating the cipher</param>
        /// <param name="keySize">Size of the key used for creating the cipher</param>
        public CommandResult <string> Encrypt(string textForEncryption, string key, AesKeySize keySize)
        {
            if (String.IsNullOrWhiteSpace(textForEncryption))
            {
                return(CommandResultFactory.Fail("There was nothing to encrypt", (string)null));
            }
            if (String.IsNullOrWhiteSpace(key))
            {
                return(CommandResultFactory.Fail("The given encryption key was null or empty", textForEncryption));
            }

            try
            {
                CommandResult <string> result;
                using (var aesCipher = Aes.Create())
                {
                    result = SetupCipher(aesCipher, key, keySize)
                             .Then(aes =>
                    {
                        var initVector          = aes.IV.ToHexString();
                        var textForEncryptBytes = textForEncryption.ToUtf8Bytes();
                        var cryptoTransform     = aes.CreateEncryptor();
                        var cipherTextBytes     = cryptoTransform.TransformFinalBlock(textForEncryptBytes, 0, textForEncryption.Length);
                        var cipherText          = cipherTextBytes.ToHexString();
                        var textResult          = $"{initVector}_{cipherText}";
                        return(CommandResultFactory.Ok <string>(textResult));
                    });
                }

                return(result);
            }
            catch (Exception e)
            {
                var message = $"An exception was thrown while trying to encrypt the text. It is as follows:\n{e.Message}";
                return(CommandResultFactory.Fail(message, (string)null));
            }
        }
Example #20
0
 public ICryptoTransform CreateEcbDecryptor(string key, AesKeySize keySize = AesKeySize.Aes128, PaddingMode paddingMode = PaddingMode.PKCS7)
 => CreateEcbDecryptor(key.GetKey(keySize), keySize, paddingMode);
Example #21
0
        private ICryptoTransform CreateEncryptor(byte[] key, byte[] IV, EncryptModeEnum encryptMode, AesKeySize keySize = AesKeySize.Aes128, PaddingMode paddingMode = PaddingMode.PKCS7)
        {
            if (EncryptModeEnum.CBC.Equals(encryptMode))
            {
                return(AesCBCEncryptor.CreateEncryptor(key, IV, keySize, paddingMode));
            }
            if (EncryptModeEnum.CTR.Equals(encryptMode))
            {
                return(AesCTREncryptor.CreateEncryptor(key, IV, keySize));
            }

            throw new Exception($"Encryption Mode {encryptMode} not valid");
        }
Example #22
0
 public ICryptoTransform CreateCtrEncryptor(byte[] key, byte[] IV, AesKeySize keySize = AesKeySize.Aes128, PaddingMode paddingMode = PaddingMode.PKCS7)
 => CreateEncryptor(key, IV, EncryptModeEnum.CTR, keySize, paddingMode);
Example #23
0
 public ICryptoTransform CreateCtrEncryptor(string key, byte[] IV, AesKeySize keySize = AesKeySize.Aes128, PaddingMode paddingMode = PaddingMode.PKCS7)
 => CreateCtrEncryptor(key.GetKey(keySize), IV, keySize, paddingMode);
Example #24
0
 /// <summary>
 /// 生成AES KEY(Generate AES KEY)
 /// </summary>
 /// <param name="keySize">AES KEY 长度(128-bit、192-bit、256-bit)</param>
 /// <returns></returns>
 public static string AESGenerateKey(AesKeySize keySize)
 {
     return(AESGenerateKey(keySize.ToInt()));
 }
Example #25
0
        private IAuthenticatedCryptoTransform CreateDecryptor(byte[] key, byte[] IV, byte[] additionalData, string tag, AesKeySize keySize = AesKeySize.Aes128)
        {
            Aes aes = CreateAesGcm(key, IV, keySize);

            return(new AesGCMEncryptor(aes, additionalData, tag));
        }
Example #26
0
 public IAuthenticatedCryptoTransform CreateGcmDecryptor(byte[] key, byte[] IV, byte[] additionalData, string tag, AesKeySize keySize = AesKeySize.Aes128)
 => CreateDecryptor(key, IV, additionalData, tag, keySize);
Example #27
0
 public IAuthenticatedCryptoTransform CreateGcmEncryptor(byte[] key, byte[] IV, byte[] additionalData, AesKeySize keySize = AesKeySize.Aes128)
 => CreateEncryptor(key, IV, additionalData, keySize);
Example #28
0
 public ICryptoTransform CreateEcbDecryptor(byte[] key, AesKeySize keySize = AesKeySize.Aes128, PaddingMode paddingMode = PaddingMode.PKCS7)
 => CreateDecryptor(key, keySize, paddingMode);
Example #29
0
 public AesManagerContext(byte[] byteKey, AesKeySize keySize = AesKeySize.Aes128)
 {
     aes = new Aes(byteKey, keySize);
 }
Example #30
0
 public static byte[] GetKey(this string key, AesKeySize keySize)
 => key.GetKey((int)keySize / 8);