Example #1
1
        // Decrypt a byte array into a byte array using a key and an IV
        public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV, CipherMode cipherMode, PaddingMode paddingMode)
        {
            // Create a MemoryStream that is going to accept the
            // decrypted bytes
            MemoryStream ms = new MemoryStream();

            // Create a symmetric algorithm.
            // We are going to use Rijndael because it is strong and
            // available on all platforms.
            // You can use other algorithms, to do so substitute the next
            // line with something like
            //     TripleDES alg = TripleDES.Create();

            Rijndael alg = Rijndael.Create();

            // Now set the key and the IV.
            // We need the IV (Initialization Vector) because the algorithm
            // is operating in its default
            // mode called CBC (Cipher Block Chaining). The IV is XORed with
            // the first block (8 byte)
            // of the data after it is decrypted, and then each decrypted
            // block is XORed with the previous
            // cipher block. This is done to make encryption more secure.
            // There is also a mode called ECB which does not need an IV,
            // but it is much less secure.

            alg.Mode = cipherMode;
            alg.Padding = paddingMode;
            alg.Key = Key;
            alg.IV = IV;

            // Create a CryptoStream through which we are going to be
            // pumping our data.
            // CryptoStreamMode.Write means that we are going to be
            // writing data to the stream
            // and the output will be written in the MemoryStream
            // we have provided.

            CryptoStream cs = new CryptoStream(ms,
                alg.CreateDecryptor(), CryptoStreamMode.Write);

            // Write the data and make it do the decryption
            cs.Write(cipherData, 0, cipherData.Length);

            // Close the crypto stream (or do FlushFinalBlock).
            // This will tell it that we have done our decryption
            // and there is no more data coming in,
            // and it is now a good time to remove the padding
            // and finalize the decryption process.

            cs.Close();

            // Now get the decrypted data from the MemoryStream.
            // Some people make a mistake of using GetBuffer() here,
            // which is not the right way.

            byte[] decryptedData = ms.ToArray();

            return decryptedData;
        }
        [System.Security.SecurityCritical]  // auto-generated
        private ICryptoTransform _NewEncryptor (byte[] rgbKey, CipherMode mode, byte[] rgbIV, int feedbackSize, CryptoAPITransformMode encryptMode) {
            int cArgs = 0;
            int[] rgArgIds = new int[10];
            Object[] rgArgValues = new Object[10];

            // Check for bad values
            // 1) we don't support OFB mode in DESCryptoServiceProvider
            if (mode == CipherMode.OFB)
                throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_OFBNotSupported"));
            // 2) we only support CFB with a feedback size of 8 bits
            if ((mode == CipherMode.CFB) && (feedbackSize != 8)) 
                throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_CFBSizeNotSupported"));

            // Build the key if one does not already exist
            if (rgbKey == null) {
                rgbKey = new byte[8];
                Utils.StaticRandomNumberGenerator.GetBytes(rgbKey);
            }

            // Set the mode for the encryptor (defaults to CBC)
            if (mode != CipherMode.CBC) {
                rgArgIds[cArgs] = Constants.KP_MODE;
                rgArgValues[cArgs] = mode;
                cArgs += 1;
            }

            // If not ECB mode -- pass in an IV
            if (mode != CipherMode.ECB) {
                if (rgbIV == null) {
                    rgbIV = new byte[8];
                    Utils.StaticRandomNumberGenerator.GetBytes(rgbIV);
                }

                //
                // We truncate IV's that are longer than the block size to 8 bytes : this is
                // done to maintain backward compatibility with the behavior shipped in V1.x.
                // The call to set the IV in CryptoAPI will ignore any bytes after the first 8
                // bytes. We'll still reject IV's that are shorter than the block size though.
                //
                if (rgbIV.Length < 8)
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidIVSize"));

                rgArgIds[cArgs] = Constants.KP_IV;
                rgArgValues[cArgs] = rgbIV;
                cArgs += 1;
            }

            // If doing OFB or CFB, then we need to set the feed back loop size
            if ((mode == CipherMode.OFB) || (mode == CipherMode.CFB)) {
                rgArgIds[cArgs] = Constants.KP_MODE_BITS;
                rgArgValues[cArgs] = feedbackSize;
                cArgs += 1;
            }

            // Create the encryptpr/decryptor object
            return new CryptoAPITransform(Constants.CALG_DES, cArgs, rgArgIds, 
                                          rgArgValues, rgbKey, PaddingValue,
                                          mode, BlockSizeValue, feedbackSize, false,
                                          encryptMode);
        }
 public static byte[] EncriptarDeImagen(byte[] bytEncriptar, string strPK, CipherMode cMode)
 {
     Rijndael rijndael = Rijndael.Create();
     byte[] buffer = null;
     byte[] array = null;
     try
     {
         rijndael.Key = new PasswordDeriveBytes(strPK, null).GetBytes(0x20);
         rijndael.Mode = cMode;
         byte[] destinationArray = new byte[bytEncriptar.Length - 0x22];
         Array.Copy(bytEncriptar, 0x22, destinationArray, 0, bytEncriptar.Length - 0x22);
         buffer = rijndael.CreateEncryptor().TransformFinalBlock(destinationArray, 0, destinationArray.Length);
         array = new byte[0x22 + buffer.Length];
         bytEncriptar.CopyTo(array, 0);
         buffer.CopyTo(array, 0x22);
     }
     catch
     {
     }
     finally
     {
         rijndael.Clear();
     }
     return array;
 }
Example #4
0
        public static byte[] EncriptarDeImagen(byte[] bytEncriptar, string strPK, CipherMode cMode)
        {
            Rijndael miRijndael = Rijndael.Create();
            byte[] encrypted = null;
            byte[] returnValue = null;

            try
            {
                miRijndael.Key =  (new PasswordDeriveBytes(strPK, null)).GetBytes(32);
                miRijndael.Mode = cMode;

                byte[] toEncrypt = new byte[bytEncriptar.Length-34];
                Array.Copy(bytEncriptar, 34, toEncrypt, 0, bytEncriptar.Length-34);
                encrypted = (miRijndael.CreateEncryptor()).TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);

                returnValue = new byte[34 + encrypted.Length];
                bytEncriptar.CopyTo(returnValue, 0);
                encrypted.CopyTo(returnValue, 34);

            }
            catch { }
            finally { miRijndael.Clear(); }

            return returnValue;
        }
		public static byte[] Decrypt(byte[] value, byte[] key, byte[] iv, CipherMode mode = CipherMode.CBC, PaddingMode padding = PaddingMode.None)
		{
			if (value == null || value.Length <= 0)
				throw new ArgumentNullException("value");
			if (key == null || key.Length <= 0)
				throw new ArgumentNullException("key");
			if (iv == null || iv.Length <= 0)
				throw new ArgumentNullException("iv");

			byte[] result;
			using (RijndaelManaged rijndael = new RijndaelManaged())
			{
				rijndael.Key = key;
				rijndael.IV = iv;
				rijndael.Mode = mode;
				rijndael.Padding = padding;

				ICryptoTransform transform = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV);
				using (MemoryStream memory = new MemoryStream())
				using (CryptoStream crypto = new CryptoStream(memory, transform, CryptoStreamMode.Read))
				{
					crypto.Write(value, 0, value.Length);
					result = memory.ToArray();
				}
			}

			return result;
		}
        private Native.SafeCipherHandle GetCipher(CipherMode mode, int keyLength)
        {
            if (mode == CipherMode.CBC) {
                switch (keyLength) {
                case 16:
                    return Native.EVP_aes_128_cbc ();

                case 24:
                    return Native.EVP_aes_192_cbc ();

                case 32:
                    return Native.EVP_aes_256_cbc ();
                }
            } else if (mode == CipherMode.ECB) {
                switch (keyLength) {
                case 16:
                    return Native.EVP_aes_128_ecb ();

                case 24:
                    return Native.EVP_aes_192_ecb ();

                case 32:
                    return Native.EVP_aes_256_ecb ();
                }
            }

            throw new CryptographicException (string.Format ("{0} not supported", mode));
        }
Example #7
0
		public static string DecryptMessage(string message, byte[] key, CipherMode mode)
		{
			var cipherBytes = CipherHelper.ConvertFromHexString(message).ToArray<byte>();
			// first 16 bytes of cipher text is IV
			var IV = cipherBytes.Take<byte>(blockSize).ToArray<byte>();
			cipherBytes = cipherBytes.Skip<byte>(blockSize).ToArray<byte>();

			var textBytes = new byte[cipherBytes.Length];

			using (var aesAlg = Aes.Create())
			{
				aesAlg.Mode = mode;
				aesAlg.KeySize = keySize;
				aesAlg.Padding = PaddingMode.PKCS7;
				using(ICryptoTransform decryptor = aesAlg.CreateDecryptor(key, IV))
				{
					using(MemoryStream memStream = new MemoryStream(cipherBytes))
					{
						using(CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
						{
							using (var reader = new BinaryReader(cryptoStream))
							{
								textBytes = reader.ReadBytes(cipherBytes.Length);
							}
						}
					}
				}
			}

			return CipherHelper.GetASCIIString(textBytes);
		}
Example #8
0
        public TripleDesOpenSslCipher(CipherMode cipherMode, int blockSizeInBytes, byte[] key, byte[] iv, bool encrypting)
            : base(cipherMode.GetCipherIv(iv), blockSizeInBytes)
        {
            _encrypting = encrypting;

            OpenKey(cipherMode, key);
        }
Example #9
0
        private ICryptoTransform NewEncryptor (byte[] rgbKey,
                                               CipherMode mode,
                                               byte[] rgbIV,
                                               int feedbackSize,
                                               RijndaelManagedTransformMode encryptMode) {
            // Build the key if one does not already exist
            if (rgbKey == null) {
                rgbKey = Utils.GenerateRandom(KeySizeValue / 8);
            }

            // If not ECB mode, make sure we have an IV. In CoreCLR we do not support ECB, so we must have
            // an IV in all cases.
#if !FEATURE_CRYPTO
            if (mode != CipherMode.ECB) {
#endif // !FEATURE_CRYPTO
                if (rgbIV == null) {
                    rgbIV = Utils.GenerateRandom(BlockSizeValue / 8);
                }
#if !FEATURE_CRYPTO
            }
#endif // !FEATURE_CRYPTO

            // Create the encryptor/decryptor object
            return new RijndaelManagedTransform (rgbKey,
                                                 mode,
                                                 rgbIV,
                                                 BlockSizeValue,
                                                 feedbackSize,
                                                 PaddingValue,
                                                 encryptMode);
        }
Example #10
0
        private static ICryptoTransform CreateTransformCore(
            CipherMode cipherMode,
            PaddingMode paddingMode,
            byte[] key,
            byte[] iv,
            int blockSize,
            bool encrypting)
        {
            // The algorithm pointer is a static pointer, so not having any cleanup code is correct.
            IntPtr algorithm;
            switch (cipherMode)
            {
                case CipherMode.CBC:
                    algorithm = Interop.Crypto.EvpDesCbc();
                    break;
                case CipherMode.ECB:
                    algorithm = Interop.Crypto.EvpDesEcb();
                    break;
                default:
                    throw new NotSupportedException();
            }

            BasicSymmetricCipher cipher = new OpenSslCipher(algorithm, cipherMode, blockSize, key, 0, iv, encrypting);
            return UniversalCryptoTransform.Create(paddingMode, cipher, encrypting);
        }
Example #11
0
 public static string Decrypt(string cipherText, string Password, CipherMode cipherMode, PaddingMode paddingMode)
 {
     byte[] cipherData = Convert.FromBase64String(cipherText);
     PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 110, 0x20, 0x4d, 0x65, 100, 0x76, 0x65, 100, 0x65, 0x76 });
     byte[] buffer2 = Decrypt(cipherData, bytes.GetBytes(0x20), bytes.GetBytes(0x10), cipherMode, paddingMode);
     return Encoding.Unicode.GetString(buffer2);
 }
Example #12
0
        private void buttonGenerator_Click(object sender, EventArgs e)
        {
            try
            {
                // Selected 'Preset'
                if (tabControl.SelectedIndex == 0)
                {
                    CurrentBlockSize = comboBoxPresets.SelectedIndex == 0 ? 128 : 256;
                    CurrentKeySize = comboBoxPresets.SelectedIndex == 0 ? 128 : 256;
                    SelectedCipher = CipherMode.CBC;
                    SelectedPadding = PaddingMode.PKCS7;
                }

                int index = tabControl.SelectedIndex;
                if ((index == 0 && comboBoxPresets.SelectedIndex == 1) ||
                    (index == 1 && radioButtonAes.Checked))
                    Build(new RijndaelManaged());
                else
                    Build(new AesManaged());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #13
0
	public static bool TestAlgorithms(SymmetricAlgorithm encAlgorithm, SymmetricAlgorithm decAlgorithm, CipherMode[] modes, int maxLength, int iterations)
	{
		Random rand = new Random();
		
		for (int i = 0; i < iterations; i++)
		{
			// Create random data, key, IV, mode
			//
			byte[] key = new byte[KeySizeBytes[rand.Next(KeySizeBytes.Length)]];
			rand.NextBytes(key);
			
			byte[] data = new byte[rand.Next(1, maxLength + 1)];
			rand.NextBytes(data);

			byte[] IV = new byte[BlockSizeBytes];
			rand.NextBytes(IV);
			
			CipherMode mode = modes[rand.Next(modes.Length)];
			PaddingMode padding = PaddingModes[new Random().Next(PaddingModes.Length)];

			// Encrypt the data
			//
			byte[] encryptedData;
			encAlgorithm.Key = key;
			encAlgorithm.IV = IV;
			encAlgorithm.Mode = mode;
			encAlgorithm.Padding = padding;

			ICryptoTransform transform = encAlgorithm.CreateEncryptor();
			encryptedData = transform.TransformFinalBlock(data, 0, data.Length);

			// Decrypt the data
			//
			byte[] decryptedData;
			decAlgorithm.Key = key;
			decAlgorithm.IV = IV;
			decAlgorithm.Mode = mode;
			decAlgorithm.Padding = padding;

			transform = decAlgorithm.CreateDecryptor();
			decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

			if (!CompareBytes(data, decryptedData))
			{
				Console.WriteLine("ERROR - roundtrip encrypt/decrypt failed!\n");
				Console.WriteLine("Encryption algorithm: {0}", encAlgorithm.ToString());
				Console.WriteLine("Decryption algorithm: {0}", decAlgorithm.ToString());
				Console.WriteLine("Original data: {0}", ByteArrayToString(data));
				Console.WriteLine("Roundtrip data: {0}", ByteArrayToString(decryptedData));
				Console.WriteLine("Key: {0}", ByteArrayToString(key));
				Console.WriteLine("IV: {0}", ByteArrayToString(IV));
				Console.WriteLine("Cipher mode: {0}", mode.ToString());
				Console.WriteLine("Padding mode: {0}", padding.ToString());
				return false;
			}
		}

		return true;
	}
 public CapiSymmetricAlgorithm(int blockSize, int feedbackSize, SafeCspHandle provider, SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, PaddingMode paddingMode, EncryptionMode encryptionMode)
 {
     this.m_blockSize = blockSize;
     this.m_encryptionMode = encryptionMode;
     this.m_paddingMode = paddingMode;
     this.m_provider = provider.Duplicate();
     this.m_key = SetupKey(key, ProcessIV(iv, blockSize, cipherMode), cipherMode, feedbackSize);
 }
 /// <summary>
 /// Initializes a new instance of the SymmetricAlgorithm class.
 /// </summary>
 /// <param name="session">The cryptoki session context for which the symmectric algorithm will execute.</param>
 /// <param name="ownsSession">true if the session should be closed by this base class, false otherwise.</param>
 protected SymmetricAlgorithm(Session session, bool ownsSession)
     : base(session, ownsSession)
 {
     // Default to cipher block chaining (CipherMode.CBC) and
     // PKCS-style padding (pad n bytes with value n)
     ModeValue = CipherMode.CBC;
     PaddingValue  = PaddingMode.PKCS7;
 }
Example #16
0
 /// <summary>
 /// Initialize new AES
 /// </summary>
 /// <param name="keySize">Optional key size. Default 128.</param>
 /// <param name="mode">Optional cipher mode. Default: CBC</param>
 public AES_THL(int keySize = 128, CipherMode mode = CipherMode.CBC)
 {
     this.keySize = keySize;
     this.mode = mode;
     aes = new AesCryptoServiceProvider();
     aes.Mode = mode;
     aes.KeySize = keySize;
 }
Example #17
0
 private static ICryptoTransform CreateEncryptor(
     CipherMode cipherMode,
     PaddingMode paddingMode,
     byte[] key,
     byte[] iv,
     int blockSize)
 {
     return new AesOpenSslCryptoTransform(cipherMode, paddingMode, key, iv, blockSize, true);
 }
 private static ICryptoTransform CreateDecryptor(
     CipherMode cipherMode,
     PaddingMode paddingMode,
     byte[] key,
     byte[] iv,
     int blockSize)
 {
     return new AesCngCryptoDecryptor(cipherMode, paddingMode, key, iv, blockSize);
 }
Example #19
0
        public OpenSslCipher(IntPtr algorithm, CipherMode cipherMode, int blockSizeInBytes, byte[] key, int effectiveKeyLength, byte[] iv, bool encrypting)
            : base(cipherMode.GetCipherIv(iv), blockSizeInBytes)
        {
            Debug.Assert(algorithm != IntPtr.Zero);

            _encrypting = encrypting;

            OpenKey(algorithm, key, effectiveKeyLength);
        }
Example #20
0
 public HwAes(Connection connection, byte[] Key, int KeySize, CipherMode cipherMode, PaddingMode padding)
 {
     this.AES = new AesCryptoServiceProvider();
     this.AES.Padding = padding;
     this.AES.Mode = cipherMode;
     this.AES.KeySize = KeySize;
     this.IvConfuser = new DataConfuser(connection.PrivateSeed, 16);
     ApplyKey(Key);
 }
        public TripleDesSymmetricKeyCryptoProvider(string base64EncodedKey, CipherMode cipherMode, PaddingMode paddingMode)
        {
            var tripleDes = TripleDES.Create();
            tripleDes.Mode = cipherMode;
            tripleDes.Padding = paddingMode;
            tripleDes.Key = Convert.FromBase64String(base64EncodedKey);

            _encrypt = tripleDes.CreateEncryptor();
            _decrypt = tripleDes.CreateDecryptor();
        }
Example #22
0
		/// <summary>
		/// Costruttore della classe per crittografare
		/// </summary>
		public Encryption(string strSalt = "")
			{
			keySize = 32;									// 32 caratteri (256 bit)
			blockSize = 32;									// 32 caratteri (256 bit)
			paddingMode = PaddingMode.PKCS7;				// Completa con numero progressivo
			cipherMode = CipherMode.CBC;					// Combina blocco precedente crittografato al successivo (contro blocchi identici)
			IVbase64size = IVbase64length();                // Imposta la lunghezza dell'IV in base64
			errors = new List<string>();                    // Lista dei messaggi di errore o altro
			SetSalt(strSalt);
			}
		/// <summary>
		/// Initializes a new instance of the RijndaelUnmanagedTransform class.
		/// </summary>
		/// <param name="algorithm">One of the <see cref="CryptoAlgorithm"/> values.</param>
		/// <param name="method">One of the <see cref="CryptoMethod"/> values.</param>
		/// <param name="key">The key to use.</param>
		/// <param name="iv">The IV to use.</param>
		/// <param name="mode">One of the <see cref="CipherMode"/> values.</param>
		/// <param name="feedback">The feedback size of the cryptographic operation in bits.</param>
		/// <param name="padding">One of the <see cref="PaddingMode"/> values.</param>
		public RijndaelUnmanagedTransform(CryptoAlgorithm algorithm, CryptoMethod method, byte[] key, byte[] iv, CipherMode mode, int feedback, PaddingMode padding) {
			m_Key = new SymmetricKey(CryptoProvider.RsaAes, algorithm, key);
			m_Key.IV = iv;
			m_Key.Mode = mode;
			if (mode == CipherMode.CFB)
				m_Key.FeedbackSize = feedback;
			m_Key.Padding = padding;
			m_BlockSize = 128;
			m_Method = method;
		}
 public EncryptedXml(XmlDocument document, Evidence evidence)
 {
     this.m_document = document;
     this.m_evidence = evidence;
     this.m_xmlResolver = null;
     this.m_padding = PaddingMode.ISO10126;
     this.m_mode = CipherMode.CBC;
     this.m_encoding = System.Text.Encoding.UTF8;
     this.m_keyNameMapping = new Hashtable(4);
 }
 public RijndaelParameters(RijndaelManaged rijndael)
 {
     BlockSize = rijndael.BlockSize;
     FeedbackSize = rijndael.FeedbackSize;
     KeySize = rijndael.KeySize;
     Mode = rijndael.Mode;
     Padding = rijndael.Padding;
     IV = rijndael.IV;
     Key = rijndael.Key;
 }
Example #26
0
		static double[] Run (SymmetricAlgorithm algo, CipherMode mode, int keySize, int blockSize, int dataSize)
		{
			double[] result = SpeedTest.Run (algo, mode, keySize, blockSize, dataSize);
			for (int i = 0; i < 10; i++) {
				double[] temp = SpeedTest.Run (algo, mode, keySize, blockSize, dataSize);
				result[0] = Math.Max (result[0], temp[0]);
				result[1] = Math.Max (result[1], temp[1]);
			}
			return result;
		}
 private ICryptoTransform CreateTransformCore(
     CipherMode cipherMode,
     PaddingMode paddingMode,
     byte[] key,
     byte[] iv,
     int blockSize,
     bool encrypting)
 {
     BasicSymmetricCipher cipher = new TripleDesCngCipher(cipherMode, blockSize, key, iv, encrypting);
     return UniversalCryptoTransform.Create(paddingMode, cipher, encrypting);
 }
 private ICryptoTransform NewEncryptor(byte[] rgbKey, CipherMode mode, byte[] rgbIV, int feedbackSize, RijndaelManagedTransformMode encryptMode)
 {
     if (rgbKey == null)
     {
         rgbKey = Utils.GenerateRandom(base.KeySizeValue / 8);
     }
     if (rgbIV == null)
     {
         rgbIV = Utils.GenerateRandom(base.BlockSizeValue / 8);
     }
     return new RijndaelManagedTransform(rgbKey, mode, rgbIV, base.BlockSizeValue, feedbackSize, base.PaddingValue, encryptMode);
 }
        internal static void VerifyPersistedKey(
            string keyName,
            int plainBytesCount,
            Func<string, SymmetricAlgorithm> persistedFunc,
            Func<SymmetricAlgorithm> ephemeralFunc,
            CipherMode cipherMode,
            PaddingMode paddingMode)
        {
            byte[] plainBytes = GenerateRandom(plainBytesCount);

            using (SymmetricAlgorithm persisted = persistedFunc(keyName))
            using (SymmetricAlgorithm ephemeral = ephemeralFunc())
            {
                persisted.Mode = ephemeral.Mode = cipherMode;
                persisted.Padding = ephemeral.Padding = paddingMode;

                ephemeral.Key = persisted.Key;
                ephemeral.GenerateIV();
                persisted.IV = ephemeral.IV;

                using (ICryptoTransform persistedEncryptor = persisted.CreateEncryptor())
                using (ICryptoTransform persistedDecryptor = persisted.CreateDecryptor())
                using (ICryptoTransform ephemeralEncryptor = ephemeral.CreateEncryptor())
                {
                    Assert.True(
                        persistedEncryptor.CanTransformMultipleBlocks,
                        "Pre-condition: persistedEncryptor.CanTransformMultipleBlocks");

                    byte[] persistedEncrypted = persistedEncryptor.TransformFinalBlock(plainBytes, 0, plainBytesCount);
                    byte[] ephemeralEncrypted = ephemeralEncryptor.TransformFinalBlock(plainBytes, 0, plainBytesCount);

                    Assert.Equal(ephemeralEncrypted, persistedEncrypted);

                    byte[] cipherBytes = persistedEncrypted;
                    byte[] persistedDecrypted = persistedDecryptor.TransformFinalBlock(cipherBytes, 0,
                        cipherBytes.Length);

                    byte[] expectedBytes = plainBytes;

                    if (persistedDecrypted.Length > plainBytes.Length)
                    {
                        // This should only ever happen in 
                        Assert.Equal(PaddingMode.Zeros, paddingMode);

                        expectedBytes = new byte[persistedDecrypted.Length];
                        Buffer.BlockCopy(plainBytes, 0, expectedBytes, 0, plainBytesCount);
                    }

                    Assert.Equal(expectedBytes, persistedDecrypted);
                }
            }
        }
 private ICryptoTransform _NewEncryptor(byte[] rgbKey, CipherMode mode, byte[] rgbIV, int feedbackSize, CryptoAPITransformMode encryptMode)
 {
     int index = 0;
     int[] rgArgIds = new int[10];
     object[] rgArgValues = new object[10];
     int algid = 0x6603;
     if (mode == CipherMode.OFB)
     {
         throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_OFBNotSupported"));
     }
     if ((mode == CipherMode.CFB) && (feedbackSize != 8))
     {
         throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_CFBSizeNotSupported"));
     }
     if (rgbKey == null)
     {
         rgbKey = new byte[base.KeySizeValue / 8];
         Utils.StaticRandomNumberGenerator.GetBytes(rgbKey);
     }
     if (mode != CipherMode.CBC)
     {
         rgArgIds[index] = 4;
         rgArgValues[index] = mode;
         index++;
     }
     if (mode != CipherMode.ECB)
     {
         if (rgbIV == null)
         {
             rgbIV = new byte[8];
             Utils.StaticRandomNumberGenerator.GetBytes(rgbIV);
         }
         if (rgbIV.Length < 8)
         {
             throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidIVSize"));
         }
         rgArgIds[index] = 1;
         rgArgValues[index] = rgbIV;
         index++;
     }
     if ((mode == CipherMode.OFB) || (mode == CipherMode.CFB))
     {
         rgArgIds[index] = 5;
         rgArgValues[index] = feedbackSize;
         index++;
     }
     if (rgbKey.Length == 0x10)
     {
         algid = 0x6609;
     }
     return new CryptoAPITransform(algid, index, rgArgIds, rgArgValues, rgbKey, base.PaddingValue, mode, base.BlockSizeValue, feedbackSize, false, encryptMode);
 }
Example #31
0
        private static string EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV, CipherMode mode, PaddingMode padding)
        {
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            byte[] encrypted;

            using (RijndaelManaged aesAlg = new RijndaelManaged())
            {
                aesAlg.KeySize   = 256;
                aesAlg.BlockSize = 128;
                aesAlg.Key       = Key;
                aesAlg.IV        = IV;
                aesAlg.Mode      = mode;
                aesAlg.Padding   = padding;

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt =
                               new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            return(Convert.ToBase64String(encrypted));
        }
Example #32
0
        private static byte[] Decrypt(byte[] cyphertext, SymmetricAlgorithm sa, byte[] key, byte[] iv, CipherMode mode,
                                      PaddingMode padding)
        {
            sa.Key     = key;
            sa.IV      = iv;
            sa.Mode    = mode;
            sa.Padding = padding;
            MemoryStream ms = new MemoryStream(cyphertext);
            CryptoStream cs = new CryptoStream(ms, sa.CreateDecryptor(), CryptoStreamMode.Read);

            byte[] buffer    = new byte[cyphertext.Length];
            int    readCount = cs.Read(buffer, 0, cyphertext.Length);

            byte[] result = new byte[readCount];
            Array.Copy(buffer, result, readCount);
            cs.Close();
            ms.Close();
            return(result);
        }
Example #33
0
        [System.Security.SecurityCritical]  // auto-generated
        private ICryptoTransform _NewEncryptor(byte[] rgbKey, CipherMode mode, byte[] rgbIV,
                                               int effectiveKeySize, int feedbackSize, CryptoAPITransformMode encryptMode)
        {
            int cArgs = 0;

            int[]    rgArgIds    = new int[10];
            Object[] rgArgValues = new Object[10];

            // Check for bad values
            // 1) we don't support OFB mode in RC2_CSP
            if (mode == CipherMode.OFB)
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_OFBNotSupported"));
            }
            // 2) we only support CFB with a feedback size of 8 bits
            if ((mode == CipherMode.CFB) && (feedbackSize != 8))
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_CFBSizeNotSupported"));
            }

            if (rgbKey == null)
            {
                rgbKey = new byte[KeySizeValue / 8];
                Utils.StaticRandomNumberGenerator.GetBytes(rgbKey);
            }

            // Check the rgbKey size
            int keySizeValue = rgbKey.Length * 8;

            if (!ValidKeySize(keySizeValue))
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
            }

            // Deal with effective key length questions
            rgArgIds[cArgs] = Constants.KP_EFFECTIVE_KEYLEN;
            if (EffectiveKeySizeValue == 0)
            {
                rgArgValues[cArgs] = keySizeValue;
            }
            else
            {
                rgArgValues[cArgs] = effectiveKeySize;
            }
            cArgs += 1;

            // Set the mode for the encryptor (defaults to CBC)
            if (mode != CipherMode.CBC)
            {
                rgArgIds[cArgs]    = Constants.KP_MODE;
                rgArgValues[cArgs] = mode;
                cArgs += 1;
            }

            // If not ECB mode -- pass in an IV
            if (mode != CipherMode.ECB)
            {
                if (rgbIV == null)
                {
                    rgbIV = new byte[8];
                    Utils.StaticRandomNumberGenerator.GetBytes(rgbIV);
                }

                //
                // We truncate IV's that are longer than the block size to 8 bytes : this is
                // done to maintain backward compatibility with the behavior shipped in V1.x.
                // The call to set the IV in CryptoAPI will ignore any bytes after the first 8
                // bytes. We'll still reject IV's that are shorter than the block size though.
                //
                if (rgbIV.Length < 8)
                {
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidIVSize"));
                }

                rgArgIds[cArgs]    = Constants.KP_IV;
                rgArgValues[cArgs] = rgbIV;
                cArgs += 1;
            }

            // If doing OFB or CFB, then we need to set the feed back loop size
            if ((mode == CipherMode.OFB) || (mode == CipherMode.CFB))
            {
                rgArgIds[cArgs]    = Constants.KP_MODE_BITS;
                rgArgValues[cArgs] = feedbackSize;
                cArgs += 1;
            }

            if (!Utils.HasAlgorithm(Constants.CALG_RC2, keySizeValue))
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_AlgKeySizeNotAvailable", keySizeValue));
            }

            //  Create the encryptor/decryptor object
            return(new CryptoAPITransform(Constants.CALG_RC2, cArgs, rgArgIds,
                                          rgArgValues, rgbKey, PaddingValue,
                                          mode, BlockSizeValue, feedbackSize, m_use40bitSalt,
                                          encryptMode));
        }
Example #34
0
    // Run a cipher mode test.
    private void RunModeTest(SymmetricAlgorithm alg, CipherMode mode,
                             PaddingMode padding, String input)
    {
        // Set the algorithm modes.
        alg.Mode    = mode;
        alg.Padding = padding;

        // Get the raw and padded versions of the input.
        byte[] rawInput    = Encoding.ASCII.GetBytes(input);
        byte[] paddedInput = StringToBytes(input, alg);

        // Generate key and IV values.
        byte[] key = CreateKey(alg);
        byte[] iv  = CreateIV(alg);

        // Encrypt the raw input in the selected mode.
        int size   = alg.BlockSize / 8;
        int cutoff = rawInput.Length - rawInput.Length % size;
        ICryptoTransform encryptor;

        encryptor = alg.CreateEncryptor(key, iv);
        Assert(GetError("encryptor cannot transform multiple blocks",
                        alg, input),
               encryptor.CanTransformMultipleBlocks);
        if (mode == CipherMode.ECB || mode == CipherMode.CBC)
        {
            AssertEquals(GetError("encryptor has wrong input size",
                                  alg, input),
                         size, encryptor.InputBlockSize);
            AssertEquals(GetError("encryptor has wrong output size",
                                  alg, input),
                         size, encryptor.OutputBlockSize);
        }
        else
        {
            AssertEquals(GetError("encryptor has wrong input size",
                                  alg, input),
                         1, encryptor.InputBlockSize);
            AssertEquals(GetError("encryptor has wrong output size",
                                  alg, input),
                         1, encryptor.OutputBlockSize);
        }
        byte[] rawOutput = new byte [rawInput.Length + 256];
        int    len       = encryptor.TransformBlock
                               (rawInput, 0, cutoff, rawOutput, 0);

        byte[] rawTail = encryptor.TransformFinalBlock
                             (rawInput, cutoff, rawInput.Length - cutoff);
        Array.Copy(rawTail, 0, rawOutput, len, rawTail.Length);
        len += rawTail.Length;
        ((IDisposable)encryptor).Dispose();

        // Reverse the ciphertext back to the original.
        cutoff = len - len % size;
        ICryptoTransform decryptor;

        decryptor = alg.CreateDecryptor(key, iv);
        Assert(GetError("decryptor cannot transform multiple blocks",
                        alg, input),
               decryptor.CanTransformMultipleBlocks);
        if (mode == CipherMode.ECB || mode == CipherMode.CBC)
        {
            AssertEquals(GetError("decryptor has wrong input size",
                                  alg, input),
                         size, decryptor.InputBlockSize);
            AssertEquals(GetError("decryptor has wrong output size",
                                  alg, input),
                         size, decryptor.OutputBlockSize);
        }
        else
        {
            AssertEquals(GetError("decryptor has wrong input size",
                                  alg, input),
                         1, decryptor.InputBlockSize);
            AssertEquals(GetError("decryptor has wrong output size",
                                  alg, input),
                         1, decryptor.OutputBlockSize);
        }
        byte[] rawReverse = new byte [rawInput.Length + 256];
        int    rlen       = decryptor.TransformBlock
                                (rawOutput, 0, cutoff, rawReverse, 0);

        rawTail = decryptor.TransformFinalBlock
                      (rawOutput, cutoff, len - cutoff);
        Array.Copy(rawTail, 0, rawReverse, rlen, rawTail.Length);
        rlen += rawTail.Length;
        ((IDisposable)decryptor).Dispose();

        // Compare the reversed plaintext with the original.
        if (padding != PaddingMode.None)
        {
            AssertEquals(GetError
                             ("reversed plaintext has incorrect length",
                             alg, input), rawInput.Length, rlen);
            if (!IdenticalBlock(rawInput, 0, rawReverse, 0, rlen))
            {
                Fail(GetError
                         ("reversed plaintext is not the same as original",
                         alg, input));
            }
        }
        else
        {
            if (rawInput.Length > rlen)
            {
                Fail(GetError
                         ("reversed plaintext has incorrect length",
                         alg, input));
            }
            if (!IdenticalBlock(rawInput, 0, rawReverse, 0,
                                rawInput.Length))
            {
                Fail(GetError
                         ("reversed plaintext is not the same as original",
                         alg, input));
            }
        }

        // Encrypt the padded plaintext using a primitive
        // algorithm simulation to verify the expected output.
        byte[] paddedOutput;
        switch (mode)
        {
        case CipherMode.ECB:
        {
            paddedOutput = DoECB(paddedInput, alg, key);
        }
        break;

        case CipherMode.CBC:
        {
            paddedOutput = DoCBC(paddedInput, alg, key, iv);
        }
        break;

        case CipherMode.OFB:
        {
            paddedOutput = DoOFB(paddedInput, alg, key, iv);
        }
        break;

        case CipherMode.CFB:
        {
            paddedOutput = DoCFB(paddedInput, alg, key, iv);
        }
        break;

        case CipherMode.CTS:
        default:
        {
            paddedOutput = DoCTS(paddedInput, alg, key, iv);
        }
        break;
        }

        // Compare the actual output with the expected output.
        AssertEquals(GetError("ciphertext has incorrect length",
                              alg, input),
                     paddedOutput.Length, len);
        if (!IdenticalBlock(paddedOutput, 0, rawOutput, 0, len))
        {
            Fail(GetError("ciphertext was not the expected value",
                          alg, input));
        }
    }
Example #35
0
 public void TryDecryptOneShot_DestinationJustRight(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode) =>
 TryDecryptOneShot_DestinationJustRightTest(plaintext, ciphertext, padding, mode);
Example #36
0
        /// <summary>
        /// 加密 - 默认加密
        /// </summary>
        /// <typeparam name="T">对称加密算法类型</typeparam>
        /// <param name="data">明文</param>
        /// <param name="key">秘钥</param>
        /// <param name="encoding">编码方式,默认:UTF-8</param>
        /// <param name="outType">输出类型,默认:Base64</param>
        /// <param name="iv">加密偏移量,<see cref="CipherMode.ECB"/>模式不可用</param>
        /// <param name="keySize">秘钥大小</param>
        /// <param name="blockSize">块大小</param>
        /// <param name="cipherMode">对称算法加密模式,默认:<see cref="CipherMode.ECB"/></param>
        /// <param name="paddingMode">填充模式,默认:<see cref="PaddingMode.PKCS7"/></param>
        /// <returns></returns>
        internal static string Encrypt <T>(string data, string key, Encoding encoding = null,
                                           OutType outType         = OutType.Base64, string iv = null,
                                           int keySize             = 128, int blockSize        = 128, CipherMode cipherMode = CipherMode.ECB,
                                           PaddingMode paddingMode = PaddingMode.PKCS7) where T : SymmetricAlgorithm, new()
        {
            data.CheckNotNullOrEmpty(nameof(data));
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }
            byte[] plainBytes = encoding.GetBytes(data);

            byte[] encrypted;
            using (T cipher = new T())
            {
                cipher.KeySize   = keySize;
                cipher.BlockSize = blockSize;
                cipher.Mode      = cipherMode;
                cipher.Padding   = paddingMode;
                cipher.Key       = encoding.GetBytes(key);
                if (iv != null)
                {
                    int    ivsLength = blockSize / 8;
                    byte[] ivs       = new byte[ivsLength];
                    Array.Copy(encoding.GetBytes(iv.PadRight(ivsLength)), ivs, ivsLength);
                    cipher.IV = ivs;
                }

                using (ICryptoTransform encryptor = cipher.CreateEncryptor())
                {
                    encrypted = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
                }

                cipher.Clear();
            }
            return(GetEncryptResult(encrypted, outType));
        }
Example #37
0
 protected void RunModeTest(SymmetricAlgorithm alg, CipherMode mode)
 {
     RunModeTest(alg, mode, PaddingMode.None);
     RunModeTest(alg, mode, PaddingMode.PKCS7);
     RunModeTest(alg, mode, PaddingMode.Zeros);
 }
Example #38
0
 /// <summary>
 /// Creates a decryption transform that can be used by the .NET cryptography APIs.
 /// </summary>
 /// <param name="cipherMode">The mode if the cipher to use.</param>
 /// <param name="initializationVector">An initialization vector (if used by the <paramref name="cipherMode"/>, or <see langword="null"/> if not used).</param>
 /// <param name="feedbackSizeInBits">Size of the feedback register in bits for feedback modes.</param>
 /// <param name="paddingMode">The style of padding to apply to the last block.</param>
 /// <returns>An decryption transform that can be used by the .NET cryptography APIs.</returns>
 public ICryptoTransform CreateDecryptor(CipherMode cipherMode, byte[] initializationVector,
                                         int feedbackSizeInBits, PaddingMode paddingMode)
 {
     return(RijndaelDecryptionTransformFactory.Create(this, cipherMode, initializationVector, feedbackSizeInBits,
                                                      paddingMode));
 }
Example #39
0
        //----------------------------------------------------------------------------------

        static void Main(string[] args)
        {
            CipherMode cm   = CipherMode.CBC;
            string     salt = Program.SALT;
            string     hash = Program.HASH;
            string     iv   = Program.IV;
            string     pwd  = string.Empty;
            string     mode = string.Empty;
            string     ifn  = string.Empty;
            string     ofn  = string.Empty;
            byte       op   = 0;
            int        iks  = 256;
            int        inum = Program.INUM;
            bool       bow  = false;

            int l = args.Length;

            if (l < 1)
            {
                Program.ShowHelp();
            }

            else
            {
                try
                {
                    for (int i = 0; i < l; ++i)
                    {
                        switch (args[i].ToLower())
                        {
                        case "-e":
                        case "--encrypt-encode":
                            op = 1;
                            break;

                        case "-d":
                        case "--decrypt-decode":
                            op = 2;
                            break;

                        case "-o":
                        case "--output-file":
                            ofn = args[++i];
                            break;

                        case "-w":
                        case "--overwrite":
                            bow = true;
                            break;

                        case "-k":
                        case "--key-size":
                            switch (iks = Convert.ToInt32(args[++i]))
                            {
                            case 128:
                            case 192:
                            case 256:
                                break;

                            default:
                                throw new Exception("Invalid key size!");
                            }
                            break;

                        case "-p":
                        case "--password":
                            pwd = args[++i];
                            break;

                        case "-m":
                        case "--mode":
                            mode = args[++i].ToLower();
                            break;

                        case "-h":
                        case "--hash":
                            switch (hash = args[++i].ToUpper())
                            {
                            case "MD5":
                            case "SHA1":
                            case "SHA256":
                                break;

                            default:
                                throw new Exception("Invalid algorithm!");
                            }
                            break;

                        case "-c":
                        case "--cipher-mode":
                            switch (args[++i].ToUpper())
                            {
                            case "CBC":
                                cm = CipherMode.CBC;
                                break;

                            case "ECB":
                                cm = CipherMode.ECB;
                                break;

                            default:
                                throw new Exception("Invalid Cipher-Mode!");
                            }
                            break;

                        case "-s":
                        case "--salt":
                            salt = args[++i];
                            break;

                        case "-i":
                        case "--initial-vector":
                            if (args[++i].Length == 16)
                            {
                                iv = args[i];
                            }

                            else
                            {
                                throw new Exception
                                      (
                                          "Initial Vector does not have 16 characters!"
                                      );
                            }
                            break;

                        case "-n":
                        case "--num-iterations":
                            if ((inum = Convert.ToInt32(args[++i])) < 1)
                            {
                                inum = 1;
                            }
                            break;

                        case "--help":
                            Program.ShowHelp();
                            Environment.Exit(0);
                            break;

                        default:
                            ifn = args[i];
                            break;
                        }
                    }

                    Program.ShowLogo();

                    if (File.Exists(ifn))
                    {
                        BinaryReader br = new BinaryReader(File.Open(ifn, FileMode.Open));
                        long         ln = br.BaseStream.Length;
                        byte[]       bf = new byte[ln];

                        for (long i = 0; i < ln; ++i)
                        {
                            bf[i] = br.ReadByte();
                        }

                        br.Close();
                        Messenger.Print(Messenger.Icon.INFORMATION, "Processing. Please wait...");

                        switch (mode)
                        {
                        case "b64":
                            if (op == 1)
                            {
                                bf = ASCIIEncoding.ASCII.GetBytes
                                     (
                                    Convert.ToBase64String(bf)
                                     );
                            }

                            else if (op == 2)
                            {
                                bf = Convert.FromBase64String
                                     (
                                    ASCIIEncoding.ASCII.GetString(bf)
                                     );
                            }

                            ln = bf.Length;
                            break;

                        case "aes":
                            while (pwd.Length == 0)
                            {
                                Messenger.Print(Messenger.Icon.WARNING, "Password: "******"Mode no found!");
                        }

                        if (ofn.Length < 1)
                        {
                            Messenger.Print(Messenger.Icon.ERROR, "Output file name no found!\n");
                        }

                        else
                        {
                            if (File.Exists(ofn))
                            {
                                if (!bow)
                                {
                                    bow = ConsoleKey.Y == Messenger.Print
                                          (
                                        Messenger.Icon.QUESTION
                                        , String.Format
                                        (
                                            "The file \"{0}\"\n" +
                                            "     Already exists! Overwrite?"
                                            , Path.GetFullPath(ofn)
                                        )
                                        , new ConsoleKey[] { ConsoleKey.Y, ConsoleKey.N }
                                        , true
                                        , true
                                          );
                                }

                                if (bow)
                                {
                                    File.Delete(ofn);
                                }

                                else
                                {
                                    Messenger.Print
                                    (
                                        Messenger.Icon.WARNING
                                        , "Process canceled by user!\n"
                                    );

                                    Environment.Exit(0);
                                }
                            }

                            BinaryWriter bw = new BinaryWriter(File.Open(ofn, FileMode.CreateNew));

                            for (long i = 0; i < ln; ++i)
                            {
                                bw.Write(bf[i]);
                            }

                            bw.Close();

                            Messenger.Print(Messenger.Icon.INFORMATION, "Done!\n");
                        }
                    }

                    else
                    {
                        throw new Exception
                              (
                                  String.Format
                                  (
                                      "File \"{0}\" no found!"
                                      , ifn
                                  )
                              );
                    }
                }

                catch (Exception e)
                {
                    Program.ShowLogo();

                    if (e.Message.Length > 0)
                    {
                        Messenger.Print(Messenger.Icon.ERROR, e.Message, false, true);
                    }

                    Environment.Exit(1);
                }
            }
        }
Example #40
0
        /// <summary>
        ///   加密
        /// </summary>
        /// <param name="keyArray"></param>
        /// <param name="toEncryptArray"></param>
        /// <param name="iv">偏移量</param>
        /// <param name="keySize">key大小</param>
        /// <param name="blockSize">块大小</param>
        /// <param name="cipherMode"></param>
        /// <param name="paddingMode"></param>
        /// <returns></returns>
        public static byte[] Encrypt(byte[] keyArray, byte[] toEncryptArray, byte[] iv = null, int keySize = 256, int blockSize = 128, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7)
        {
            using (Aes rDel = Aes.Create())
            {
                rDel.KeySize   = keySize;
                rDel.BlockSize = blockSize;

                rDel.Key = keyArray;
                if (iv != null)
                {
                    rDel.IV = iv;
                }

                rDel.Mode    = cipherMode;
                rDel.Padding = paddingMode;

                ICryptoTransform cTransform  = rDel.CreateEncryptor();
                byte[]           resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                return(resultArray);
            }
        }
Example #41
0
        public static IBufferedCipher GetCipher(
            string algorithm)
        {
            if (algorithm == null)
            {
                throw new ArgumentNullException("algorithm");
            }

            algorithm = Platform.ToUpperInvariant(algorithm);

            {
                string aliased = (string)algorithms[algorithm];

                if (aliased != null)
                {
                    algorithm = aliased;
                }
            }

            IBasicAgreement iesAgreement = null;

            if (algorithm == "IES")
            {
                iesAgreement = new DHBasicAgreement();
            }
            else if (algorithm == "ECIES")
            {
                iesAgreement = new ECDHBasicAgreement();
            }

            if (iesAgreement != null)
            {
                return(new BufferedIesCipher(
                           new IesEngine(
                               iesAgreement,
                               new Kdf2BytesGenerator(
                                   new Sha1Digest()),
                               new HMac(
                                   new Sha1Digest()))));
            }



            if (Platform.StartsWith(algorithm, "PBE"))
            {
                if (Platform.EndsWith(algorithm, "-CBC"))
                {
                    if (algorithm == "PBEWITHSHA1ANDDES-CBC")
                    {
                        return(new PaddedBufferedBlockCipher(
                                   new CbcBlockCipher(new DesEngine())));
                    }
                    else if (algorithm == "PBEWITHSHA1ANDRC2-CBC")
                    {
                        return(new PaddedBufferedBlockCipher(
                                   new CbcBlockCipher(new RC2Engine())));
                    }
                    else if (Strings.IsOneOf(algorithm,
                                             "PBEWITHSHAAND2-KEYTRIPLEDES-CBC", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC"))
                    {
                        return(new PaddedBufferedBlockCipher(
                                   new CbcBlockCipher(new DesEdeEngine())));
                    }
                    else if (Strings.IsOneOf(algorithm,
                                             "PBEWITHSHAAND128BITRC2-CBC", "PBEWITHSHAAND40BITRC2-CBC"))
                    {
                        return(new PaddedBufferedBlockCipher(
                                   new CbcBlockCipher(new RC2Engine())));
                    }
                }
                else if (Platform.EndsWith(algorithm, "-BC") || Platform.EndsWith(algorithm, "-OPENSSL"))
                {
                    if (Strings.IsOneOf(algorithm,
                                        "PBEWITHSHAAND128BITAES-CBC-BC",
                                        "PBEWITHSHAAND192BITAES-CBC-BC",
                                        "PBEWITHSHAAND256BITAES-CBC-BC",
                                        "PBEWITHSHA256AND128BITAES-CBC-BC",
                                        "PBEWITHSHA256AND192BITAES-CBC-BC",
                                        "PBEWITHSHA256AND256BITAES-CBC-BC",
                                        "PBEWITHMD5AND128BITAES-CBC-OPENSSL",
                                        "PBEWITHMD5AND192BITAES-CBC-OPENSSL",
                                        "PBEWITHMD5AND256BITAES-CBC-OPENSSL"))
                    {
                        return(new PaddedBufferedBlockCipher(
                                   new CbcBlockCipher(new AesEngine())));
                    }
                }
            }



            string[] parts = algorithm.Split('/');

            IBlockCipher           blockCipher     = null;
            IAsymmetricBlockCipher asymBlockCipher = null;
            IStreamCipher          streamCipher    = null;

            string algorithmName = parts[0];

            {
                string aliased = (string)algorithms[algorithmName];

                if (aliased != null)
                {
                    algorithmName = aliased;
                }
            }

            CipherAlgorithm cipherAlgorithm;

            try
            {
                cipherAlgorithm = (CipherAlgorithm)Enums.GetEnumValue(typeof(CipherAlgorithm), algorithmName);
            }
            catch (ArgumentException)
            {
                throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
            }

            switch (cipherAlgorithm)
            {
            case CipherAlgorithm.AES:
                blockCipher = new AesEngine();
                break;

            case CipherAlgorithm.ARC4:
                streamCipher = new RC4Engine();
                break;

            case CipherAlgorithm.BLOWFISH:
                blockCipher = new BlowfishEngine();
                break;

            case CipherAlgorithm.CAMELLIA:
                blockCipher = new CamelliaEngine();
                break;

            case CipherAlgorithm.CAST5:
                blockCipher = new Cast5Engine();
                break;

            case CipherAlgorithm.CAST6:
                blockCipher = new Cast6Engine();
                break;

            case CipherAlgorithm.DES:
                blockCipher = new DesEngine();
                break;

            case CipherAlgorithm.DESEDE:
                blockCipher = new DesEdeEngine();
                break;

            case CipherAlgorithm.ELGAMAL:
                asymBlockCipher = new ElGamalEngine();
                break;

            case CipherAlgorithm.GOST28147:
                blockCipher = new Gost28147Engine();
                break;

            case CipherAlgorithm.HC128:
                streamCipher = new HC128Engine();
                break;

            case CipherAlgorithm.HC256:
                streamCipher = new HC256Engine();
                break;

            case CipherAlgorithm.IDEA:
                blockCipher = new IdeaEngine();
                break;

            case CipherAlgorithm.NOEKEON:
                blockCipher = new NoekeonEngine();
                break;

            case CipherAlgorithm.PBEWITHSHAAND128BITRC4:
            case CipherAlgorithm.PBEWITHSHAAND40BITRC4:
                streamCipher = new RC4Engine();
                break;

            case CipherAlgorithm.RC2:
                blockCipher = new RC2Engine();
                break;

            case CipherAlgorithm.RC5:
                blockCipher = new RC532Engine();
                break;

            case CipherAlgorithm.RC5_64:
                blockCipher = new RC564Engine();
                break;

            case CipherAlgorithm.RC6:
                blockCipher = new RC6Engine();
                break;

            case CipherAlgorithm.RIJNDAEL:
                blockCipher = new RijndaelEngine();
                break;

            case CipherAlgorithm.RSA:
                asymBlockCipher = new RsaBlindedEngine();
                break;

            case CipherAlgorithm.SALSA20:
                streamCipher = new Salsa20Engine();
                break;

            case CipherAlgorithm.SEED:
                blockCipher = new SeedEngine();
                break;

            case CipherAlgorithm.SERPENT:
                blockCipher = new SerpentEngine();
                break;

            case CipherAlgorithm.SKIPJACK:
                blockCipher = new SkipjackEngine();
                break;

            case CipherAlgorithm.SM4:
                blockCipher = new SM4Engine();
                break;

            case CipherAlgorithm.TEA:
                blockCipher = new TeaEngine();
                break;

            case CipherAlgorithm.THREEFISH_256:
                blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_256);
                break;

            case CipherAlgorithm.THREEFISH_512:
                blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_512);
                break;

            case CipherAlgorithm.THREEFISH_1024:
                blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_1024);
                break;

            case CipherAlgorithm.TNEPRES:
                blockCipher = new TnepresEngine();
                break;

            case CipherAlgorithm.TWOFISH:
                blockCipher = new TwofishEngine();
                break;

            case CipherAlgorithm.VMPC:
                streamCipher = new VmpcEngine();
                break;

            case CipherAlgorithm.VMPC_KSA3:
                streamCipher = new VmpcKsa3Engine();
                break;

            case CipherAlgorithm.XTEA:
                blockCipher = new XteaEngine();
                break;

            default:
                throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
            }

            if (streamCipher != null)
            {
                if (parts.Length > 1)
                {
                    throw new ArgumentException("Modes and paddings not used for stream ciphers");
                }

                return(new BufferedStreamCipher(streamCipher));
            }


            bool cts    = false;
            bool padded = true;
            IBlockCipherPadding padding         = null;
            IAeadBlockCipher    aeadBlockCipher = null;

            if (parts.Length > 2)
            {
                if (streamCipher != null)
                {
                    throw new ArgumentException("Paddings not used for stream ciphers");
                }

                string paddingName = parts[2];

                CipherPadding cipherPadding;
                if (paddingName == "")
                {
                    cipherPadding = CipherPadding.RAW;
                }
                else if (paddingName == "X9.23PADDING")
                {
                    cipherPadding = CipherPadding.X923PADDING;
                }
                else
                {
                    try
                    {
                        cipherPadding = (CipherPadding)Enums.GetEnumValue(typeof(CipherPadding), paddingName);
                    }
                    catch (ArgumentException)
                    {
                        throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
                    }
                }

                switch (cipherPadding)
                {
                case CipherPadding.NOPADDING:
                    padded = false;
                    break;

                case CipherPadding.RAW:
                    break;

                case CipherPadding.ISO10126PADDING:
                case CipherPadding.ISO10126D2PADDING:
                case CipherPadding.ISO10126_2PADDING:
                    padding = new ISO10126d2Padding();
                    break;

                case CipherPadding.ISO7816_4PADDING:
                case CipherPadding.ISO9797_1PADDING:
                    padding = new ISO7816d4Padding();
                    break;

                case CipherPadding.ISO9796_1:
                case CipherPadding.ISO9796_1PADDING:
                    asymBlockCipher = new ISO9796d1Encoding(asymBlockCipher);
                    break;

                case CipherPadding.OAEP:
                case CipherPadding.OAEPPADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher);
                    break;

                case CipherPadding.OAEPWITHMD5ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new MD5Digest());
                    break;

                case CipherPadding.OAEPWITHSHA1ANDMGF1PADDING:
                case CipherPadding.OAEPWITHSHA_1ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha1Digest());
                    break;

                case CipherPadding.OAEPWITHSHA224ANDMGF1PADDING:
                case CipherPadding.OAEPWITHSHA_224ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha224Digest());
                    break;

                case CipherPadding.OAEPWITHSHA256ANDMGF1PADDING:
                case CipherPadding.OAEPWITHSHA_256ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest());
                    break;

                case CipherPadding.OAEPWITHSHA384ANDMGF1PADDING:
                case CipherPadding.OAEPWITHSHA_384ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha384Digest());
                    break;

                case CipherPadding.OAEPWITHSHA512ANDMGF1PADDING:
                case CipherPadding.OAEPWITHSHA_512ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha512Digest());
                    break;

                case CipherPadding.PKCS1:
                case CipherPadding.PKCS1PADDING:
                    asymBlockCipher = new Pkcs1Encoding(asymBlockCipher);
                    break;

                case CipherPadding.PKCS5:
                case CipherPadding.PKCS5PADDING:
                case CipherPadding.PKCS7:
                case CipherPadding.PKCS7PADDING:
                    padding = new Pkcs7Padding();
                    break;

                case CipherPadding.TBCPADDING:
                    padding = new TbcPadding();
                    break;

                case CipherPadding.WITHCTS:
                    cts = true;
                    break;

                case CipherPadding.X923PADDING:
                    padding = new X923Padding();
                    break;

                case CipherPadding.ZEROBYTEPADDING:
                    padding = new ZeroBytePadding();
                    break;

                default:
                    throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
                }
            }

            string mode = "";

            if (parts.Length > 1)
            {
                mode = parts[1];

                int    di       = GetDigitIndex(mode);
                string modeName = di >= 0 ? mode.Substring(0, di) : mode;

                try
                {
                    CipherMode cipherMode = modeName == ""
                        ? CipherMode.NONE
                        : (CipherMode)Enums.GetEnumValue(typeof(CipherMode), modeName);

                    switch (cipherMode)
                    {
                    case CipherMode.ECB:
                    case CipherMode.NONE:
                        break;

                    case CipherMode.CBC:
                        blockCipher = new CbcBlockCipher(blockCipher);
                        break;

                    case CipherMode.CCM:
                        aeadBlockCipher = new CcmBlockCipher(blockCipher);
                        break;

                    case CipherMode.CFB:
                    {
                        int bits = (di < 0)
                                ?       8 * blockCipher.GetBlockSize()
                                :       int.Parse(mode.Substring(di));

                        blockCipher = new CfbBlockCipher(blockCipher, bits);
                        break;
                    }

                    case CipherMode.CTR:
                        blockCipher = new SicBlockCipher(blockCipher);
                        break;

                    case CipherMode.CTS:
                        cts         = true;
                        blockCipher = new CbcBlockCipher(blockCipher);
                        break;

                    case CipherMode.EAX:
                        aeadBlockCipher = new EaxBlockCipher(blockCipher);
                        break;

                    case CipherMode.GCM:
                        aeadBlockCipher = new GcmBlockCipher(blockCipher);
                        break;

                    case CipherMode.GOFB:
                        blockCipher = new GOfbBlockCipher(blockCipher);
                        break;

                    case CipherMode.OCB:
                        aeadBlockCipher = new OcbBlockCipher(blockCipher, CreateBlockCipher(cipherAlgorithm));
                        break;

                    case CipherMode.OFB:
                    {
                        int bits = (di < 0)
                                ?       8 * blockCipher.GetBlockSize()
                                :       int.Parse(mode.Substring(di));

                        blockCipher = new OfbBlockCipher(blockCipher, bits);
                        break;
                    }

                    case CipherMode.OPENPGPCFB:
                        blockCipher = new OpenPgpCfbBlockCipher(blockCipher);
                        break;

                    case CipherMode.SIC:
                        if (blockCipher.GetBlockSize() < 16)
                        {
                            throw new ArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)");
                        }
                        blockCipher = new SicBlockCipher(blockCipher);
                        break;

                    default:
                        throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
                    }
                }
                catch (ArgumentException)
                {
                    throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
                }
            }

            if (aeadBlockCipher != null)
            {
                if (cts)
                {
                    throw new SecurityUtilityException("CTS mode not valid for AEAD ciphers.");
                }
                if (padded && parts.Length > 2 && parts[2] != "")
                {
                    throw new SecurityUtilityException("Bad padding specified for AEAD cipher.");
                }

                return(new BufferedAeadBlockCipher(aeadBlockCipher));
            }

            if (blockCipher != null)
            {
                if (cts)
                {
                    return(new CtsBlockCipher(blockCipher));
                }

                if (padding != null)
                {
                    return(new PaddedBufferedBlockCipher(blockCipher, padding));
                }

                if (!padded || blockCipher.IsPartialBlockOkay)
                {
                    return(new BufferedBlockCipher(blockCipher));
                }

                return(new PaddedBufferedBlockCipher(blockCipher));
            }

            if (asymBlockCipher != null)
            {
                return(new BufferedAsymmetricBlockCipher(asymBlockCipher));
            }

            throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
        }
 public static void ResetPaddingAndCipherModes()
 {
     _paddingMode = PaddingMode.ISO10126;
     _cipherMode  = CipherMode.CBC;
 }
Example #43
0
        [System.Security.SecurityCritical]  // auto-generated
        internal CryptoAPITransform(int algid, int cArgs, int[] rgArgIds,
                                    Object[] rgArgValues, byte[] rgbKey, PaddingMode padding,
                                    CipherMode cipherChainingMode, int blockSize,
                                    int feedbackSize, bool useSalt,
                                    CryptoAPITransformMode encDecMode)
        {
            int dwValue;

            byte[] rgbValue;

            BlockSizeValue   = blockSize;
            ModeValue        = cipherChainingMode;
            PaddingValue     = padding;
            encryptOrDecrypt = encDecMode;

            // Copy the input args
            int _cArgs = cArgs;

            int[] _rgArgIds = new int[rgArgIds.Length];
            Array.Copy(rgArgIds, _rgArgIds, rgArgIds.Length);
            _rgbKey = new byte[rgbKey.Length];
            Array.Copy(rgbKey, _rgbKey, rgbKey.Length);
            Object[] _rgArgValues = new Object[rgArgValues.Length];
            // an element of rgArgValues can only be an int or a byte[]
            for (int j = 0; j < rgArgValues.Length; j++)
            {
                if (rgArgValues[j] is byte[])
                {
                    byte[] rgbOrig = (byte[])rgArgValues[j];
                    byte[] rgbNew  = new byte[rgbOrig.Length];
                    Array.Copy(rgbOrig, rgbNew, rgbOrig.Length);
                    _rgArgValues[j] = rgbNew;
                    continue;
                }
                if (rgArgValues[j] is int)
                {
                    _rgArgValues[j] = (int)rgArgValues[j];
                    continue;
                }
                if (rgArgValues[j] is CipherMode)
                {
                    _rgArgValues[j] = (int)rgArgValues[j];
                    continue;
                }
            }

            _safeProvHandle = Utils.AcquireProvHandle(new CspParameters(Utils.DefaultRsaProviderType));

            SafeKeyHandle safeKeyHandle = SafeKeyHandle.InvalidHandle;

            // _ImportBulkKey will check for failures and throw an exception
            Utils._ImportBulkKey(_safeProvHandle, algid, useSalt, _rgbKey, ref safeKeyHandle);
            _safeKeyHandle = safeKeyHandle;

            for (int i = 0; i < cArgs; i++)
            {
                switch (rgArgIds[i])
                {
                case Constants.KP_IV:
                    IVValue  = (byte[])_rgArgValues[i];
                    rgbValue = IVValue;
                    Utils.SetKeyParamRgb(_safeKeyHandle, _rgArgIds[i], rgbValue, rgbValue.Length);
                    break;

                case Constants.KP_MODE:
                    ModeValue = (CipherMode)_rgArgValues[i];
                    dwValue   = (Int32)_rgArgValues[i];
SetAsDWord:
                    Utils.SetKeyParamDw(_safeKeyHandle, _rgArgIds[i], dwValue);
                    break;

                case Constants.KP_MODE_BITS:
                    dwValue = (Int32)_rgArgValues[i];
                    goto SetAsDWord;

                case Constants.KP_EFFECTIVE_KEYLEN:
                    dwValue = (Int32)_rgArgValues[i];
                    goto SetAsDWord;

                default:
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeyParameter"), "_rgArgIds[i]");
                }
            }
        }
Example #44
0
 public void EncryptOneShot_Array(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode) =>
 EncryptOneShot_ArrayTest(plaintext, ciphertext, padding, mode);
Example #45
0
 /// <summary>
 /// 3des ecb模式加密
 /// </summary>
 /// <param name="aStrString">待加密的字符串</param>
 /// <param name="aStrKey">密钥</param>
 /// <param name="iv">加密矢量:只有在CBC解密模式下才适用</param>
 /// <param name="mode">运算模式</param>
 /// <returns>加密后的字符串</returns>
 public static string Encrypt3Des(string aStrString, string aStrKey = "12345678qwertyui87654321", CipherMode mode = CipherMode.ECB, string iv = "1234abcd")
 {
     try
     {
         var des = new TripleDESCryptoServiceProvider
         {
             Key  = Encoding.UTF8.GetBytes(aStrKey),
             Mode = mode
         };
         if (mode == CipherMode.CBC)
         {
             des.IV = Encoding.UTF8.GetBytes(iv);
         }
         des.Padding = PaddingMode.PKCS7;
         var    desEncrypt = des.CreateEncryptor();
         byte[] buffer     = Encoding.UTF8.GetBytes(aStrString);
         return(Convert.ToBase64String(desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length)));
     }
     catch (Exception e)
     {
         return(string.Empty);
     }
 }
Example #46
0
 public void DecryptOneShot_Span(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode) =>
 DecryptOneShot_SpanTest(plaintext, ciphertext, padding, mode);
Example #47
0
 public void TryEncryptOneShot_Overlaps(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode) =>
 TryEncryptOneShot_OverlapsTest(plaintext, ciphertext, padding, mode);
Example #48
0
 public void setMode(CipherMode mode)
 {
     this.mode = mode;
 }
Example #49
0
 public void TryEncryptOneShot_DestinationLarger(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode) =>
 TryEncryptOneShot_DestinationLargerTest(plaintext, ciphertext, padding, mode);
Example #50
0
 /// <summary>
 /// 对称加密算法AES RijndaelManaged解密字符串
 /// </summary>
 /// <param name="decryptString">待解密的字符串</param>
 /// <param name="decryptKey">解密密钥,和加密密钥相同</param>
 /// <param name="mode">加密模式</param>
 /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
 public static string AESDecrypt(this string decryptString, byte[] decryptKey, CipherMode mode = CipherMode.CBC)
 {
     try
     {
         using var rijndaelProvider = new RijndaelManaged()
               {
                   Key  = decryptKey,
                   IV   = Keys,
                   Mode = mode
               };
         using ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
         byte[] inputData     = Convert.FromBase64String(decryptString);
         byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
         return(Encoding.UTF8.GetString(decryptedData));
     }
     catch
     {
         return(string.Empty);
     }
 }
Example #51
0
 public void OneShotRoundtrip(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode) =>
 OneShotRoundtripTest(plaintext, ciphertext, padding, mode);
Example #52
0
 /// <summary>
 /// 加密文件流
 /// </summary>
 /// <param name="fs">需要加密的文件流</param>
 /// <param name="decryptKey">加密密钥</param>
 /// <param name="mode">加密模式</param>
 /// <returns>加密流</returns>
 public static CryptoStream AESEncryptStrream(this FileStream fs, string decryptKey, CipherMode mode = CipherMode.CBC)
 {
     decryptKey = GetSubString(decryptKey, 32, "");
     decryptKey = decryptKey.PadRight(32, ' ');
     using var rijndaelProvider = new RijndaelManaged()
           {
               Key  = Encoding.UTF8.GetBytes(decryptKey),
               IV   = Keys,
               Mode = mode
           };
     using var encrypto = rijndaelProvider.CreateEncryptor();
     return(new CryptoStream(fs, encrypto, CryptoStreamMode.Write));
 }
Example #53
0
        private static byte[] Encrypt(byte[] message, SymmetricAlgorithm sa, byte[] key, byte[] iv, CipherMode mode,
                                      PaddingMode padding)
        {
            sa.Key     = key;
            sa.IV      = iv;
            sa.Mode    = mode;
            sa.Padding = padding;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, sa.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(message, 0, message.Length);
            cs.Close();
            ms.Close();
            return(ms.ToArray());
        }
Example #54
0
 /// <summary>
 /// 加密文件流
 /// </summary>
 /// <param name="fs">需要加密的文件流</param>
 /// <param name="decryptKey">加密密钥</param>
 /// <param name="mode">加密模式</param>
 /// <returns>加密流</returns>
 public static CryptoStream AESEncryptStrream(this FileStream fs, byte[] decryptKey, CipherMode mode = CipherMode.CBC)
 {
     using var rijndaelProvider = new RijndaelManaged()
           {
               Key  = decryptKey,
               IV   = Keys,
               Mode = mode
           };
     using var encrypto = rijndaelProvider.CreateEncryptor();
     return(new CryptoStream(fs, encrypto, CryptoStreamMode.Write));
 }
Example #55
0
        public static string DecryptStringFromBytes_Aes(byte[] cipherBytes, byte[] key, byte[] iv, int blockSize, CipherMode mode)
        {
            if (cipherBytes == null || cipherBytes.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }

            // Declare the string used to hold the decrypted text.
            string plainText = null;

            // Create an AesManaged object with the specified key and IV.
            using (AesManaged aesAlg = new AesManaged()) {
                aesAlg.Key       = key;
                aesAlg.IV        = iv;
                aesAlg.BlockSize = blockSize;
                aesAlg.Mode      = mode;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherBytes)) {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt)) {
                            // Read the decrypted bytes from the decrypting stream and place them in a string.
                            plainText = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return(plainText);
        }
        private static void aesEncryptFile(CipherMode mode, byte[] keyBytes, byte[] ivBytes, string inputFile, string outputFile)
        {
            //Setting Up the AES object
            Aes aes = Aes.Create();

            aes.Mode = mode;
            aes.Key  = keyBytes;

            //For ECB it will ignore the IV anyway so we dont have to worry about checking mode
            if (ivBytes != null)
            {
                aes.IV = ivBytes;
            }
            else
            {
                // In the case where the user has not provided the IV
                // It will print the IV to the console. We would not usally do
                // this. But this allows me to check my output.
                printIV(aes.IV);
            }

            // The Assignment doesn't seem require us to create code that will decrpyt the file as well.
            // However, if you wanted to decrypt as well, it would be the same code as this method except
            // here you would call aes.CreateDecryptor().
            ICryptoTransform cryptoTransform = aes.CreateEncryptor();

            // Here we open the input file
            using (FileStream outputFileStream = new FileStream(outputFile, FileMode.Create))
            {
                using (CryptoStream cryptoStream = new CryptoStream(outputFileStream, cryptoTransform, CryptoStreamMode.Write))
                {
                    // We are reading in blocks in a time just to make it a bit faster
                    var totalBytesRead = 0;
                    var offset         = 0;

                    // This is how many bits per block we read in a time. However, it
                    // However, this has nothing do with AES block size. We could choose
                    // any block size. But we might as well use the AES block size and
                    // hopefully save some padding.
                    int    inputBlockSize = 128;
                    byte[] inputData      = new byte[inputBlockSize];

                    using (FileStream inputFileStream = new FileStream(inputFile, FileMode.Open))
                    {
                        var bytesRead = 0;
                        do
                        {
                            bytesRead = inputFileStream.Read(inputData, 0, inputBlockSize);
                            offset   += bytesRead;
                            // The Crypto Stream will use the transformer we declared above
                            // to actually carry out the transformation.
                            cryptoStream.Write(inputData, 0, bytesRead);
                            totalBytesRead += bytesRead;
                        }while (bytesRead > 0);

                        inputFileStream.Close();
                    }

                    cryptoStream.FlushFinalBlock();
                    cryptoStream.Close();
                }
                outputFileStream.Close();
            }
        }
Example #57
0
 /// <summary>
 /// 对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法)
 /// </summary>
 /// <param name="encryptString">待加密字符串</param>
 /// <param name="encryptKey">加密密钥,须半角字符</param>
 /// <param name="mode">加密模式</param>
 /// <returns>加密结果字符串</returns>
 public static string AESEncrypt(this string encryptString, byte[] encryptKey, CipherMode mode = CipherMode.CBC)
 {
     using var rijndaelProvider = new RijndaelManaged
           {
               Key  = encryptKey,
               IV   = Keys,
               Mode = mode
           };
     using ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
     byte[] inputData     = Encoding.UTF8.GetBytes(encryptString);
     byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
     return(Convert.ToBase64String(encryptedData));
 }
Example #58
0
 /// <summary>
 /// 对称加密算法AES RijndaelManaged解密字符串
 /// </summary>
 /// <param name="decryptString">待解密的字符串</param>
 /// <param name="mode">加密模式</param>
 /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
 public static string AESDecrypt(this string decryptString, CipherMode mode = CipherMode.CBC)
 {
     return(AESDecrypt(decryptString, Default_AES_Key, mode));
 }
 /// <summary>
 /// Initialize algo with key, block size, key size, padding mode and cipher mode to be known.
 /// </summary>
 /// <param name="key">ASCII key to be used for encryption or decryption</param>
 /// <param name="blockSize">block size to use for AES algorithm. 128, 192 or 256 bits (default for incorrect size=256)</param>
 /// <param name="keySize">key length to use for AES algorithm. 128, 192, or 256 bits (default for incorrect size=128)</param>
 /// <param name="paddingMode"></param>
 /// <param name="cipherMode"></param>
 public AnotherAES(string key, int blockSize, int keySize, PaddingMode paddingMode, CipherMode cipherMode)
 {
     rijn = new RijndaelManaged();
     rijn.Key = Encoding.UTF8.GetBytes(key);
     rijn.BlockSize = (new string[] { "128", "192", "256" }).Contains(blockSize.ToString()) ? blockSize : 256;
     rijn.KeySize = (new string[] { "128", "192", "256" }).Contains(blockSize.ToString()) ? keySize : 128;
     rijn.Padding = paddingMode;
     rijn.Mode = cipherMode;
 }
Example #60
0
        private static string DecryptStringFromBytes_Aes(string cipherTextString, byte[] Key, byte[] IV, CipherMode mode, PaddingMode padding)
        {
            byte[] cipherText = Convert.FromBase64String(cipherTextString);

            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            string plaintext = null;

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.KeySize   = 256;
                aesAlg.BlockSize = 128;
                aesAlg.Key       = Key;
                aesAlg.IV        = IV;
                aesAlg.Mode      = mode;
                aesAlg.Padding   = padding;

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt =
                               new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            return(plaintext);
        }