Ejemplo n.º 1
0
        public EncryptionTests()
        {
            var aescsp = new AesCryptoServiceProvider();

            aescsp.GenerateKey();
            aescsp.GenerateIV();
            _correctKey    = aescsp.Key;
            _correctVector = aescsp.IV;

            aescsp.GenerateKey();
            aescsp.GenerateIV();

            _wrongKey    = aescsp.Key;
            _wrongVector = aescsp.IV;
        }
Ejemplo n.º 2
0
        bool SessionTest_CloseWithCreateKeyObjects_internal(string svcProvider)
        {
            bool res = true;

            CryptoKey key;

            using (Session sess = new Session(svcProvider, MechanismType.AES_CBC))
            {
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider(sess);

                aes.GenerateKey();

                key = aes.Key;

                SymmetricTestHelper.Test_EncryptUpdate(aes);
            }

            try
            {
                using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider(svcProvider))
                {
                    aes.Key = key;

                    SymmetricTestHelper.Test_EncryptUpdate(aes);
                }

                res = false;
            }
            catch (Exception)
            {
            }

            return(res);
        }
Ejemplo n.º 3
0
        public static byte[] encrypt(string receiverPublicKey, byte[] plaintext)
        {
            byte[] encryptedText;

            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            aes.KeySize = 256;
            aes.Mode    = CipherMode.CBC;
            aes.GenerateKey();
            aes.GenerateIV();

            ICryptoTransform encryptor = aes.CreateEncryptor();

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    csEncrypt.Write(plaintext, 0, plaintext.Length);
                    csEncrypt.FlushFinalBlock();
                    encryptedText = msEncrypt.ToArray();
                }
            }

            byte[] encryptedKey = Account.encryptData(receiverPublicKey, aes.Key);

            byte[] ciphertext = new byte[1 + encryptedKey.Length + aes.IV.Length + encryptedText.Length];
            ciphertext[0] = (byte)encryptedKey.Length;
            Buffer.BlockCopy(encryptedKey, 0, ciphertext, 1, encryptedKey.Length);
            Buffer.BlockCopy(aes.IV, 0, ciphertext, 1 + encryptedKey.Length, aes.IV.Length);
            Buffer.BlockCopy(encryptedText, 0, ciphertext, 1 + encryptedKey.Length + aes.IV.Length, encryptedText.Length);

            return(ciphertext);
        }
Ejemplo n.º 4
0
        public static string GetKey(string humanKey = null, string keyInit = null)
        {
            byte[] keyString;
            int    keyStringSize = 0;

            if (humanKey == null)
            {
                humanKey = DataAccess.GetIdentificator();
            }
            using (AesCryptoServiceProvider aesCryptoProvider = new AesCryptoServiceProvider())
            {
                if (keyInit != null)
                {
                    keyString     = Encoding.Unicode.GetBytes(keyInit);
                    keyStringSize = aesCryptoProvider.Key.Length;
                    keyString     = keyString.Take(keyStringSize).ToArray();
                }
                else
                {
                    aesCryptoProvider.GenerateKey();
                    keyString = aesCryptoProvider.Key;
                }
            }
            return(XORStrings(humanKey, keyString));
        }
Ejemplo n.º 5
0
        public SecureKeyPair()
        {
            RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider();

            //Generate Private RSA Key
            RSAParameters privateKey = RSA.Create().ExportParameters(true);

            rsaCSP.ImportParameters(privateKey);
            Rsa_privateKey = rsaCSP.ToXmlString(true);

            //Generate Public RSA Key
            RSAParameters publicKey = new RSAParameters();

            publicKey.Modulus  = privateKey.Modulus;
            publicKey.Exponent = privateKey.Exponent;
            rsaCSP.ImportParameters(publicKey);
            Rsa_publicKey = rsaCSP.ToXmlString(false);

            AesCryptoServiceProvider aesCSP = new AesCryptoServiceProvider();

            aesCSP.KeySize   = 128;
            aesCSP.BlockSize = 128;
            aesCSP.GenerateKey();

            byte[] keyBytes = aesCSP.Key;
            Aes_key = Convert.ToBase64String(keyBytes);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 动态生成密钥,并对明文进行AES加密
        /// </summary>
        /// <param name="sCrypto">明文</param>
        /// <returns></returns>

        public bool Encrypt(string sCrypto, bool containKey, out string str)
        {
            m_aesCryptoServiceProvider.GenerateKey();
            var key = m_aesCryptoServiceProvider.Key;

            return(Encrypt(sCrypto, key, containKey, out str));
        }
Ejemplo n.º 7
0
        public byte[] Encrypt(byte[] data, string RSAKey)
        {
            //Generate random 256 bit AES key
            using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider())
            {
                AES.KeySize = 256;
                AES.GenerateKey();
                AES.GenerateIV();

                //Encrypt the data with aes
                using (MemoryStream memStream = new MemoryStream())
                {
                    using (
                        CryptoStream cryptoStream = new CryptoStream(memStream, AES.CreateEncryptor(),
                                                                     CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(data, 0, data.Length);
                        cryptoStream.FlushFinalBlock();
                        this.data = memStream.ToArray();
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }

                //Encrypt the AES key with RSA
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    rsa.FromXmlString(RSAKey);
                    sessionKey = rsa.Encrypt(AES.Key, true);
                }

                IV = AES.IV;
                return(AES.Key);
            }
        }
            static void Main(string[] args)
            {
                /* */
                AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider();

                aesProvider.KeySize = 256;
                aesProvider.Mode    = CipherMode.CBC;
                aesProvider.Padding = PaddingMode.PKCS7;
                aesProvider.GenerateKey();

                RunApp();

                Console.WriteLine("Cipher file... Press Enter");
                Console.ReadLine();

                CipherFileWithAES256(filePath, ByteArrayToBase64String(aesProvider.Key));

                try
                {
                    Console.WriteLine("Ciphered sucess... Press enter to continue");
                    Console.ReadLine();
                    RunApp();
                } catch (Exception)
                {
                    Console.WriteLine("Invalid file... Ciphered");
                }

                Console.WriteLine("Decipher file... Press Enter");
                Console.ReadLine();
                DecipherFileWithAES256(filePath, ByteArrayToBase64String(aesProvider.Key));

                Console.WriteLine("Run againe... Press Enter");
                Console.ReadLine();
                RunApp();
            }
        /// <summary>
        /// Event that fires when the aes encrypt button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAESEncrypt_Click(object sender, RoutedEventArgs e)
        {
            byte[] cipherText;

            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.KeySize = ((ListItem)this.cboAESKeySize.SelectedItem).Value;
                aes.Mode    = (CipherMode)((ListItem)this.cboAESMode.SelectedItem).Value;
                aes.Padding = (PaddingMode)((ListItem)this.cboAESPadding.SelectedItem).Value;
                //aes.BlockSize = ;

                aes.GenerateIV();
                this.txtAESIV.Text = Convert.ToBase64String(aes.IV);

                //generate the key and insert it into the text box
                aes.GenerateKey();
                this.txtAESPassword.Text = Convert.ToBase64String(aes.Key);

                byte[] byteInputText = Convert.FromBase64String(this.txtAESInput.Text);

                using (ICryptoTransform crypto = aes.CreateEncryptor())
                {
                    cipherText = crypto.TransformFinalBlock(byteInputText, 0, byteInputText.Length);
                    aes.Clear();
                }
            }

            this.txtAESOutput.Text = Convert.ToBase64String(cipherText);
        }
Ejemplo n.º 10
0
        public static byte[] InitializeSymmetricFileSystemKey()
        {
            if (Debugger.IsAttached && Path.DirectorySeparatorChar == '\\') // check if we're debugging - double check to overdo security
            {
                return(new byte[32]);                                       // can't write to /etc/swarmops in the debugger; return an all-zero key while debugging
            }

            if (File.Exists("/etc/swarmops/symmetricKey.config"))
            {
                if (!File.ReadAllText("/etc/swarmops/symmetricKey.config").StartsWith("UNINIT"))    // the word "Uninitialized" in caps
                {
                    throw new InvalidOperationException("Can't overwrite encryption key - BAD BAD BAD code!");
                }
            }

            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.KeySize = 256;
                aes.GenerateKey();
                byte[] key = aes.Key;

                string keyString = Convert.ToBase64String(key);
                File.WriteAllText("/etc/swarmops/symmetricKey.config", keyString, Encoding.ASCII);

                return(key);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Adiciona um membro novo e respetivas chaves
        /// </summary>
        /// <param name="Membro"></param>
        public void AddMember(string Membro)
        {
            if (!Members.Contains(Membro))
            {
                Members.Add(Membro);
            }
            if (Members.Count > 1)
            {
                int j = Members.Count - 1;
                for (int i = 0; i < j; i++)
                {
                    AesCryptoServiceProvider aes = new AesCryptoServiceProvider {
                        KeySize = 256
                    };
                    aes.GenerateKey();
                    aes.GenerateIV();

                    Keys aux = new Keys
                    {
                        Member  = i,
                        Member2 = j,
                        Key     = aes.Key,
                        Iv      = aes.IV
                    };
                    GenKeys.Add(aux);
                }
            }
        }
Ejemplo n.º 12
0
        public static string getEncryptedAssetData(string data, out string encryptionKey)
        {
            string result = null;

            byte[] encrypted;
            using (var aes = new AesCryptoServiceProvider())
            {
                aes.KeySize = 256;
                aes.GenerateKey();
                encryptionKey = Convert.ToBase64String(aes.Key);
                aes.GenerateIV();
                var enc = aes.CreateEncryptor(aes.Key, aes.IV);
                using (var msEncrypt = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(msEncrypt, enc, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(cryptoStream))
                        {
                            swEncrypt.Write(data);
                        }
                    }
                    encrypted = msEncrypt.ToArray();
                }
                result = Convert.ToBase64String(encrypted);
                result = result + "|" + Convert.ToBase64String(aes.IV);
            }
            return(result);
        }
Ejemplo n.º 13
0
 public void GenerateSessionKey()
 {
     rijndaelManaged = new AesCryptoServiceProvider();
     rijndaelManaged.GenerateKey();
     rijndaelManaged.GenerateIV();
     rijndaelManaged.Mode = CipherMode.CFB;
 }
Ejemplo n.º 14
0
        } //computes hash value of folder name containing input file name

        private static string GetAESHash(string text)
        {
            //create variables for computing hash and making it a string
            UnicodeEncoding UniCode = new UnicodeEncoding();

            byte[] HashResult;
            byte[] msg        = UniCode.GetBytes(text);
            Aes    hashString = new AesCryptoServiceProvider();

            //generate a weak KEY and Initialization Vector for the hash algorithm
            hashString.GenerateKey();
            hashString.GenerateIV();
            ICryptoTransform encryptor = hashString.CreateEncryptor(hashString.Key, hashString.IV);
            string           Str       = "";

            //compute hash with AES module and format output as string
            //convert bytes in HashResult to string values
            HashResult = encryptor.TransformFinalBlock(msg, 0, msg.Length);
            foreach (byte x in HashResult)
            {
                Str += String.Format("{0:x2}", x);
            }

            //clear excess resource usage
            hashString.Clear();
            return(Str);
        } //compute hash from arguments and return hash value as string
Ejemplo n.º 15
0
        private static byte[] GenerateKey()
        {
            using var cryptoServiceProvider = new AesCryptoServiceProvider();
            cryptoServiceProvider.GenerateKey();

            return(cryptoServiceProvider.Key);
        }
Ejemplo n.º 16
0
        public static void TestShims()
        {
            using (var alg = new AesCryptoServiceProvider())
            {
                alg.BlockSize = 128;
                Assert.Equal(128, alg.BlockSize);

                var emptyIV = new byte[alg.BlockSize / 8];
                alg.IV = emptyIV;
                Assert.Equal(emptyIV, alg.IV);
                alg.GenerateIV();
                Assert.NotEqual(emptyIV, alg.IV);

                var emptyKey = new byte[alg.KeySize / 8];
                alg.Key = emptyKey;
                Assert.Equal(emptyKey, alg.Key);
                alg.GenerateKey();
                Assert.NotEqual(emptyKey, alg.Key);

                alg.KeySize = 128;
                Assert.Equal(128, alg.KeySize);

                alg.Mode = CipherMode.ECB;
                Assert.Equal(CipherMode.ECB, alg.Mode);

                alg.Padding = PaddingMode.PKCS7;
                Assert.Equal(PaddingMode.PKCS7, alg.Padding);
            }
        }
Ejemplo n.º 17
0
        public List <byte[]> GerarListaDeMensagens()
        {
            List <byte[]> listaMes = new List <byte[]>();

            Random randNum = new Random();



            for (int i = 0; i < 256; i++)
            {
                Random r  = new Random();
                int    xi = r.Next(45, 300);

                AesCryptoServiceProvider aes = new AesCryptoServiceProvider {
                    KeySize = 256
                };
                aes.GenerateKey();
                string puzzle   = "puzzle" + xi;
                string ki       = Convert.ToBase64String(aes.Key);
                string mensagem = (puzzle + "|" + ki);

                listaMes.Add(Encoding.UTF8.GetBytes(mensagem));

                Console.WriteLine("mensagem " + i + ": " + listaMes[i]);
            }
            return(listaMes);
        }
Ejemplo n.º 18
0
        public static Tuple <byte[], byte[], byte[]> EncryptAES(byte[] toEncrypt, int keySize, CipherMode mode, PaddingMode padding)
        {
            byte[] iv;
            byte[] key;
            byte[] data;
            using (var provider = new AesCryptoServiceProvider())
            {
                provider.KeySize = keySize;
                provider.GenerateKey();
                provider.GenerateIV();
                provider.Mode    = mode;
                provider.Padding = padding;
                using (var encryptor = provider.CreateEncryptor())
                {
                    var ms = new MemoryStream();
                    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        cs.Write(toEncrypt, 0, toEncrypt.Length);
                        cs.FlushFinalBlock();
                    }
                    iv   = provider.IV;;
                    key  = provider.Key;
                    data = ms.ToArray();
                }
            }

            return(new Tuple <byte[], byte[], byte[]>(iv, key, data));
        }
Ejemplo n.º 19
0
 /// <summary>
 /// 动态生成密匙,并对明文进行AES加密
 /// </summary>
 /// <param name="plaintext">明文</param>
 /// <returns></returns>
 public string Encrypt(string plaintext)
 {
     byte[] key = new byte[CRYPTO_KEY_LENGTH];
     _aesCryptoServiceProvider.GenerateKey();
     key = _aesCryptoServiceProvider.Key;
     return(Encrypt(plaintext, key));
 }
Ejemplo n.º 20
0
 private void Init(long startTime, long period, int numberOfEntries, long replicationDuration)
 {
     if (numberOfEntries > 0)
     {
         using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider())
         {
             int  num   = aesCryptoServiceProvider.Key.Length + aesCryptoServiceProvider.IV.Length;
             long ticks = (Canary15DataSegment.UtcNow + Canary15DataSegment.ReplicationDuration).Ticks;
             if (startTime < ticks)
             {
                 startTime = ticks;
             }
             this.header = new Canary15DataSegment.DataSegmentHeader(startTime, ticks, Canary15DataSegment.UtcNowTicks, period, numberOfEntries, num, replicationDuration);
             this.data   = new byte[numberOfEntries][];
             for (int i = 0; i < numberOfEntries; i++)
             {
                 aesCryptoServiceProvider.GenerateKey();
                 aesCryptoServiceProvider.GenerateIV();
                 this.data[i] = new byte[num];
                 aesCryptoServiceProvider.Key.CopyTo(this.data[i], 0);
                 aesCryptoServiceProvider.IV.CopyTo(this.data[i], aesCryptoServiceProvider.Key.Length);
             }
             this.header.ComputeState(this.data);
             this.Trace(0, "Init()");
         }
     }
 }
Ejemplo n.º 21
0
        /**
         * 生成指定加密位数的AES SecretKey
         *
         * @param bits
         *          加密位数
         *
         * @return
         *              SecretKey
         *
         */
        public SecretKey getKey(int bits)
        {
            if (bits < 128)
            {
                return(null);
            }

            try
            {
                AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider();
                aesProvider.KeySize = bits;
                aesProvider.GenerateKey();

                return(new SecretKey {
                    Key = aesProvider.Key, Algorithym = "AES"
                });
            }
            catch (Exception ex)
            {
                log("生成AES SecretKey出错:");

                //ex.printStackTrace();

                return(null);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// 获取加密和解密时用的key和iv
        /// </summary>
        /// <param name="providerType">算法类型</param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        public static void GenerateCryptKeyAndIV(CryptProviderType providerType, out byte[] key, out byte[] iv)
        {
            key = null;
            iv  = null;
            switch (providerType)
            {
            case CryptProviderType.AES:
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                aes.GenerateKey();
                aes.GenerateIV();
                key = aes.Key;
                iv  = aes.IV;
                return;

            case CryptProviderType.DES:
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.GenerateKey();
                des.GenerateIV();
                key = des.Key;
                iv  = des.IV;
                return;

            case CryptProviderType.TripleDES:
                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                tdes.GenerateKey();
                tdes.GenerateIV();
                key = tdes.Key;
                iv  = tdes.IV;
                return;

            default:
                return;
            }
        }
Ejemplo n.º 23
0
            public void Should_fail_if_not_supported()
            {
                using (var provider = new AesCryptoServiceProvider())
                {
                    provider.GenerateKey();
                    provider.GenerateIV();

                    using (ICryptoTransform encryptor = provider.CreateEncryptor())
                    {
                        byte[] bytes = Encoding.UTF8.GetBytes("secret");

                        byte[] password = encryptor.TransformFinalBlock(bytes, 0, bytes.Length);

                        var builder = new RoutingSlipBuilder(NewId.NextGuid());
                        builder.AddActivity("GetFile", new Uri("rabbitmq://localhost/execute_getfile"), new
                        {
                            Username = "******",
                            Password = password,
                        });

                        RoutingSlip routingSlip = builder.Build();

                        Console.WriteLine(routingSlip.ToJsonString());
                    }
                }
            }
Ejemplo n.º 24
0
        static int Handle(bool onlyIV, bool onlyKey)
        {
            if (onlyIV && onlyKey)
            {
                throw new ArgumentException("Unable to exclusively print both");
            }

            using (var provider = new AesCryptoServiceProvider())
            {
                provider.GenerateKey();
                provider.GenerateIV();

                if (!onlyKey)
                {
                    Console.WriteLine($"IV: \"{Convert.ToBase64String(provider.IV)}\"");
                }

                if (!onlyIV)
                {
                    Console.WriteLine($"Key: \"{Convert.ToBase64String(provider.Key)}\"");
                }
            }

            return(0);
        }
Ejemplo n.º 25
0
        public async Task <string> GenerateHash(string url)
        {
            var arr = url.ToCharArray();

            Array.Reverse(arr);
            var reverseUrl = new string(arr);

            byte[] encrypted;
            using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
            {
                aesAlg.GenerateKey();
                aesAlg.GenerateIV();

                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))
                        {
                            await swEncrypt.WriteAsync(reverseUrl);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            string hash = ToBase64String(encrypted);

            return(hash);
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            string message = "https://10.81.11.203:8095/WSBienestarAzteca/BienestarAzteca/operacionesGobierno/validaRetiro";

            using (var aes = new AesCryptoServiceProvider())
            {
                aes.BlockSize = 128;
                aes.KeySize   = 256;

                //aes.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
                //aes.IV = System.Text.UTF8Encoding.ASCII.GetBytes(iv);

                aes.GenerateIV();
                aes.GenerateKey();

                aes.Mode    = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;

                Console.WriteLine(aes.Key.Length);

                byte[] encrypted = AESCrypto(Mode.ENCRYPT, aes, Encoding.UTF8.GetBytes(message));
                Console.WriteLine("Encrypted text: " + BitConverter.ToString(encrypted).Replace("-", ""));

                byte[] decrypted = AESCrypto(Mode.DECRYPT, aes, encrypted);
                Console.WriteLine("Decryp text: " + Encoding.UTF8.GetString(decrypted));
            }
        }
Ejemplo n.º 27
0
        public RemoteComputer(Socket _clientSocket)
        {
            clientSocket = _clientSocket;
            AES          = new AesCryptoServiceProvider();
            AES.GenerateKey();
            AES.GenerateIV();

            byte[] data = new byte[1000];

            int lengthOfMessage = clientSocket.Receive(data);

            MessageEncrypt.EncryptAndSendAESKey(clientSocket, data, AES, lengthOfMessage);

            lengthOfMessage = clientSocket.Receive(data);
            ComputerName    = CommandMessage.GetNameFromByte(data, lengthOfMessage);
            ComputerName    = MessageEncrypt.AESDecrypt(ComputerName, AES);

            lengthOfMessage = clientSocket.Receive(data);
            ComputerUser    = CommandMessage.GetNameFromByte(data, lengthOfMessage);
            ComputerUser    = MessageEncrypt.AESDecrypt(ComputerUser, AES);

            lengthOfMessage = clientSocket.Receive(data);
            ClientIP        = CommandMessage.GetNameFromByte(data, lengthOfMessage);
            ClientIP        = MessageEncrypt.AESDecrypt(ClientIP, AES);

            Thread ReciveScreenImageThread = new Thread(ReciveScreenImage);

            ReciveScreenImageThread.IsBackground = true;
            ReciveScreenImageThread.Start(); //запускаем поток
        }
Ejemplo n.º 28
0
        public static byte[] GenerateKey(SymmetricAlgorithmType yourType, int keySize)
        {
            byte[]             outBytes;
            SymmetricAlgorithm key;

            switch (yourType)
            {
            case SymmetricAlgorithmType.DES:
                key = new DESCryptoServiceProvider();
                break;

            case SymmetricAlgorithmType.TripleDES:
                key = new TripleDESCryptoServiceProvider();
                break;

            case SymmetricAlgorithmType.AES:
                key = new AesCryptoServiceProvider();
                break;

            default:
                throw new Exception("not support this encrypt type");
            }
            if (keySize > 0)
            {
                key.KeySize = keySize;
            }
            key.GenerateKey();
            outBytes = key.Key;
            key.Clear();
            return(outBytes);
        }
Ejemplo n.º 29
0
        public static Tuple <byte[], byte[], byte[]> EncryptAES(byte[] toEncrypt)
        {
            var toEncryptBytes = toEncrypt;

            using (var provider = new AesCryptoServiceProvider())
            {
                provider.KeySize = 256;
                provider.GenerateKey();
                provider.GenerateIV();
                provider.Mode    = CipherMode.CBC;
                provider.Padding = PaddingMode.PKCS7;
                using (var encryptor = provider.CreateEncryptor(provider.Key, provider.IV))
                {
                    using (var ms = new MemoryStream())
                    {
                        using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                        {
                            cs.Write(toEncryptBytes, 0, toEncryptBytes.Length);
                            cs.FlushFinalBlock();
                        }

                        return(new Tuple <byte[], byte[], byte[]> (provider.IV, provider.Key, ms.ToArray()));
                    }
                }
            }
        }
        public static void TestShims()
        {
            using (var alg = new AesCryptoServiceProvider())
            {
                alg.BlockSize = 128;
                Assert.Equal(128, alg.BlockSize);

                var emptyIV = new byte[alg.BlockSize / 8];
                alg.IV = emptyIV;
                Assert.Equal(emptyIV, alg.IV);
                alg.GenerateIV();
                Assert.NotEqual(emptyIV, alg.IV);

                var emptyKey = new byte[alg.KeySize / 8];
                alg.Key = emptyKey;
                Assert.Equal(emptyKey, alg.Key);
                alg.GenerateKey();
                Assert.NotEqual(emptyKey, alg.Key);

                alg.KeySize = 128;
                Assert.Equal(128, alg.KeySize);

                alg.Mode = CipherMode.ECB;
                Assert.Equal(CipherMode.ECB, alg.Mode);

                alg.Padding = PaddingMode.PKCS7;
                Assert.Equal(PaddingMode.PKCS7, alg.Padding);
            }
        }
Ejemplo n.º 31
0
    private static bool TestKeyGeneration()
    {
        try
        {
            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                // Try creating the other sized keys
                aes.KeySize = 128;
                if (aes.Key.Size != 128)
                {
                    return(false);
                }

                // Make sure consecutive reads don't change the key
                aes.GenerateKey();
                byte[] read1 = aes.Key.ExportKey(true);
                byte[] read2 = aes.Key.ExportKey(true);

                if (!CompareBytes(read1, read2))
                {
                    return(false);
                }
            }

            return(true);
        }
        catch
        {
            return(false);
        }
    }