Example #1
0
        /// <summary>
        ///     AES Encryption service.
        /// </summary>
        /// <param name="toEncryption">CLI input model.</param>
        /// <returns>CLI output model with information about decryption.</returns>
        public static SymmetricCryptographyCliOutput EncryptionRequest(ISymmetricCryptographyCliInput toEncryption, CryptoProvider cryptoProvider)
        {
            Log.Information($"New aes encryption request => {toEncryption.CipherType}");

            byte[] key = null;
            byte[] IV  = null;

            // check if user provide encryption key
            if (!string.IsNullOrEmpty(toEncryption.Key))
            {
                Log.Information("Working with the provided encryption key.");

                key = Convert.FromBase64String(toEncryption.Key);
            }
            else
            {
                Log.Information("Generating new encryption key.");

                key = cryptoProvider.GenerateKey(toEncryption.CipherType.KeySize);
            }

            // check if user provide IV
            if (!string.IsNullOrEmpty(toEncryption.InitializationVector) && toEncryption.CipherType.CipherMode != CipherMode.ECB)
            {
                Log.Information("Working with the provided initialization vector.");

                Console.WriteLine("Using same initialization vector for more then one encryption is not recommended!");
                IV = Convert.FromBase64String(toEncryption.InitializationVector);
            }
            else
            {
                Log.Information("Generating new initialization vector.");

                IV = cryptoProvider.GenerateInitializationVector();
            }

            var encrypted = cryptoProvider.Encrypt(toEncryption.Content, key, IV, toEncryption.CipherType.CipherMode);

            Log.Information("Successfully encrypted.");

            if (toEncryption.CipherType.CipherMode == CipherMode.ECB)
            {
                return(new SymmetricCryptographyCliOutput(key, encrypted, toEncryption.CipherType));
            }
            else
            {
                return(new SymmetricCryptographyCliOutput(IV, key, encrypted, toEncryption.CipherType));
            }
        }