Пример #1
2
    static Boolean TestKnownEnc(Aes aes, Byte[] Key, Byte[] IV, Byte[] Plain, Byte[] Cipher)
    {

        Byte[]  CipherCalculated;
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(Plain);
        Console.WriteLine("With the following Key:");
        PrintByteArray(Key);
        Console.WriteLine("and IV:");
        PrintByteArray(IV);
 		Console.WriteLine("Expecting this ciphertext:");
		PrintByteArray(Cipher);        
        
        ICryptoTransform sse = aes.CreateEncryptor(Key, IV);
        MemoryStream 	ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(Plain,0,Plain.Length);
        cs.FlushFinalBlock();
        CipherCalculated = ms.ToArray();
        cs.Close();

		Console.WriteLine("Computed this cyphertext:");
        PrintByteArray(CipherCalculated);
        

        if (!Compare(Cipher, CipherCalculated)) {
        	Console.WriteLine("ERROR: result is different from the expected");
        	return false;
        }
        
        Console.WriteLine("OK");
        return true;
    }
Пример #2
0
        public static string EncryptString(string key, string plainText)
        {
            byte[] iv = new byte[16];
            byte[] array;

            using (Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV  = iv;

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

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
                        {
                            streamWriter.Write(plainText);
                        }

                        array = memoryStream.ToArray();
                    }
                }
            }

            return(Convert.ToBase64String(array));
        }
        /// <summary>
        /// Encrypts a string
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public byte[] EncryptToBytes(string value)
        {
            byte[]           output = null;
            ICryptoTransform et     = _cryptor.CreateEncryptor(_cryptor.Key, _cryptor.IV);

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, et, CryptoStreamMode.Write))
                {
                    using (StreamWriter sw = new StreamWriter(cs, this._encoding, this._padding))
                    {
                        sw.Write(value);
                        sw.Flush();
                    }
                    cs.Flush();
                    output = ms.ToArray();
                }

                ms.Flush();
                ms.Dispose();
            }

            et.Dispose();
            et = null;
            return(output);
        }
Пример #4
0
        internal void ProcessEncryption(crypto.Aes cipher, CommandLine commandLine)
        {
            var key = new Rfc2898DeriveBytes(commandLine.Password, commandLine.KeySaltLength, commandLine.KeyIterations);

            cipher.GenerateIV();
            cipher.Key = key.GetBytes(cipher.KeySize / 8);

            Stream inputStream  = CreateInputStream(commandLine);
            Stream outputStream = CreateOutputStream(commandLine);

            // 2 bytes of version
            outputStream.Write(Constants.FormatVersionBytes, 0, Constants.FormatVersionBytes.Length);

            // stores 16 bytes of IV
            outputStream.Write(cipher.IV, 0, cipher.IV.Length);

            // stores 2 bytes of salt size (in network order)
            short saltLength = IPAddress.HostToNetworkOrder((short)key.Salt.Length);

            byte[] saltLengthBytes = BitConverter.GetBytes(saltLength);
            outputStream.Write(saltLengthBytes, 0, saltLengthBytes.Length);

            // stores n bytes of salt
            outputStream.Write(key.Salt, 0, key.Salt.Length);

            using (ICryptoTransform encryptor = cipher.CreateEncryptor())
            {
                using (Stream cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write))
                    inputStream.CopyTo(cryptoStream);
            }
        }
Пример #5
0
        // Для работы TripleDES требуется вектор инициализации (IV) и ключ (Key)
        // Операции шифрования/деширования должны использовать одинаковые значения IV и Key

        public void EncryptStream(Stream sourcestream, Stream deststream, string key)
        {
            byte[] _key = new byte[32];
            byte[] _IV  = new byte[16];

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

            for (int i = 0; i < _key.Length; i++)
            {
                _key[i] = 0;
            }
            for (int i = 0; (i < _key.Length) && (i < myKey.Length); i++)
            {
                _key[i] = myKey[i];
            }
            for (int i = 0; (i < _key.Length) && (i < _IV.Length); i++)
            {
                _IV[i] = _key[i];
            }
            _IV.Reverse();

            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
            aes.IV  = _IV;
            aes.Key = _key;
            var decStream = new CryptoStream(sourcestream, aes.CreateEncryptor(), CryptoStreamMode.Read);

            deststream.SetLength(0);
            decStream.CopyTo(deststream);
        }
        protected virtual ICryptoTransform CreateTransform(System.Security.Cryptography.Aes aes, byte[] key, byte[] iv, AesMode mode)
        {
            if (aes == null)
            {
                throw new ArgumentNullException(nameof(aes));
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (iv == null)
            {
                throw new ArgumentNullException(nameof(iv));
            }

            switch (mode)
            {
            case AesMode.Decrypt:
                return(aes.CreateDecryptor(key, iv));

            case AesMode.Encrypt:
                return(aes.CreateEncryptor(key, iv));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Пример #7
0
        public override void init(int mode, byte[] key, byte[] iv)
        {
            if (mode != ENCRYPT_MODE && mode != DECRYPT_MODE) throw new ArgumentOutOfRangeException();
            ms = new PipedMemoryStream();
            aesm = AesManaged.Create();
            aesm.BlockSize = blockSize * 8;
            aesm.Padding = PaddingMode.None;
            ICryptoTransform ict;
            if (key.Length > blockSize)
            {
                byte[] tmp = new byte[blockSize];
                Array.Copy(key, 0, tmp, 0, tmp.Length);
                key = tmp;
            }
            if (iv.Length > ivSize)
            {
                byte[] tmp = new byte[ivSize];
                Array.Copy(iv, 0, tmp, 0, tmp.Length);
                iv = tmp;
            }
            if (mode == ENCRYPT_MODE)
            {
                ict = aesm.CreateEncryptor(key, iv);
            }
            else
            {
                ict = aesm.CreateDecryptor(key, iv);
            }

            cs = new CryptoStream(ms, ict, CryptoStreamMode.Write);
        }
Пример #8
0
        private static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
        {
            byte[] encrypted;
            // Create an Aes object
            // with the specified key and IV.
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

                // Create a decrytor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(
                               msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        using (System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.
            return(encrypted);
        }
Пример #9
0
                /// <summary>
                /// Encrypt a message
                /// </summary>
                /// <param name="messageToEncrypt">The message to be encrypted</param>
                /// <param name="secretKey">The 32 characters long secret key to be used on the encryption</param>
                /// <param name="secretVector">The 16 characters long secret vector to be used on the encryption</param>
                /// <returns>The encrypted message</returns>
                public static String Encrypt(String messageToEncrypt, String secretKey, String secretVector)
                {
                    String messageEncrypted = null;

                    using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
                    {
                        aes.Key = System.Text.Encoding.UTF8.GetBytes(secretKey);
                        aes.IV  = System.Text.Encoding.UTF8.GetBytes(secretVector);

                        ICryptoTransform iCryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV);

                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, iCryptoTransform, CryptoStreamMode.Write))
                            {
                                using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
                                {
                                    streamWriter.Write(messageToEncrypt);
                                }

                                messageEncrypted = Convert.ToBase64String(memoryStream.ToArray());
                            }
                        }
                    }

                    return(messageEncrypted);
                }
Пример #10
0
 public AES(byte[] key)
 {
     rsa = new AesManaged();
     rsa.GenerateKey();
     rsa.GenerateIV();
     _decoder = rsa.CreateDecryptor();
     _encoder = rsa.CreateEncryptor();
 }
Пример #11
0
        /// <summary>
        /// AES加解密
        /// </summary>
        /// <param name="aes"></param>
        /// <param name="forEncryption">是否加密(false为解密)</param>
        /// <param name="data">待加解密的数据</param>
        /// <param name="key">加解密密钥,为空则使用实体属性Key</param>
        /// <param name="mode">加解密模式,为空则使用实体属性Mode</param>
        /// <param name="padding">填充算法,为空则使用实体属性Padding</param>
        /// <returns>加解密后数据</returns>
        public static byte[] Crypto(this System.Security.Cryptography.Aes aes,
                                    bool forEncryption, byte[] data, byte[] key = null, CipherMode?mode = null, PaddingMode?padding = null)
        {
            aes.Key     = key ?? aes.Key;
            aes.Mode    = mode ?? aes.Mode;
            aes.Padding = padding ?? aes.Padding;
            var cryptor = forEncryption ? aes.CreateEncryptor() : aes.CreateDecryptor();

            return(cryptor.TransformFinalBlock(data, 0, data.Length));
        }
Пример #12
0
        static DBCrypto()
        {
            aesAlg = Aes.Create();
            aesAlg.Key = AES_CBC_KEY;
            aesAlg.IV = AES_CBC_IV;
            aesAlg.Padding = PaddingMode.PKCS7;

            decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
            encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
        }
Пример #13
0
        public SimpleAes(byte[] key)
        {
            aes = Aes.Create();
            aes.GenerateIV();

            aes.Key = key;

            encryptor = aes.CreateEncryptor(key, aes.IV);
            decryptor = aes.CreateDecryptor(key, aes.IV);
        }
Пример #14
0
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="key"></param>
        /// <param name="counterBufferSegment"></param>
        /// <param name="aesFactory"></param>
        /// <exception cref="ArgumentException">
        /// <paramref name="counterBufferSegment"/> needs to have the same length as <see cref="AesConstants.STR_AES_BLOCK_SIZE"/>.
        /// </exception>
        public AesCtrCryptoTransform(byte[] key, ArraySegment<byte> counterBufferSegment, Func<Aes> aesFactory = null)
        {
            if (counterBufferSegment.Count != AesConstants.AES_BLOCK_SIZE)
                throw new ArgumentException($"{nameof(counterBufferSegment)}.Count must be {AesConstants.STR_AES_BLOCK_SIZE}.", nameof(counterBufferSegment));

            _aes = aesFactory?.Invoke() ?? CipherFactory.Aes();
            _aes.Mode = CipherMode.ECB;
            _aes.Padding = PaddingMode.None;

            Buffer.BlockCopy(counterBufferSegment.Array, counterBufferSegment.Offset, _counterBuffer.Value, 0, AesConstants.AES_BLOCK_SIZE);
            _cryptoTransform = _aes.CreateEncryptor(rgbKey: key, rgbIV: null);
        }
		/// <summary>ctor</summary>
		public AesCtrCryptoTransform(byte[] key, ArraySegment<byte> counterBufferSegment, Func<Aes> aesFactory = null)
		{
			if (counterBufferSegment.Count != AesConstants.AES_BLOCK_SIZE)
				throw new ArgumentException("counterBufferSegment.Count must be " + AesConstants.STR_AES_BLOCK_SIZE + ".");

			this.aes = aesFactory == null ? AesFactories.Aes() : aesFactory();
			this.aes.Mode = CipherMode.ECB;
			this.aes.Padding = PaddingMode.None;

			Utils.BlockCopy(counterBufferSegment.Array, counterBufferSegment.Offset, counterBuffer, 0, AesConstants.AES_BLOCK_SIZE);
			this.cryptoTransform = aes.CreateEncryptor(rgbKey: key, rgbIV: null);
		}// ctor
 internal static byte[] AES256Encrypt(byte[] block, byte[] key)
 {
     using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
     {
         aes.Key     = key;
         aes.Mode    = System.Security.Cryptography.CipherMode.ECB;
         aes.Padding = System.Security.Cryptography.PaddingMode.None;
         using (System.Security.Cryptography.ICryptoTransform encryptor = aes.CreateEncryptor())
         {
             return(encryptor.TransformFinalBlock(block, 0, block.Length));
         }
     }
 }
Пример #17
0
        private string CryptoTransform(string input, bool base64in, bool base64out, Aes cipher, CMode mode)
        {
            byte[] bytes;
            if (base64in)
                bytes = decode64(input);
            else
                bytes = Encoding.UTF8.GetBytes(input);


            using (var c = mode == CMode.ENCRYPT ? cipher.CreateEncryptor() : cipher.CreateDecryptor()) {
            var buf = c.TransformFinalBlock(bytes, 0, bytes.Length);
            return base64out ? encode64(buf) : Encoding.UTF8.GetString(buf);
            }
        }
Пример #18
0
        public static byte[] EncryptStringToBytes_AES(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments
            if (ReferenceEquals(plainText, null) || plainText.Length <= 0)
            {
                throw (new ArgumentNullException("plainText"));
            }

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

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

            byte[] encrypted = null;

            // Create an Aes object with the specified key and IV
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            // Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }


                        encrypted = msEncrypt.ToArray();
                    }
                }
            }


            // Return the encrypted bytes from the memory stream
            return(encrypted);
        }
Пример #19
0
        /// <summary>
        /// Encrypt the giving <see cref="Byte"> <see cref="Array"/>.
        /// </summary>
        /// <param name="plainText">The <see cref="Byte"> <see cref="Array"/> that contains data to encrypt.</param>
        /// <param name="Key">The <see cref="Byte"> <see cref="Array"/> that contains the key.</param>
        /// <param name="IV">The <see cref="Byte"> <see cref="Array"/> that contains the initialize vector.</param>
        /// <returns>The encrypted data.</returns>
        public static byte[] Encrypt(byte[] plainText, byte[] Key, byte[] IV)
        {
            // Check arguments
            if (ReferenceEquals(plainText, null) || plainText.Length <= 0)
            {
                throw (new ArgumentNullException("plainText"));
            }

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

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

            byte[] encrypted = null;

            // Create an Aes object with the specified key and IV
            using (System.Security.Cryptography.Aes aesAlg = AesManaged.Create())
            {
                aesAlg.Key     = Key;
                aesAlg.IV      = IV;
                aesAlg.Padding = PaddingMode.Zeros;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(plainText, 0, plainText.Length);
                        csEncrypt.Flush();
                        csEncrypt.Close();
                    }

                    encrypted = msEncrypt.ToArray();
                }
            }

            // Return the encrypted bytes from the memory stream
            return(encrypted);
        }
Пример #20
0
    static Boolean Test(Aes aes, CipherMode md)
    {

        Byte[]  PlainText = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        Byte[]  Key = {1, 1, 1, 1, 1, 1, 1, 1,2,2,2,2,2,2,2,2};
        Byte[]  IV = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115};
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(PlainText);
        
        aes.Mode = md;

        Console.WriteLine("AES default key size = " + aes.KeySize);
        ICryptoTransform sse = aes.CreateEncryptor(Key, IV);
        Console.WriteLine("SSE mode = " + aes.Mode);
        MemoryStream ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(PlainText,0,PlainText.Length);
        cs.FlushFinalBlock();
        byte[] CipherText = ms.ToArray();
        cs.Close();

        Console.WriteLine("Cyphertext:");
        PrintByteArray(CipherText);
        

        Console.WriteLine("Decrypting...");

        ICryptoTransform ssd = aes.CreateDecryptor(Key, IV);
        Console.WriteLine("SSD mode = " + aes.Mode);
        cs = new CryptoStream(new MemoryStream(CipherText), ssd, CryptoStreamMode.Read);

        byte[] NewPlainText = new byte[PlainText.Length];
        cs.Read(NewPlainText,0,PlainText.Length);

        PrintByteArray(NewPlainText);
        
        if (!Compare(PlainText, NewPlainText)) {
        	Console.WriteLine("ERROR: roundtrip failed");
        	return false;
        }
        
        return true;
    }
Пример #21
0
 public override string Encrypt(string plainText)
 {
     try
     {
         System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
         byte[] inputBytes = Encoding.UTF8.GetBytes(plainText);
         this.Key = Convert.ToBase64String(aes.Key).Replace("-", "");
         this.IV  = Convert.ToBase64String(aes.IV).Replace("-", "");
         MemoryStream ms = new MemoryStream();
         CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
         cs.Write(inputBytes, 0, inputBytes.Length);
         cs.FlushFinalBlock();
         return(Convert.ToBase64String(ms.ToArray()));
     }
     catch (Exception e)
     {
         return("\nERROR: " + e.Message);
     }
 }
Пример #22
0
 public string Encrypt(string str)
 {
     using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create())
     {
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, 8);
         encryptor.Key = pdb.GetBytes(32);
         encryptor.IV  = pdb.GetBytes(16);
         using (MemoryStream ms = new MemoryStream())
         {
             byte[] bytes = Encoding.Unicode.GetBytes(str);
             using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
             {
                 cs.Write(bytes, 0, bytes.Length);
                 cs.Close();
             }
             return(Convert.ToBase64String(ms.ToArray()));
         }
     }
 }
 public static string Encrypt(string EncryptText)
 {
     byte[] clearBytes = Encoding.Unicode.GetBytes(EncryptText);
     using (Aes encryptor = Aes.Create())
     {
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
         encryptor.Key = pdb.GetBytes(32);
         encryptor.IV  = pdb.GetBytes(16);
         using (MemoryStream ms = new MemoryStream())
         {
             using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
             {
                 cs.Write(clearBytes, 0, clearBytes.Length);
                 cs.Close();
             }
             EncryptText = Convert.ToBase64String(ms.ToArray());
         }
     }
     return(EncryptText);
 }
Пример #24
0
        public byte[] CoderBytes(byte[] input)
        {
            //Проверка аргументов
            if (input == null || input.Length <= 0)
            {
                return(null);
            }

            byte[] coderByte;

            //Создаем поток для шифрования
            using (var msEncrypt = new MemoryStream())
            {
                using (var csEncrypt = new CryptoStream(msEncrypt, AES.CreateEncryptor(AES.Key, AES.IV), CryptoStreamMode.Write))
                {
                    csEncrypt.Write(input, 0, input.Length);
                }
                coderByte = msEncrypt.ToArray();
            }

            return(coderByte);
        }
Пример #25
0
    public string Encrypt(string clearText)
    {
        string EncryptionKey = "KFNLP@$$W0rdMOICP@$$Word";

        byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
        using (System.Security.Cryptography.Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x49, 0x65, 0x64, 0x76, 0x65, 0x64, 0x76, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV  = pdb.GetBytes(16);
            using (System.IO.MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return(clearText);
    }
Пример #26
0
        public void Initialize(ReadOnlySpan <byte> key, ReadOnlySpan <byte> iv, CipherMode mode, bool isDecrypting)
        {
            Debug.Assert(key.Length == Aes.KeySize128);
            Debug.Assert(iv.IsEmpty || iv.Length == Aes.BlockSize);

            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();

            if (aes == null)
            {
                throw new CryptographicException("Unable to create AES object");
            }
            aes.Key     = key.ToArray();
            aes.Mode    = mode;
            aes.Padding = PaddingMode.None;

            if (!iv.IsEmpty)
            {
                aes.IV = iv.ToArray();
            }

            _transform    = isDecrypting ? aes.CreateDecryptor() : aes.CreateEncryptor();
            _isDecrypting = isDecrypting;
        }
Пример #27
0
        private static byte[] EncryptStringToBytesAes(string plainText, byte[] key, byte[] iv)
        {
            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");
            }

            var data = plainText.FromHexString();

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.Padding = PaddingMode.None;
                aes.Mode    = CipherMode.CBC;
                aes.Key     = key;
                aes.IV      = iv;

                var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (var msEncrypt = new MemoryStream())
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(data, 0, data.Length);

                        return(msEncrypt.ToArray());
                    }
            }
        }
Пример #28
0
        // Central Method for string encryption
        public static string encrypt(string encryptString)
        {
            string EncryptionKey = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

            byte[] clearBytes = Encoding.Unicode.GetBytes(encryptString);
            using (System.Security.Cryptography.Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
                    0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76
                });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV  = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    encryptString = Convert.ToBase64String(ms.ToArray());
                }
            }
            return(encryptString);
        }
Пример #29
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="data">待加密的明文</param>
        /// <param name="password">加密公钥</param>
        /// <returns>返回一个Base64编码的密文</returns>
        public static string AesEncrypt(this string data, string password)
        {
            if (string.IsNullOrEmpty(data) || string.IsNullOrEmpty(password))
            {
                return(data);
            }

            byte[] keyBytes       = password.ToBytes();
            byte[] toEncryptArray = data.ToBytes();
            Aes    aesProvider    = Aes.Create();

            if (keyBytes.Length < aesProvider.KeySize)
            {
                throw new KeySizeException();
            }

            aesProvider.Key     = keyBytes;
            aesProvider.Mode    = CipherMode.ECB;
            aesProvider.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = aesProvider.CreateEncryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return(resultArray.ToBase64String());
        }
Пример #30
0
	public static bool TestTransform(Aes aes)
	{
		CipherMode[] modes;

		// AES allows CBC, ECB, and CFB modes.  Due to bug in RijndaelManaged, AesManaged does not
		// allow CFB.
		//
		if (aes is AesManaged)
			modes = new CipherMode[] {CipherMode.CBC, CipherMode.ECB};
		else
			modes = new CipherMode[] {CipherMode.CBC, CipherMode.ECB, CipherMode.CFB};

		ICryptoTransform encryptor;
		ICryptoTransform decryptor;

		foreach (CipherMode mode in modes)
		{
			aes.Mode = mode;

			encryptor = aes.CreateEncryptor();
			decryptor = aes.CreateDecryptor();

			if (encryptor.CanReuseTransform != true)
			{
				Console.WriteLine("Error - encryptor CanReuseTransform not true");
				return false;
			}

			if (decryptor.CanReuseTransform != true)
			{
				Console.WriteLine("Error - decryptor CanReuseTransform not true");
				return false;
			}

			if (encryptor.CanTransformMultipleBlocks != true)
			{
				Console.WriteLine("Error - encryptor CanTransformMultipleBlocks not true");
				return false;
			}

			if (decryptor.CanTransformMultipleBlocks != true)
			{
				Console.WriteLine("Error - decryptor CanTransformMultipleBlocks not true");
				return false;
			}

			if (encryptor.InputBlockSize != 16)
			{
				Console.WriteLine("Error - encryptor InputBlockSize not 16");
				return false;
			}

			if (decryptor.InputBlockSize != 16)
			{
				Console.WriteLine("Error - decryptor InputBlockSize not 16");
				return false;
			}

			if (encryptor.OutputBlockSize != 16)
			{
				Console.WriteLine("Error - encryptor OutputBlockSize not 16");
				return false;
			}

			if (decryptor.OutputBlockSize != 16)
			{
				Console.WriteLine("Error - decryptor OutputBlockSize not 16");
				return false;
			}
		}

		return true;
	}
Пример #31
0
        /// <summary>
        /// Encrypt a byte array by using the AES algorightm.
        /// <para>The input is: [data]</para>
        /// <para>The output is: [Magic Number (4 bytes)] [AES IV (16 bytes)] [AES(data) (xx bytes)] [HMAC(IV || AES(data)) (32 bytes)]</para>
        /// </summary>
        public static byte[] Encrypt(byte[] content, Aes aes)
        {
            using (MemoryStream outputStream = new MemoryStream()) {
                // Write the magic number
                outputStream.Write (MAGIC_NUMBER, 0, 4);

                using (MemoryStream cypherStream = new MemoryStream()) {
                    // Write the IV
                    cypherStream.Write (aes.IV, 0, 16);

                    // Write the AES encrypted content
                    using (ICryptoTransform transform = aes.CreateEncryptor ()) {
                        using (CryptoStream cryptoStream = new CryptoStream(cypherStream, transform, CryptoStreamMode.Write)) {
                            cryptoStream.Write (content, 0, content.Length);
                            cryptoStream.Flush ();
                            cryptoStream.Close ();
                        }
                    }

                    // Collect cypher result
                    cypherStream.Flush ();
                    cypherStream.Close ();
                    byte[] cypherBytes = cypherStream.ToArray ();

                    // Write the cypher
                    outputStream.Write (cypherBytes, 0, cypherBytes.Length);

                    // Compute the HMAC of the cypher
                    using (HMACSHA256 hmac = new HMACSHA256 (DeriveKey (aes.Key))) {
                        byte[] hmacBytes = hmac.ComputeHash (cypherBytes);

                        // Write the HMAC
                        outputStream.Write (hmacBytes, 0, hmacBytes.Length);
                    }
                }

                outputStream.Flush ();
                outputStream.Close ();
                byte[] outputBytes = outputStream.ToArray ();

                return outputBytes;
            }
        }
Пример #32
0
 public static ICryptoTransform getEncryptor(Aes aes)
 {
     return aes.CreateEncryptor(aes.Key, aes.IV);
 }
            internal AesCbcHmacSha2Encryptor( string name, byte[] key, byte[] iv, byte[] associatedData )
            {
                // Split the key to get the AES key, the HMAC key and the HMAC object
                byte[] aesKey;

                GetAlgorithmParameters( name, key, out aesKey, out _hmac_key, out _hmac );

                // Create the AES provider
                _aes = Aes.Create();

                _aes.Mode    = CipherMode.CBC;
                _aes.Padding = PaddingMode.PKCS7;
                _aes.KeySize = aesKey.Length * 8;
                _aes.Key     = aesKey;
                _aes.IV      = iv;

                _inner = _aes.CreateEncryptor();

                _associated_data_length = ConvertToBigEndian( associatedData.Length * 8 );

                // Prime the hash.
                _hmac.TransformBlock( associatedData, 0, associatedData.Length, associatedData, 0 );
                _hmac.TransformBlock( iv, 0, iv.Length, iv, 0 );
            }
        /// <summary>
        /// Encrypts data.
        /// </summary>
        /// <param name="aes">Aes object.</param>
        /// <param name="content">Content to be encrypted.</param>
        /// <param name="key">Encryption key.</param>
        /// <param name="iv">Initial vector.</param>
        /// <returns>Encrypted data.</returns>
        public static byte[] Encrypt(Aes aes, byte[] content, byte[] key, byte[] iv)
        {
            var encryptor = aes.CreateEncryptor(key, iv);

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    cs.Write(content, 0, content.Length);
                }
                return ms.ToArray();
            }
        }
Пример #35
0
	public static bool TestTransform(Aes aes)
	{
		ICryptoTransform encryptor;
		ICryptoTransform decryptor;

		encryptor = aes.CreateEncryptor();
		decryptor = aes.CreateDecryptor();

		if (encryptor.CanReuseTransform != true)
		{
			Console.WriteLine("Error - encryptor CanReuseTransform not true");
			return false;
		}

		if (decryptor.CanReuseTransform != true)
		{
			Console.WriteLine("Error - decryptor CanReuseTransform not true");
			return false;
		}

		if (encryptor.CanTransformMultipleBlocks != true)
		{
			Console.WriteLine("Error - encryptor CanTransformMultipleBlocks not true");
			return false;
		}

		if (decryptor.CanTransformMultipleBlocks != true)
		{
			Console.WriteLine("Error - decryptor CanTransformMultipleBlocks not true");
			return false;
		}

		if (encryptor.InputBlockSize != 16)
		{
			Console.WriteLine("Error - encryptor InputBlockSize not 16");
			return false;
		}

		if (decryptor.InputBlockSize != 16)
		{
			Console.WriteLine("Error - decryptor InputBlockSize not 16");
			return false;
		}

		if (encryptor.OutputBlockSize != 16)
		{
			Console.WriteLine("Error - encryptor OutputBlockSize not 16");
			return false;
		}

		if (decryptor.OutputBlockSize != 16)
		{
			Console.WriteLine("Error - decryptor OutputBlockSize not 16");
			return false;
		}

		return true;
	}
Пример #36
0
	// AES allows CBC, ECB, and CFB modes.  Due to bug in RijndaelManaged, AesManaged does not
	// allow CFB.
	//
	public static bool TestModes(Aes aes)
	{
		if (aes.Mode != CipherMode.CBC)
		{
			Console.WriteLine("Error - default Mode not CBC");
			return false;
		}

		aes.CreateEncryptor().TransformFinalBlock(new byte[10], 0, 10);

		aes.Mode = CipherMode.ECB;
		aes.CreateEncryptor().TransformFinalBlock(new byte[10], 0, 10);

		try
		{
			aes.Mode = CipherMode.CFB;
			aes.CreateEncryptor().TransformFinalBlock(new byte[10], 0, 10);

			if (aes is AesManaged)
			{
				Console.WriteLine("Error - CFB mode allowed");
				return false;
			}
		}
		catch (CryptographicException)
		{
			if (!(aes is AesManaged))
			{
				Console.WriteLine("Error - CFB mode not allowed");
				return false;
			}
		}

		try
		{
			aes.Mode = CipherMode.CTS;
			aes.CreateEncryptor().TransformFinalBlock(new byte[10], 0, 10);
			
			Console.WriteLine("Error - CTS mode allowed");
			return false;
		}
		catch (CryptographicException)
		{
		}

		try
		{
			aes.Mode = CipherMode.OFB;
			aes.CreateEncryptor().TransformFinalBlock(new byte[10], 0, 10);
			
			Console.WriteLine("Error - OFB mode allowed");
			return false;
		}
		catch (CryptographicException)
		{
		}

		return true;
	}
Пример #37
0
        /**********************************************************************************************************
        *	void MainWindow_Closing
        *       Purpose:	Fires when the window is to be closed. Prompts the user to save changes.
        *					Encrypts the file using AES using a SHA-3 key derived from the MasterPassword.
        **********************************************************************************************************/
        void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult save = MessageBox.Show("Save your data?", "Save Prompt", MessageBoxButton.YesNoCancel);

            if (save == MessageBoxResult.No)
            {
                return;
            }
            else if (save == MessageBoxResult.Cancel)
            {
                e.Cancel = true;
                return;
            }

            // Need 128 bits password for the encryption key.
            ApplicationEntry self     = new ApplicationEntry("MasterPass", 128 / sizeof(char) / 8, 0, true, true, true, false);
            HashedPassword   fileName = self.GeneratePassword(MasterPassword);
            HashedPassword   aesKey   = self.GeneratePassword(MasterPassword);
            HashedPassword   aesIV    = self.GeneratePassword(MasterPassword);

            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();

            // Even if aes is broken the master password is unrecoverable.
            aes.Key     = Encoding.Unicode.GetBytes(aesKey.Password);
            aes.IV      = Encoding.Unicode.GetBytes(aesIV.Password);
            aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            ICryptoTransform encryptor = aes.CreateEncryptor();

            // Open the file
            using (FileStream outputStream = new FileStream(fileName.Password + ".pass", FileMode.OpenOrCreate))
            {
                // Use a safe to file encryption method
                using (CryptoStream csEncrypt = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write))
                {
                    // Convert the object to a byte array
                    using (MemoryStream objectStream = new MemoryStream())
                    {
                        // Throw the userData into the object stream.
                        IFormatter formatter = new BinaryFormatter();
                        formatter.Serialize(objectStream, Data);

                        objectStream.Position = 0;

                        byte[] buffer    = new byte[1024];
                        int    bytesRead = objectStream.Read(buffer, 0, buffer.Length);

                        // While there are still more bytes to write
                        while (bytesRead > 0)
                        {
                            // Write them to the file.
                            csEncrypt.Write(buffer, 0, bytesRead);
                            bytesRead = objectStream.Read(buffer, 0, buffer.Length);
                        }

                        // Flush the final block.
                        csEncrypt.FlushFinalBlock();
                    }
                }
            }
        }
Пример #38
0
        public SegmentReader(Stream _bsstr, Aes rdale, int _fragsize)
        {
            
            _rdale = rdale as AesManaged;
            
            basestream = _bsstr;
            fragsize = _fragsize;
            reader = rdale.CreateDecryptor();
            writer = rdale.CreateEncryptor();
#if !SINGLE_THREADED
            mthread = new System.Threading.Thread(thetar);
            mthread.Start();
#endif
        }
Пример #39
0
        public byte[] EncodeBytes(byte[] e)
        {
            var es = new PerformanceCounter();

            return(Transform(_encoder ?? rsa.CreateEncryptor(), e));
        }
Пример #40
0
	public static byte[] GetPaddingBytes(Aes aes, PaddingMode mode, int offset)
	{
		byte[] originalData = new byte[BlockSizeBytes + offset];
		new Random().NextBytes(originalData);

		aes.Padding = mode;
		byte[] encryptedData = aes.CreateEncryptor().TransformFinalBlock(originalData, 0, originalData.Length);

		aes.Padding = PaddingMode.None;
		byte[] decryptedData = aes.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);

		byte[] paddingBytes = new byte[decryptedData.Length - BlockSizeBytes - offset];
		Array.Copy(decryptedData, BlockSizeBytes + offset, paddingBytes, 0, decryptedData.Length - BlockSizeBytes - offset);
		
		return paddingBytes;
	}
Пример #41
0
 public override ICryptoTransform CreateEncryptor() => _impl.CreateEncryptor();
Пример #42
0
        public static void WriteMessageStream(MemoryStream outStream, Message outMessage, string sessionKey, Aes aes, bool encrypt)
        {
            outMessage.ReplaceControlValue(Message.TimestampControlValueName, DateTime.Now.ToUniversalTime().ToString());
            outMessage.ReplaceControlValue(Message.SessionKeyControlValueName, sessionKey);
            if (encrypt)
            {
                aes.GenerateIV();

                StreamUtilities.WriteStringToMemoryStream(outStream, aes.IV.Length + "!");
                outStream.Write(aes.IV, 0, aes.IV.Length);
                StreamUtilities.RunCryptoTransform(outMessage.Serialize(), aes.CreateEncryptor(), outStream, true);
            }
            else
            {
                outMessage.Serialize(outStream);
            }
        }