/// <summary>
        /// 用输入的密钥和初始化向量,对输入的文本进行加密,返回加密后的结果
        /// 密钥与初始话向量不可为汉语
        /// </summary>
        /// <param name="input">要加密的内容</param>
        /// <param name="key">加密用的密钥</param>
        /// <param name="iv">加密用的初始化变量</param>
        /// <param name="bitLength">密钥的字节长度</param>
        /// <param name="encryptSymmetryType">要采用的对称加密算法</param>
        /// <returns>加密后的结果</returns>
        private static byte[] EncryptStringByKeyIV(this string input, byte[] key, byte[] iv, int bitLength, EncryptSymmetryType encryptSymmetryType)
        {
            if (input == null || input.Length <= 0)
            {
                throw new ArgumentNullException("input");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("iv");
            }

            SymmetricAlgorithm symmetricAlgorithm = null;

            byte[]       plainBytes   = null;
            MemoryStream memoryStream = new MemoryStream();

            switch (encryptSymmetryType)
            {
            case EncryptSymmetryType.DES:
            case EncryptSymmetryType.Rijandel:
            case EncryptSymmetryType.TripleDES:
            case EncryptSymmetryType.RC2:
            {
                symmetricAlgorithm = GetSymmetricAlgorithmBySmartEncryptSymmetryType(encryptSymmetryType);
                if (bitLength != int.MinValue && !symmetricAlgorithm.ValidKeySize(bitLength))
                {
                    throw new Exception("密钥大小对当前算法无效");
                }
                if (bitLength != int.MinValue && symmetricAlgorithm.ValidKeySize(bitLength))
                {
                    symmetricAlgorithm.KeySize = bitLength;
                }
                symmetricAlgorithm.Key = key;
                symmetricAlgorithm.IV  = iv;
                ICryptoTransform decryptor = symmetricAlgorithm.CreateEncryptor(symmetricAlgorithm.Key, symmetricAlgorithm.IV);
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
                    {
                        streamWriter.Write(input);
                    }

                    if (symmetricAlgorithm != null)
                    {
                        symmetricAlgorithm.Clear();
                    }
                }
            }

            break;
            }

            plainBytes = memoryStream.ToArray();
            return(plainBytes);
        }
Exemple #2
0
        public static void InitCryptAlgorithm(string keyHexString)
        {
            if (keyHexString == null || keyHexString.Length == 0)
            {
                _cryptAlgorithm = null;
                return; // encryption off
            }

            byte[] cryptKey = StringUtil.HexStringToByteArray(keyHexString);

            _cryptAlgorithm = SymmetricAlgorithm.Create(CRYPT_ALGORITHM);

            if (!_cryptAlgorithm.ValidKeySize(cryptKey.Length * 8))
            {
                string msg =
                    "Invalid Configuration value \"QueryStringEncryptionKey\". " +
                    "The specified key size of " + cryptKey.Length + " bytes is incorrect for the \"" + CRYPT_ALGORITHM + "\" algorithm. " +
                    "Try " + _cryptAlgorithm.Key.Length + " bytes.";
                throw new ApplicationException(msg);
            }

            // Set key and clear IV
            _cryptAlgorithm.Key = cryptKey;
            _cryptAlgorithm.IV  = new byte[_cryptAlgorithm.IV.Length];

            _cryptAlgorithm.Padding = PaddingMode.ISO10126; // using ISO padding introduces randomness to the padding bytes, preventing padding oracle probes from guessing at what correct padding is decrypting to.
        }
Exemple #3
0
        private static void ValidateBlockSize(
            SymmetricAlgorithm algorithm, IReadOnlyCollection <byte> initializationVector)
        {
            // Array length is bytes, IV size measured in bits.
            int initializationVectorSize = initializationVector.Count * BitsPerByte;             // (BitsPerByte == 8)

            if (algorithm.ValidKeySize(initializationVectorSize))
            {
                return;
            }

            string message = string.Format(
                "The size of the given initialization vector ({0}) does not match a valid block size ({2}) for the \"{1}\" algorithm.",
                initializationVector.Count,
                algorithm.GetType().Name,
                algorithm.LegalBlockSizes.Select(
                    legalBlockSize => string.Format(
                        "Max{0}Min{1}Skip{2}", legalBlockSize.MaxSize, legalBlockSize.MinSize, legalBlockSize.SkipSize))
                .ToDelimitedString(", "));

            ////	Contract.Requires<ArgumentOutOfRangeException>(
            ////		algorithm.ValidBlockSize(initializationVectorSize), message);
            throw new TypeInitializationException(
                      "MiscCorLib.Security.Cryptography.SymmetricTransformer",
                      new ArgumentOutOfRangeException("initializationVector", message));
        }
Exemple #4
0
        /// <summary>
        /// Determines if the specified key is a valid size for the specified algorithm.
        /// </summary>
        /// <param name="key">The key string to be evaluated.</param>
        /// <param name="algorithm">The EncryptionAlgorithm to valid the key.</param>
        /// <param name="message">An output value of the valid sizes for the specified algorithm.</param>
        /// <returns>True if the key is a valid size; otherwise false.</returns>
        public static bool IsValidKeySize(string key, EncryptionAlgorithm algorithm, out string message)
        {
            SymmetricAlgorithm crypto = GetCryptoServiceProvider(algorithm);

            if (crypto != null)
            {
                byte[]        keyBytes  = Encoding.ASCII.GetBytes(key);
                int           bitLength = keyBytes.Length * 8;
                StringBuilder sb        = new StringBuilder();
                sb.AppendFormat("The size of your key is {0} byte(s).\n", keyBytes.Length);
                foreach (KeySizes sizes in crypto.LegalKeySizes)
                {
                    int min  = (sizes.MinSize / 8);
                    int max  = (sizes.MaxSize / 8);
                    int skip = (sizes.SkipSize / 8);
                    sb.AppendFormat("The minimum key size acceptable is {0} byte(s), the maximum key size " +
                                    "acceptable is {1} byte(s) and the key must be created in increments of {2} byte(s).\n",
                                    min, max, skip);
                }
                message = sb.ToString();
                return(crypto.ValidKeySize(bitLength));
            }
            message = String.Empty;
            return(false);
        }
Exemple #5
0
        /// <summary>
        /// 对字符串进行对称加密
        /// </summary>
        public static string SymmetricEncrypt(string inputString, SymmetricFormat symmetricFormat, string key, string iv)
        {
            SymmetricAlgorithm algorithm = GetSymmetricAlgorithm(symmetricFormat);

            byte[] desString = Encoding.UTF8.GetBytes(inputString);

            byte[] desKey = Encoding.ASCII.GetBytes(key);

            byte[] desIV = Encoding.ASCII.GetBytes(iv);

            if (!algorithm.ValidKeySize(desKey.Length * 8))
            {
                throw new ArgumentOutOfRangeException("key");
            }

            if (algorithm.IV.Length != desIV.Length)
            {
                throw new ArgumentOutOfRangeException("iv");
            }

            MemoryStream mStream = new MemoryStream();

            CryptoStream cStream = new CryptoStream(mStream, algorithm.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

            cStream.Write(desString, 0, desString.Length);

            cStream.FlushFinalBlock();

            cStream.Close();

            return(Convert.ToBase64String(mStream.ToArray()));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="V2CryptoBase" /> class.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="iv">The iv, or null for none.</param>
        /// <param name="keyStreamOffset">The key stream offset.</param>
        /// <exception cref="System.ArgumentNullException">factory
        /// or
        /// key
        /// or
        /// iv</exception>
        /// <exception cref="System.ArgumentException">Key length is invalid.
        /// or
        /// The IV length must be the same as the algorithm block length.</exception>
        protected void Initialize(SymmetricKey key, SymmetricIV iv, long keyStreamOffset, SymmetricAlgorithm algorithm)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (algorithm == null)
            {
                throw new ArgumentNullException("algorithm");
            }

            if (!algorithm.ValidKeySize(key.Size))
            {
                throw new ArgumentException("Key length is invalid.");
            }
            iv = iv ?? new SymmetricIV(new byte[algorithm.BlockSize / 8]);
            if (iv.Length != algorithm.BlockSize / 8)
            {
                throw new ArgumentException("The IV length must be the same as the algorithm block length.");
            }

            Key           = key;
            _iv           = iv;
            _blockCounter = keyStreamOffset / iv.Length;
            _blockOffset  = (int)(keyStreamOffset % iv.Length);
        }
Exemple #7
0
 /// <summary>
 /// Controlla correttezza formale chiave
 /// </summary>
 /// <param name="algorithm"></param>
 /// <param name="key"></param>
 private static void checkAlgoKey(SymmetricAlgorithm algorithm, byte[] key)
 {
     if (!algorithm.ValidKeySize(key.Length * 8))
     {
         throw new ArgumentException(string.Format("La lunghezza della chiave fornita ({0} Bytes / {1} bits) non risulta compatibile con l'algoritmo selezionato {2}. Lunghezze supportate: Min-> {3} bits, Max-> {4} bits", key.Length, key.Length * 8, algorithm.GetType().Name, algorithm.LegalKeySizes[0].MinSize, algorithm.LegalKeySizes[0].MaxSize));
     }
 }
Exemple #8
0
 /// <summary>
 /// Create class and create a new key for the passed algorithm with a fixed keysize.
 /// </summary>
 /// <param name="Algorithm">new algorithm</param>
 /// <param name="KeySize">Keysize in bits(8 bits = 1 byte)</param>
 /// <param name="Password">Password, used to generate key</param>
 /// <param name="Salt">Salt, used to make generated key more random(min 8 characters)</param>
 /// <param name="Iterations">Rounds PBKDF2 will make to genarete a key</param>
 public Encryption(SymmetricAlgorithm Algorithm, int KeySize, string Password, string Salt, int Iterations = 10000)
 {
     _Algorithm = Algorithm ?? throw new ArgumentException("Invalid algorithm, algorithm is null.");
     if (!_Algorithm.ValidKeySize(KeySize))
     {
         throw new ArgumentException("Invalid key, key has an invalid size.");
     }
     Algorithm.Key = CreateKey(KeySize, Password, Salt, Iterations);
 }
Exemple #9
0
 public static string GenerateKey(SymmetricAlgorithm algorithm, int keySize)
 {
     if (!algorithm.ValidKeySize(keySize))
     {
         throw new ArgumentException("Invalid key size");
     }
     algorithm.KeySize = keySize;
     algorithm.GenerateKey();
     return(Convert.ToBase64String(algorithm.Key));
 }
Exemple #10
0
        public void KeySize_WrongSize()
        {
            SymmetricAlgorithm algo = SymmetricAlgorithm.Create();
            int n = 0;

            while (algo.ValidKeySize(++n))
            {
                ;
            }
            algo.KeySize = n;
        }
Exemple #11
0
 // Find a valid key size for this algorithm.
 private static int FindKeySize(SymmetricAlgorithm algorithm)
 {
     for (int i = 1024; i > 1; i--)
     {
         if (algorithm.ValidKeySize(i))
         {
             return(i);
         }
     }
     throw new InvalidOperationException(
               $"Cannot find a valid key size for {algorithm.GetType().Name}.");
 }
Exemple #12
0
        public SymmetricEncryptionResult Encrypt(string messageToEncrypt, int symmetricKeyLengthBits,
                                                 SymmetricAlgorithm algorithm)
        {
            SymmetricEncryptionResult encryptionResult = new SymmetricEncryptionResult();

            try
            {
                //first test if bit length is valid
                if (algorithm.ValidKeySize(symmetricKeyLengthBits))
                {
                    algorithm.KeySize = symmetricKeyLengthBits;
                    using (MemoryStream mem = new MemoryStream())
                    {
                        CryptoStream crypto         = new CryptoStream(mem, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
                        byte[]       bytesToEncrypt = Encoding.UTF8.GetBytes(messageToEncrypt);
                        crypto.Write(bytesToEncrypt, 0, bytesToEncrypt.Length);
                        crypto.FlushFinalBlock();
                        byte[] encryptedBytes       = mem.ToArray();
                        string encryptedBytesBase64 = Convert.ToBase64String(encryptedBytes);
                        encryptionResult.Success      = true;
                        encryptionResult.Cipher       = encryptedBytes;
                        encryptionResult.CipherBase64 = encryptedBytesBase64;
                        encryptionResult.IV           = algorithm.IV;
                        encryptionResult.SymmetricKey = algorithm.Key;
                    }
                }
                else
                {
                    string        NL = Environment.NewLine;
                    StringBuilder exceptionMessageBuilder = new StringBuilder();
                    exceptionMessageBuilder.Append("The provided key size - ")
                    .Append(symmetricKeyLengthBits).Append(" bits - is not valid for this algorithm.");
                    exceptionMessageBuilder.Append(NL)
                    .Append("Valid key sizes: ").Append(NL);
                    KeySizes[] validKeySizes = algorithm.LegalKeySizes;
                    foreach (KeySizes keySizes in validKeySizes)
                    {
                        exceptionMessageBuilder.Append("Min: ")
                        .Append(keySizes.MinSize).Append(NL)
                        .Append("Max: ").Append(keySizes.MaxSize).Append(NL)
                        .Append("Step: ").Append(keySizes.SkipSize);
                    }
                    throw new CryptographicException(exceptionMessageBuilder.ToString());
                }
            }
            catch (Exception ex)
            {
                encryptionResult.Success          = false;
                encryptionResult.ExceptionMessage = ex.Message;
            }

            return(encryptionResult);
        }
Exemple #13
0
 /// <summary>
 /// Create class with an algorithm and overide the key for the selected algorithm.
 /// </summary>
 /// <param name="Algorithm">New algorithm</param>
 /// <param name="Key">Generated key</param>
 public Encryption(SymmetricAlgorithm Algorithm, byte[] Key)
 {
     _Algorithm = Algorithm ?? throw new ArgumentException("Invalid algorithm, algorithm is null.");
     if (Key == null)
     {
         throw new ArgumentException("Invalid key, key is null.");
     }
     if (!_Algorithm.ValidKeySize(Key.Length * 8))
     {
         throw new ArgumentException("Invalid key, key has an invalid size.");
     }
     _Algorithm.Key = Key;
 }
Exemple #14
0
        private Tuple <byte[], byte[]> GetStartingKeyAndIVForEncryption(SymmetricAlgorithm algorithm)
        {
            int bits = algorithm.ValidKeySize(EncryptionSettings.PreferedEncryptionKeyBitsSize) ?
                       EncryptionSettings.PreferedEncryptionKeyBitsSize :
                       algorithm.LegalKeySizes[0].MaxSize;

            encryptionKeySize = bits / 8;
            encryptionIVSize  = algorithm.IV.Length;

            var deriveBytes = new Rfc2898DeriveBytes(EncryptionSettings.EncryptionKey, GetSaltFromEncryptionKey(EncryptionSettings.EncryptionKey), Constants.Rfc2898Iterations);

            return(Tuple.Create(deriveBytes.GetBytes(encryptionKeySize.Value), deriveBytes.GetBytes(encryptionIVSize.Value)));
        }
Exemple #15
0
        /// <summary>
        /// permite generar llaves de seguridad
        /// </summary>
        /// <param name="algorithm">define el algoritmo</param>
        /// <param name="keySize">tamaño del algoritmo</param>
        /// <returns></returns>
        public static string GenerateKey(SymmetricAlgorithm algorithm, int keySize)
        {
            if (algorithm.ValidKeySize(keySize))
            {
                algorithm.KeySize = keySize;
                algorithm.GenerateKey();

                return(Convert.ToBase64String(algorithm.Key));
            }
            else
            {
                throw new ArgumentException("Tamaño de Llave Invalido");
            }
        }
Exemple #16
0
        /// <summary>
        ///     Generate symmetric key for encryption and decryption.
        /// </summary>
        /// <param name="keySize">Key size.</param>
        /// <returns>Key byte array.</returns>
        public virtual byte[] GenerateKey(int keySize)
        {
            if (!_symmetricAlgorithm.ValidKeySize(keySize))
            {
                throw new CryptographicException("Invalid key size for this algorithm.");
            }

            _symmetricAlgorithm.Clear();

            _symmetricAlgorithm.KeySize = keySize;
            _symmetricAlgorithm.GenerateKey();

            return(_symmetricAlgorithm.Key);
        }
Exemple #17
0
 /// <summary>
 /// </summary>
 /// <param name="algorithm">algorithm used for encryption, Aes if null</param>
 /// <param name="key">key used for encryption, secure random if null</param>
 /// <exception cref="ArgumentException">can't create EasyEncrypt: key is invalid</exception>
 public EasyEncrypt(SymmetricAlgorithm algorithm = null, byte[] key = null)
 {
     Algorithm = algorithm ?? Aes.Create();
     if (key == null)
     {
         Algorithm.GenerateKey();
     }
     else if (Algorithm.ValidKeySize(key.Length * 8))
     {
         Algorithm.Key = key;
     }
     else
     {
         throw new ArgumentException("Can't create EasyEncrypt: key is invalid");
     }
 }
Exemple #18
0
        public static string GenerarKey(string tipoAlgoritmo, int keySize)
        {
            SymmetricAlgorithm mCSP = elegirAlgoritmo(tipoAlgoritmo);

            if (mCSP.ValidKeySize(keySize))
            {
                mCSP.KeySize = keySize;
                mCSP.GenerateKey();

                return(Convert.ToBase64String(mCSP.Key));
            }
            else
            {
                throw new ArgumentException("Tamaño inválido de la clave");
            }
        }
Exemple #19
0
        private static SymmetricAlgorithm InitSymmetric(SymmetricAlgorithm algorithm, string password, int keyBitLength)
        {
            var salt = new byte[] { 1, 2, 23, 234, 37, 48, 134, 63, 248, 4 };

            const int iterations = 234;

            using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, iterations))
            {
                if (!algorithm.ValidKeySize(keyBitLength))
                {
                    throw new InvalidOperationException("Invalid size key");
                }

                algorithm.Key = rfc2898DeriveBytes.GetBytes(keyBitLength / 8);
                algorithm.IV  = rfc2898DeriveBytes.GetBytes(algorithm.BlockSize / 8);
                return(algorithm);
            }
        }
Exemple #20
0
 private bool IsKeySizeValid(int size)
 {
     return(myCSP.ValidKeySize(size));
 }
 public bool ValidKeySize(int bitLength)
 {
     return(_algo.ValidKeySize(bitLength));
 }