private async Task <byte[]> AliceSendsDataAsync(string message)
        {
            WriteLine($"Alice sends message: {message}");
            byte[] rawData       = Encoding.UTF8.GetBytes(message);
            byte[] encryptedData = null;

            using (var aliceAlgorithm = new ECDiffieHellmanCng(_aliceKey))
                using (CngKey bobPubKey = CngKey.Import(_bobPubKeyBlob,
                                                        CngKeyBlobFormat.EccPublicBlob))
                {
                    byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);
                    WriteLine("Alice creates this symmetric key with " +
                              $"Bobs public key information: { Convert.ToBase64String(symmKey)}");

                    using (var aes = new AesCryptoServiceProvider())
                    {
                        aes.Key = symmKey;
                        aes.GenerateIV();
                        using (ICryptoTransform encryptor = aes.CreateEncryptor())
                            using (var ms = new MemoryStream())
                            {
                                // create CryptoStream and encrypt data to send
                                using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                                {
                                    // write initialization vector not encrypted
                                    await ms.WriteAsync(aes.IV, 0, aes.IV.Length);

                                    await cs.WriteAsync(rawData, 0, rawData.Length);
                                }
                                encryptedData = ms.ToArray();
                            }
                        aes.Clear();
                    }
                }
            WriteLine($"Alice: message is encrypted: {Convert.ToBase64String(encryptedData)}");;
            WriteLine();
            return(encryptedData);
        }
Exemplo n.º 2
0
        public static string AESDecrypt(string hexString, string key = "56dPz3VDYwGpJYqe7dFG0g==")
        {
            try
            {
                using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
                {
                    aesProvider.Key     = Convert.FromBase64String(key);
                    aesProvider.Mode    = CipherMode.ECB;
                    aesProvider.Padding = PaddingMode.PKCS7;
                    using (ICryptoTransform cryptoTransform = aesProvider.CreateDecryptor())
                    {
                        hexString = hexString.ToLower();
                        byte[] byteArray = new byte[hexString.Length >> 1];
                        int    index     = 0;
                        for (int i = 0; i < hexString.Length; i++)
                        {
                            if (index > hexString.Length - 1)
                            {
                                continue;
                            }
                            byte highDit = (byte)(Digit(hexString[index], 16) & 0xFF);
                            byte lowDit  = (byte)(Digit(hexString[index + 1], 16) & 0xFF);
                            byteArray[i] = (byte)(highDit << 4 | lowDit & 0xFF);
                            index       += 2;
                        }

                        byte[] inputBuffers = byteArray;
                        byte[] results      = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
                        aesProvider.Clear();
                        return(Encoding.UTF8.GetString(results));
                    }
                }
            }
            catch (Exception)
            {
                return(string.Empty);
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// Aes解密
 /// </summary>
 /// <param name="source">源字符串</param>
 /// <param name="key">aes密钥,长度必须32位</param>
 /// <returns>解密后的字符串</returns>
 public static string DecryptAes(string source, string key)
 {
     try
     {
         using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
         {
             aesProvider.Key     = GetAesKey(key);
             aesProvider.Mode    = CipherMode.ECB;
             aesProvider.Padding = PaddingMode.PKCS7;
             using (ICryptoTransform cryptoTransform = aesProvider.CreateDecryptor())
             {
                 byte[] inputBuffers = Convert.FromBase64String(source);
                 byte[] results      = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
                 aesProvider.Clear();
                 return(Encoding.UTF8.GetString(results));
             }
         }
     }
     catch
     {
         return(null);
     }
 }
Exemplo n.º 4
0
        public static string DecryptString(string toDecrypt)
        {
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
            byte[] IV             = UTF8Encoding.UTF8.GetBytes("zT$3qIjUR$4rIj45");
            string decryptionKey  = "b14ca5898a4e4133bbce2ea2315a1910";

            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(decryptionKey);

            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            aes.Key = keyArray;
            //aes.KeySize = 256;
            aes.BlockSize = 128;
            aes.IV        = IV;
            aes.Padding   = PaddingMode.PKCS7;

            aes.Mode = CipherMode.CBC;
            var transform   = aes.CreateDecryptor();
            var outputArray = transform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            aes.Clear();
            return(UTF8Encoding.UTF8.GetString(outputArray));
        }
Exemplo n.º 5
0
        public TestSymmetricKeyProvider(params string[] ids)
        {
            _keys = new Dictionary <string, TestSymmetricKey>();

            foreach (var id in ids.Concat(new[] { "default" }).Distinct())
            {
                byte[] key;
                byte[] iv;

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

                    key = provider.Key;
                    iv  = provider.IV;

                    provider.Clear();
                }

                _keys.Add(id, new TestSymmetricKey(key, iv));
            }
        }
Exemplo n.º 6
0
        public static string DecryptAES(string hash, string key, bool hashKey = true)
        {
            if (hash == null || key == null)
            {
                return(null);
            }

            var keyArray       = HexStringToByteArray(hashKey ? HashMD5(key) : key);
            var toEncryptArray = HexStringToByteArray(hash);

            var aes = new AesCryptoServiceProvider
            {
                Key     = keyArray,
                Mode    = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };

            var cTransform  = aes.CreateDecryptor();
            var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            aes.Clear();
            return(Encoding.UTF8.GetString(resultArray));
        }
Exemplo n.º 7
0
    /// <summary>
    /// AES解密
    /// </summary>
    /// <param name="data"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string DeAES(byte[] content, string key)
    {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(Encoding.ASCII.GetBytes(key));
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();

        using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
        {
            aesProvider.Key = enCodeFormat;
            aesProvider.Mode = CipherMode.ECB;
            aesProvider.Padding = PaddingMode.PKCS7;
            using (ICryptoTransform cryptoTransform = aesProvider.CreateDecryptor())
            {
                byte[] inputBuffers = content;
                byte[] results = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
                aesProvider.Clear();
                return Encoding.UTF8.GetString(results);
            }
        }
    }
Exemplo n.º 8
0
 /// <summary>
 /// 加密字节数组
 /// </summary>
 public static byte[] Encrypt(byte[] decodeBytes, string key, bool needIV = false)
 {
     decodeBytes.CheckNotNull("decodeBytes");
     using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
     {
         provider.Key     = CheckKey(key);
         provider.Padding = PaddingMode.PKCS7;
         provider.Mode    = CipherMode.ECB;
         byte[] ivBytes = { };
         if (needIV)
         {
             provider.Mode = CipherMode.CBC;
             provider.GenerateIV();
             ivBytes = provider.IV;
         }
         using (ICryptoTransform encryptor = provider.CreateEncryptor())
         {
             byte[] encodeBytes = encryptor.TransformFinalBlock(decodeBytes, 0, decodeBytes.Length);
             provider.Clear();
             return(needIV ? ivBytes.Concat(encodeBytes).ToArray() : encodeBytes);
         }
     }
 }
Exemplo n.º 9
0
        static string Encode(long value, byte[] key)
        {
            byte[] InputBuffer = new byte[16];
            byte[] OutputBuffer;
            unsafe
            {
                fixed(byte *pInputBuffer = InputBuffer)
                {
                    ((long *)pInputBuffer)[0] = value;
                    ((long *)pInputBuffer)[1] = value;
                }
            }
            AesCryptoServiceProvider Aes = new AesCryptoServiceProvider();

            Aes.Mode    = CipherMode.ECB;
            Aes.Padding = PaddingMode.None;
            Aes.Key     = key;
            using (ICryptoTransform Encryptor = Aes.CreateEncryptor()) {
                OutputBuffer = Encryptor.TransformFinalBlock(InputBuffer, 0, 16);
            }
            Aes.Clear();
            return(ToHex(OutputBuffer));
        }
Exemplo n.º 10
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private async Task <byte[]> AliceSendsDataAsync(string message)
        {
            Console.WriteLine("Alice sends message:" + message);
            byte[] rawData       = Encoding.UTF8.GetBytes(message);
            byte[] encryptedData = null;
            //创建ECDiffieHellmanCng对象,并使用Alice的密钥对初始化它
            using (ECDiffieHellmanCng aliceAlgorithm = new ECDiffieHellmanCng(_aliceKey))
                using (CngKey bobPubKey = CngKey.Import(_bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
                {
                    //使用Alice的密钥对和Bob的公钥创建一个对称密钥,返回的对称密钥使用对称算法AES加密数据
                    byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);
                    Console.WriteLine("Alice creates thsi symmetric key with Bobs public key Information:" + Convert.ToBase64String(symmKey));
                    //
                    using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
                    {
                        aes.Key = symmKey;
                        aes.GenerateIV();
                        using (ICryptoTransform encryptor = aes.CreateEncryptor())
                            using (MemoryStream ms = new MemoryStream())
                            {
                                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                                {
                                    await ms.WriteAsync(aes.IV, 0, aes.IV.Length);

                                    cs.Write(rawData, 0, rawData.Length);
                                }
                                encryptedData = ms.ToArray();
                            }
                        //在访问内存流中的加密数据之前,必须关闭加密流,否则加密数据就会丢失最后的位
                        aes.Clear();
                    }
                }

            Console.WriteLine("Alice:message is encrypted:" + Convert.ToBase64String(encryptedData));
            Console.WriteLine();
            return(encryptedData);
        }
Exemplo n.º 11
0
        /*Bob receives encrypted data in the argument of the method BobReceivesData() . First, the
         * unencrypted initialization vector must be read. The BlockSize property of the class
         * AesCryptoServiceProvider returns the number of bits for a block. The number of bytes can be
         * calculated by doing a divide by 8, and the fastest way to do this is by doing a bit shift of 3 bits. Shifting
         * by 1 bit is a division by 2, 2 bits by 4, and 3 bits by 8. With the for loop, the first bytes of the raw bytes
         * that contain the IV unencrypted are written to the array iv . Next, an ECDiffieHellmanCng object is
         * instantiated with the key pair from Bob. Using the public key from Alice, the symmetric key is returned
         * from the method DeriveKeyMaterial() . Comparing the symmetric keys created from Alice and Bob
         * shows that the same key value gets created. Using this symmetric key and the initialization vector, the
         * message from Alice can be decrypted with the AesCryptoServiceProvider class.
         */
        private static void BobReceivesData(byte[] encryptedData)
        {
            ReturnString += String.Format("\n\nBob receives encrypted data");
            byte[] rawData = null;
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            int nBytes = aes.BlockSize >> 3;

            byte[] iv = new byte[nBytes];
            for (int i = 0; i < iv.Length; i++)
            {
                iv[i] = encryptedData[i];
            }
            ECDiffieHellmanCng bobAlgorithm = new ECDiffieHellmanCng(bobKey);

            using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob,
                                                      CngKeyBlobFormat.EccPublicBlob))
            {
                byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey);
                ReturnString += String.Format("\nBob creates this symmetric key with " +
                                              "Alice's public key information: {0}",
                                              Convert.ToBase64String(symmKey));
                aes.Key = symmKey;
                aes.IV  = iv;
                using (ICryptoTransform decryptor = aes.CreateDecryptor())
                    using (MemoryStream ms = new MemoryStream())
                    {
                        CryptoStream cs = new CryptoStream(ms, decryptor,
                                                           CryptoStreamMode.Write);
                        cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes);
                        cs.Close();
                        rawData       = ms.ToArray();
                        ReturnString += String.Format("\nBob decrypts message to: {0}",
                                                      Encoding.UTF8.GetString(rawData));
                    }
                aes.Clear();
            }
        }
        public string Decrypt(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(input);
            }

            var inputBuffer            = Convert.FromBase64String(input);
            var cryptoServiceProvider1 = new MD5CryptoServiceProvider();
            var hash =
                cryptoServiceProvider1.ComputeHash(Encoding.UTF8.GetBytes(GetOriginalString(_salt).ToCharArray()));

            cryptoServiceProvider1.Clear();
            var cryptoServiceProvider2 = new AesCryptoServiceProvider
            {
                Key = hash, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7
            };
            var decryptor = cryptoServiceProvider2.CreateDecryptor();
            var bytes     = decryptor.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);

            decryptor.Dispose();
            cryptoServiceProvider2.Clear();
            return(Encoding.UTF8.GetString(bytes));
        }
Exemplo n.º 13
0
        public async Task BobReceivesDataAsync(byte[] encryptedData)
        {
            Console.WriteLine("Bob receives encrypted data");
            byte[] rawData = null;
            var    aes     = new AesCryptoServiceProvider();
            int    nBytes  = aes.BlockSize;

            byte[] iv = new byte[nBytes];
            for (int i = 0; i < iv.Length; i++)
            {
                iv[i] = encryptedData[i];
            }
            using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey))
            {
                using (CngKey alicePubKey = CngKey.Import(_alicePubKeyBlob, CngKeyBlobFormat.EccFullPublicBlob))
                {
                    byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey);
                    Console.WriteLine(Convert.ToBase64String(symmKey));
                    aes.Key = symmKey;
                    aes.IV  = iv;
                    using (ICryptoTransform decryptor = aes.CreateDecryptor())
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
                            {
                                await cs.WriteAsync(encryptedData, nBytes, encryptedData.Length - nBytes);
                            }
                            rawData = ms.ToArray();
                            Console.WriteLine(Encoding.UTF8.GetString(rawData));
                        }
                        aes.Clear();
                    }
                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="encrytpedData"></param>
        /// <returns></returns>

        private async Task BobReceivesDataAsync(byte[] encrytpedData)
        {
            Console.WriteLine("Bob receives encrypted data");
            byte[] rawData = null;
            //读取未加密的初始化矢量
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            //BlockSize属性返回块的位数,除以8就可以计算出字节数。
            int nBytes = aes.BlockSize / 8;

            byte[] iv = new byte[nBytes];
            for (int i = 0; i < iv.Length; i++)
            {
                iv[i] = encrytpedData[i];
            }
            //实例化一个ECDiffieHellmanCng对象,使用Alice的公钥,从DeriveKeyMaterial()方法中返回对称密钥
            using (ECDiffieHellmanCng bobAlgorithm = new ECDiffieHellmanCng(_bobKey))
                using (CngKey alicePubKey = CngKey.Import(_alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
                {
                    byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey);
                    Console.WriteLine("Bob creates this symmetric key with Alices public key information:" + Convert.ToBase64String(symmKey));

                    aes.Key = symmKey;
                    aes.IV  = iv;
                    using (ICryptoTransform decryptor = aes.CreateDecryptor())
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
                            {
                                await cs.WriteAsync(encrytpedData, nBytes, encrytpedData.Length - nBytes);
                            }
                            rawData = ms.ToArray();
                            Console.WriteLine("Bob decrypts mesage to:" + Encoding.UTF8.GetString(rawData));
                        }
                    aes.Clear();
                }
        }
Exemplo n.º 15
0
        // decryption
        static byte[] Decrypt(byte[] cipherBytes, byte[] key, byte[] iv)
        {
            byte[] plainBytes;

            using (var aes = new AesCryptoServiceProvider())
            {
                //aes.Mode = CipherMode.CBC;		// default
                //aes.Padding = PaddingMode.PKCS7;	// default
                aes.Key = key;
                aes.IV  = iv;
                using (var memoryStream = new MemoryStream())
                {
                    var cryptoStream = new CryptoStream(
                        memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write);
                    cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    plainBytes = memoryStream.ToArray();
                }

                aes.Clear();
            }

            return(plainBytes);
        }
Exemplo n.º 16
0
        private static void AnaPrimaPoruku(byte[] kriptiraniPodaci)
        {
            Console.WriteLine("Ana prima kriptiranu poruku");
            byte[] podaci = null;

            var aes    = new AesCryptoServiceProvider();
            int nBytes = aes.BlockSize >> 3;

            byte[] iv = new byte[nBytes];
            for (int i = 0; i < iv.Length; i++)
            {
                iv[i] = kriptiraniPodaci[i];
            }

            using (var anaAlgoritam = new ECDiffieHellmanCng(anakey))
                using (CngKey ivanPubKey = CngKey.Import(ivanPubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
                {
                    byte[] simKljuč = anaAlgoritam.DeriveKeyMaterial(ivanPubKey);
                    Console.WriteLine("Ana kreira simetrični ključ s Ivanovim javnim ključem: {0}", Convert.ToBase64String(simKljuč));

                    aes.Key = simKljuč;
                    aes.IV  = iv;

                    using (ICryptoTransform decryptor = aes.CreateDecryptor())
                        using (MemoryStream ms = new MemoryStream())
                        {
                            var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write);
                            cs.Write(kriptiraniPodaci, nBytes, kriptiraniPodaci.Length - nBytes);
                            cs.Close();
                            podaci = ms.ToArray();

                            Console.WriteLine("Ana dekriptira poruku: {0}", Encoding.UTF8.GetString(podaci));
                        }
                    aes.Clear();
                }
        }
Exemplo n.º 17
0
        private static byte[] Encrypt(byte[] toEncrypt, byte[] key)
        {
            List <byte> te = toEncrypt.ToList();

            while (te.Count % 16 != 0)
            {
                te.Add(0x00);
            }
            toEncrypt = te.ToArray();
            AesCryptoServiceProvider aes = CreateProvider(key);
            List <byte> K = new List <byte>();

            K = key.ToList();
            while (K.Count < 32)
            {
                K.Add(0x00);
            }
            key = K.ToArray();
            ICryptoTransform cTransform = aes.CreateEncryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);
            aes.Clear();
            return(resultArray);
        }
Exemplo n.º 18
0
 public static bool DecryptData(string data, string key, out string?output)
 {
     key = FixKeyLength(key);
     try
     {
         var array    = Convert.FromBase64String(data);
         var provider = new AesCryptoServiceProvider
         {
             Key     = Encoding.UTF8.GetBytes(key),
             Mode    = CipherMode.ECB,
             Padding = PaddingMode.PKCS7
         };
         var decryptor   = provider.CreateDecryptor();
         var resultArray = decryptor.TransformFinalBlock(array, 0, array.Length);
         provider.Clear();
         output = Encoding.UTF8.GetString(resultArray);
         return(true);
     }
     catch
     {
         output = null;
         return(false);
     }
 }
Exemplo n.º 19
0
        private string Encrypt(string text, string strMeterID)
        {
            string strAESKey = string.Empty;

            //Need to check does the key exist

            using (var db = new uwkeydataEntities1())
            {
                foreach (MeterKey mk in db.MeterKeys)
                {
                    if (mk.MeterID == strMeterID)
                    {
                        strAESKey = mk.AesKey;
                    }
                }
            }

            //if key does not already exist
            if (strAESKey == string.Empty)
            {
                //make key on the fly
                using (RijndaelManaged myRijndael = new RijndaelManaged())
                {
                    myRijndael.KeySize = 128;
                    myRijndael.GenerateKey();
                    // we dont need iv just key value
                    //myRijndael.GenerateIV();

                    byte[] xkey = myRijndael.Key;
                    //var xIV = myRijndael.IV;

                    AesCryptoServiceProvider aes;
                    // AesCryptoServiceProvider
                    using (aes = new AesCryptoServiceProvider())
                    {
                        aes.BlockSize = 128;
                        aes.KeySize   = 128;
                        aes.IV        = Encoding.UTF8.GetBytes(AesIV);
                        aes.Key       = xkey;
                        aes.Mode      = CipherMode.CBC;
                        aes.Padding   = PaddingMode.PKCS7;

                        //store meterID AES Key AES IV in Database

                        using (var db = new uwkeydataEntities1())
                        {
                            MeterKey mk = new MeterKey();
                            mk.MeterID = strMeterID;
                            mk.AesKey  = Convert.ToBase64String(aes.Key);
                            db.MeterKeys.Add(mk);
                            db.SaveChanges();
                        }

                        //byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
                        // Convert string to byte array
                        byte[] src = Encoding.Unicode.GetBytes(text);

                        // encryption
                        using (ICryptoTransform encrypt = aes.CreateEncryptor())
                        {
                            byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
                            aes.Clear();
                            aes.Dispose();
                            encrypt.Dispose();
                            // Convert byte array to Base64 strings
                            return(Convert.ToBase64String(dest));
                        }
                    }
                }
            }
            else
            {
                //we have the key
                AesCryptoServiceProvider aes;
                // AesCryptoServiceProvider
                using (aes = new AesCryptoServiceProvider())
                {
                    aes.BlockSize = 128;
                    aes.KeySize   = 128;
                    aes.IV        = Encoding.UTF8.GetBytes(AesIV);
                    //aes.Key = Encoding.UTF8.GetBytes(strAESKey);
                    aes.Key     = System.Convert.FromBase64String(strAESKey);
                    aes.Mode    = CipherMode.CBC;
                    aes.Padding = PaddingMode.PKCS7;

                    //byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
                    // Convert string to byte array
                    byte[] src = Encoding.Unicode.GetBytes(text);

                    // encryption
                    using (ICryptoTransform encrypt = aes.CreateEncryptor())
                    {
                        byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
                        aes.Clear();
                        aes.Dispose();
                        encrypt.Dispose();
                        // Convert byte array to Base64 strings
                        return(Convert.ToBase64String(dest));
                    }
                }
            }
        }
Exemplo n.º 20
0
        public static byte[] EncryptAESCryptProvider(byte[] privacyKey, byte[] scopedPDU, int pduLen, int snmpEngineBoots, int snmpEngineTime, int keySize)
        {
            int keyBytes = (keySize == 128) ? 16 : 32;

            // Salt determinitation for Privacy Parameters
            Int64 saltInt = NextSalt();

            byte[] saltInvert = BitConverter.GetBytes(saltInt);
            byte[] salt       = new byte[8];
            salt[0] = saltInvert[7];
            salt[1] = saltInvert[6];
            salt[2] = saltInvert[5];
            salt[3] = saltInvert[4];
            salt[4] = saltInvert[3];
            salt[5] = saltInvert[2];
            salt[6] = saltInvert[1];
            salt[7] = saltInvert[0];

            byte[] IV         = new byte[keyBytes];
            byte[] bootsBytes = BitConverter.GetBytes(snmpEngineBoots);
            IV[0] = bootsBytes[3];
            IV[1] = bootsBytes[2];
            IV[2] = bootsBytes[1];
            IV[3] = bootsBytes[0];
            byte[] timeBytes = BitConverter.GetBytes(snmpEngineTime);
            IV[4] = timeBytes[3];
            IV[5] = timeBytes[2];
            IV[6] = timeBytes[1];
            IV[7] = timeBytes[0];

            // Copy salt value to the iv array
            Buffer.BlockCopy(salt, 0, IV, 8, 8);

            // Create AES Key
            byte[] aesKey = new byte[keyBytes];
            Buffer.BlockCopy(privacyKey, 0, aesKey, 0, keyBytes);

            byte[] encryptedRtn = new byte[scopedPDU.Length];
            try
            {
                //perform the encyption..
                //step 1.. Create the stream which will contain the encrypted data
                System.IO.MemoryStream memStrm = new System.IO.MemoryStream();
                //create the DES crypto service provider object
                System.Security.Cryptography.AesCryptoServiceProvider des = new AesCryptoServiceProvider();
                //set the cipher mode
                des.KeySize = keyBytes * 8;
                // PVC Setting to 128 caused Bad Data err des.FeedbackSize = 128;
                des.BlockSize = bsBlockSize;
                des.Padding   = pmPaddingMode;
                des.Mode      = cmCipherMode;
                des.Key       = aesKey;
                des.IV        = IV;

                //create the stream which will convert the data into enryped form and write into underline stream
                ICryptoTransform cryptoTransform = des.CreateEncryptor(aesKey, IV);
                CryptoStream     encryptStrm     = new CryptoStream(memStrm, cryptoTransform /* PVC des.CreateEncryptor(aesKey, IV)*/, CryptoStreamMode.Write);

                //wencypt and write data into underline stream
                encryptStrm.Write(scopedPDU, 0, scopedPDU.Length);
                //flush the final block to stream
                encryptStrm.FlushFinalBlock();
                //close the streams
                encryptStrm.Close();
                //set the encypted data buffer
                encryptedRtn = memStrm.ToArray();
                //close the memory stream
                memStrm.Close();
                des.Clear();
            }
            catch (Exception exp)
            {
            }
            return(encryptedRtn);
        }
Exemplo n.º 21
0
        public string BRAPI_encrypt(string encrypt_Input)
        {
            // Assign the developer details to variables got from the UI textboxes
            string devID  = "your devID";
            string devKey = "your devKey";
            string devIV  = "your devIV";


            #region CODE FROM BR Documentation - http://www.blackoutrugby.com/game/help.documentation.php#category=35
            // This is all from the Blackout Rugby documentation
            // only changes are variables instead of direct string input

            // Create an unencrypted request as an array of bytes
            byte[] request = UTF8Encoding.UTF8.GetBytes(encrypt_Input);

            // Set the key and IV as arrays of bytes
            byte[] key = UTF8Encoding.UTF8.GetBytes(devKey);
            byte[] iv  = UTF8Encoding.UTF8.GetBytes(devIV);

            // Create an instance of the AES Encryptor
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            // Set the key and IV
            aes.Key = key;
            aes.IV  = iv;

            // Set the mode of the AES Encryptor
            aes.Mode = CipherMode.CBC;

            // Set the padding mode of the AES Encryptor
            aes.Padding = PaddingMode.Zeros;

            // Get the transformer from the AES Encryptor
            ICryptoTransform cTransform = aes.CreateEncryptor();

            // Use the transformer to encrypt our request
            byte[] result =
                cTransform.TransformFinalBlock(request, 0, request.Length);

            // Release resources held by AES Encryptor
            aes.Clear();

            // Encode to base64
            string encryptedRequest =
                Convert.ToBase64String(result, 0, result.Length);

            // Send request to API
            //string baseURL = "http://api.blackoutrugby.com/";
            string requestString = devID + "&er=" + encryptedRequest;
            //string response = getWebResponse(requestString); // Second function is called here <---

            #region WebRequest Code

            // Create a request for the URL.
            WebRequest webRequest = WebRequest.Create("http://classic-api.blackoutrugby.com/?d=" + requestString);

            WebResponse Webresponse = webRequest.GetResponse();

            //Get the stream containing content returned by the server.
            Stream dataStream = Webresponse.GetResponseStream();

            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);

            // Read the content.
            string responseFromServer = reader.ReadToEnd();


            // Clean up the streams and the response.
            reader.Close();
            Webresponse.Close();

            #endregion



            return(responseFromServer);


            #endregion CODE FROM BR Documentation
        }
Exemplo n.º 22
0
 public void Dispose()
 {
     AES.Clear();
 }