Ejemplo n.º 1
0
        public static string Decrypt(string decryptValue)
        {
            string[]      csbytes = decryptValue.Split('.');
            byte[]        temp    = new byte[csbytes.Length];
            StringBuilder sUC     = new StringBuilder();

            for (int ictr = 0; ictr < csbytes.Length; ictr++)
            {
                temp[ictr] = Convert.ToByte(csbytes[ictr].ToString());
            }
            string key       = "12345678912345678912345678912345";
            string Indicator = "mdhyadhsddmyghjq";

            byte[] Key = Encoding.ASCII.GetBytes(key);
            byte[] IV  = Encoding.ASCII.GetBytes(Indicator);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
            alg.Key = Key;
            alg.IV  = IV;
            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(temp, 0, temp.Length);
            cs.Close();
            byte[] decryptedData = ms.ToArray();
            string org;

            org = (Encoding.UTF8.GetString(decryptedData));
            return(org);
        }
Ejemplo n.º 2
0
        private string Decrypt(string cipher, string type)
        {
            string EncryptionKey;

            byte[] cipherBytes;

            EncryptionKey = string.Format(this.Core.GetAttribute("DecryptKey"), type);

            cipherBytes = Convert.FromBase64String(cipher);

            using (System.Security.Cryptography.Rijndael encryptor = System.Security.Cryptography.Rijndael.Create())
            {
                System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.Rfc2898DeriveBytes(EncryptionKey, Convert.FromBase64String(this.Core.GetAttribute("DecryptSalt")));

                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV  = pdb.GetBytes(16);

                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }

                    cipher = System.Text.Encoding.Unicode.GetString(ms.ToArray());
                }
            }

            return(cipher);
        }
Ejemplo n.º 3
0
        public static string Encrypt(string encryptValue)
        {
            string key       = "12345678912345678912345678912345";
            string Indicator = "mdhyadhsddmyghjq";

            byte[] password           = Encoding.ASCII.GetBytes(encryptValue);
            byte[] Key                = Encoding.ASCII.GetBytes(key);
            byte[] IV                 = Encoding.ASCII.GetBytes(Indicator);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
            alg.Key = Key;
            alg.IV  = IV;
            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms,
                                                                                                         alg.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(password, 0, password.Length);
            cs.Close();
            byte[] encryptedData = ms.ToArray();
            string str           = null;

            //convert byte into comma seprate string
            for (int i = 0; i < encryptedData.Length; i++)
            {
                str = str + encryptedData[i] + '.';
            }
            //trim , at the end
            str = str.TrimEnd('.');
            return(str);
        }
Ejemplo n.º 4
0
            /// <summary>
            /// 解密指定的字节数据
            /// </summary>
            /// <param name="originalData">加密的字节数据</param>
            /// <param name="keyData">解密密钥</param>
            /// <param name="ivData"></param>
            /// <returns>原始文本</returns>
            private static byte[] Decrypt(byte[] encryptedData, byte[] keyData, byte[] ivData)
            {
                MemoryStream memoryStream = new MemoryStream();

                //创建Rijndael加密算法
                System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();
                rijndael.Key = keyData;
                rijndael.IV  = ivData;

                System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(
                    memoryStream, rijndael.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                try
                {
                    cryptoStream.Write(encryptedData, 0, encryptedData.Length);
                    cryptoStream.Close();
                    cryptoStream.Dispose();
                    return(memoryStream.ToArray());
                }
                catch (Exception ex)
                {
                    LogManager.Instance.WriteLog("GlobalMethods.Decrypt", ex);
                    return(null);
                }
                finally
                {
                    memoryStream.Close();
                    memoryStream.Dispose();
                }
            }
        private static void Test(string hello)
        {
            System.Security.Cryptography.Rijndael rij = System.Security.Cryptography.Rijndael.Create();
            var    data           = Encoding.UTF8.GetBytes(hello);
            var    cryptoData     = rij.Encryptor(data, 0, data.Length);
            var    decryptoData   = rij.Dencryptor(cryptoData, 0, cryptoData.Length);
            string decryptoString = Encoding.UTF8.GetString(decryptoData);

            Assert.AreEqual(hello, decryptoString);
        }
Ejemplo n.º 6
0
        // Decrypt a file into another file using a password.
        public static void Decrypt(string sInputFilepath, string sOutputFilepath, string sPassword)
        {
            System.IO.FileStream fsIn  = null;
            System.IO.FileStream fsOut = null;
            //System.Security.Cryptography.PasswordDeriveBytes pdb = null;
            System.Security.Cryptography.Rfc2898DeriveBytes pdb2 = null;
            System.Security.Cryptography.Rijndael           alg  = null;
            System.Security.Cryptography.CryptoStream       cs   = null;
            try
            {
                // First we are going to open the file streams.
                fsIn  = new System.IO.FileStream(sInputFilepath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                fsOut = new System.IO.FileStream(sOutputFilepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);

                // Then we are going to derive a Key and an IV from the Password and create an algorithm.
                //pdb = new System.Security.Cryptography.PasswordDeriveBytes(sPassword, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
                pdb2 = new System.Security.Cryptography.Rfc2898DeriveBytes(sPassword, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                alg  = System.Security.Cryptography.Rijndael.Create();

                //alg.Key = pdb.GetBytes(32);
                alg.Key = pdb2.GetBytes(32);
                //alg.IV = pdb.GetBytes(16);
                alg.IV = pdb2.GetBytes(16);

                // Now create a crypto stream through which we are going to be pumping data.
                // Our fileOut is going to be receiving the Decrypted bytes.
                cs = new System.Security.Cryptography.CryptoStream(fsOut, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

                // Now will will initialize a buffer and will be processing the input file in chunks.
                // This is done to avoid reading the whole file (which can be huge) into memory.
                int    iBufferLen = 4096;
                byte[] buffer     = new byte[iBufferLen];
                int    iRead;
                do
                {
                    // read a chunk of data from the input file.
                    iRead = fsIn.Read(buffer, 0, iBufferLen);
                    // Decrypt it.
                    cs.Write(buffer, 0, iRead);
                } while (iRead != 0);
            }
            catch (Exception ex) { Logger?.Error(ex); }
            finally
            {
                // close everything.
                if (cs != null)
                {
                    cs.Close(); cs = null;
                }                                          // this will also close the unrelying fsOut stream
                if (fsIn != null)
                {
                    fsIn.Close(); fsIn = null;
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Encriptamos el objecto
        /// </summary>
        /// <param name="pObject">Objecto a Encriptar</param>
        /// <param name="pKey">Clave 1</param>
        /// <param name="pIV">Clave 2</param>
        /// <returns>Retorna el objecto Encriptado</returns>
        private static byte[] EncryptObjectToBytes(object pObject, byte[] pKey, byte[] pIV)
        {
            //Verifica si los parametros son nulo
            if (pObject == null)
            {
                throw new ArgumentNullException();
            }
            if (pKey == null || pKey.Length <= 0)
            {
                throw new ArgumentNullException();
            }
            if (pIV == null || pIV.Length <= 0)
            {
                throw new ArgumentNullException();
            }

            //Creamos la variable byte[] que almacena el objecto encriptado
            byte[] encrypted;

            //Creamos el algoritmo
            System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();

            //Usamos el algoritmo
            using (rijndael)
            {
                //Le pasamos los valores de las claves al algoritmno
                rijndael.Key = pKey;
                rijndael.IV  = pIV;

                //Creamos el Encriptador
                System.Security.Cryptography.ICryptoTransform encryptor = rijndael.CreateEncryptor(rijndael.Key, rijndael.IV);

                //Se crean las corrientes para el cifrado
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Escribe los datos en la secuencia
                            swEncrypt.Write(pObject);
                        }

                        //Almacenamos la encriptacion en el objecto
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            //Retornamos el objecto encriptado
            return(encrypted);
        }
 private static System.IO.Stream GenerateCryptoStream(string fileName, byte[] key, byte[] IV)
 {
     using (System.Security.Cryptography.Rijndael rijAlg = System.Security.Cryptography.Rijndael.Create())
     {
         rijAlg.Key = key;
         rijAlg.IV  = IV;
         // Create a decrytor to perform the stream transform.
         using (System.IO.FileStream fs = System.IO.File.Open(fileName, System.IO.FileMode.Open))
         {
             return(new System.Security.Cryptography.CryptoStream(fs, rijAlg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read));
         }
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Desencripta un objecto
        /// </summary>
        /// <param name="pObject">Objecto Encriptado</param>
        /// <param name="pKey">Clave 1</param>
        /// <param name="pIV">Clave 2</param>
        /// <returns>Retorna el Objecto Desencriptado</returns>
        private static object DecryptObjectFromBytes(byte[] pObject, byte[] pKey, byte[] pIV)
        {
            //Verifica si los parametros son nulo
            if (pObject == null || pObject.Length <= 0)
            {
                throw new ArgumentNullException();
            }
            if (pKey == null || pKey.Length <= 0)
            {
                throw new ArgumentNullException();
            }
            if (pIV == null || pIV.Length <= 0)
            {
                throw new ArgumentNullException();
            }

            //Variable que almacenara el valor del objecto encritado
            object vlDecodeObject = null;

            //Creamos el algoritmo
            System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();

            //Usamos el algoritmo
            using (rijndael)
            {
                //Le pasamos los valores de las claves al algoritmno
                rijndael.Key = pKey;
                rijndael.IV  = pIV;

                //Creamos el Desencriptador
                System.Security.Cryptography.ICryptoTransform decryptor = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV);

                //Se crean las corrientes para el cifrado
                using (MemoryStream msDecrypt = new MemoryStream(pObject))
                {
                    using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            //Escribe los datos en la secuencia, como un objecto (string)
                            vlDecodeObject = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            //Retornamos el objecto desencriptado
            return(vlDecodeObject);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Manda a encriptar un objecto
        /// </summary>
        /// <param name="pObject">Objecto a encriptar</param>
        /// <returns>Retorna el Objecto Encriptado con las Claves</returns>
        public static object Encode(object pObject)
        {
            //Creamos el algoritmo
            System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();

            //Almacenamos las claves
            object vlKey = rijndael.Key;
            object vlIV  = rijndael.IV;

            //Usamos el algoritmo
            using (rijndael)
            {
                //Encriptamos el objecto
                object vlEncrypted = EncryptObjectToBytes(pObject, rijndael.Key, rijndael.IV);

                //Almacenamos en un string[] el objecto encritado
                string[] vlEnEncrypted = ((IEnumerable)vlEncrypted).Cast <object>()
                                         .Select(x => x.ToString())
                                         .ToArray();

                //Almacenamos en un string[] la clave 1
                string[] vlEnKey = ((IEnumerable)vlKey).Cast <object>()
                                   .Select(x => x.ToString())
                                   .ToArray();

                //Almacenamos en un string[] la clave 2
                string[] vlEnIV = ((IEnumerable)vlIV).Cast <object>()
                                  .Select(x => x.ToString())
                                  .ToArray();

                //Creamos el string con los datos encriptados
                string vlValueEncode = string.Empty;
                vlValueEncode = vlValueEncode + string.Join(",", vlEnEncrypted);
                vlValueEncode = vlValueEncode + "/" + string.Join(",", vlEnKey);
                vlValueEncode = vlValueEncode + "/" + string.Join(",", vlEnIV);

                //Almacenamos en un objecto el string
                object vlValueFinal = vlValueEncode;

                //Retornamos el objecto
                return(vlValueFinal);
            }
        }
Ejemplo n.º 11
0
        public static bool _Create_System_String( )
        {
            //Parameters
            System.String algName = null;

            //ReturnType/Value
            System.Security.Cryptography.Rijndael returnVal_Real        = null;
            System.Security.Cryptography.Rijndael returnVal_Intercepted = null;

            //Exception
            Exception exception_Real        = null;
            Exception exception_Intercepted = null;

            InterceptionMaintenance.disableInterception( );

            try
            {
                returnValue_Real = System.Security.Cryptography.Rijndael.Create(algName);
            }

            catch (Exception e)
            {
                exception_Real = e;
            }


            InterceptionMaintenance.enableInterception( );

            try
            {
                returnValue_Intercepted = System.Security.Cryptography.Rijndael.Create(algName);
            }

            catch (Exception e)
            {
                exception_Intercepted = e;
            }


            Return((exception_Real.Messsage == exception_Intercepted.Message) && (returnValue_Real == returnValue_Intercepted));
        }
Ejemplo n.º 12
0
        // Decrypt a byte array into a byte array using a key and an IV.
        public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
        {
            byte[] byteReturn         = null;
            System.IO.MemoryStream ms = null;
            System.Security.Cryptography.Rijndael alg = null;
            //System.Security.Cryptography.CryptoStream cs = null;
            try
            {
                // Create a MemoryStream that is going to accept the decrypted bytes.
                ms = new System.IO.MemoryStream();

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

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

                // Create a CryptoStream through which we are going to be pumping our data.
                // CryptoStreamMode.Write means that we are going to be writing data to the stream and the output will be written in the MemoryStream we have provided.
                //cs = new System.Security.Cryptography.CryptoStream(ms, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

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

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

                int iLength = 0;
                if (cipherData != null)
                {
                    iLength = cipherData.Length;
                }
                using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                { cs.Write(cipherData, 0, iLength); }

                // Now get the decrypted data from the MemoryStream.
                // Some people make a mistake of using GetBuffer() here, which is not the right way.
                if (ms != null)
                {
                    byteReturn = ms.ToArray();
                }

                return(byteReturn);
            }
            catch (Exception ex)
            {
                Logger?.Error(ex);
                return(null);
            }
        }
Ejemplo n.º 13
0
        private static void VerifyDefaults(Rijndael alg)
        {
            // The block size differs from the base
            Assert.Equal(128, alg.LegalBlockSizes[0].MinSize);
            Assert.Equal(128, alg.LegalBlockSizes[0].MaxSize);
            Assert.Equal(128, alg.BlockSize);

            // Different exception since we have different supported BlockSizes than desktop
            Assert.Throws<PlatformNotSupportedException>(() => alg.BlockSize = 192);
            Assert.Throws<PlatformNotSupportedException>(() => alg.BlockSize = 256);

            // Normal exception for rest
            Assert.Throws<CryptographicException>(() => alg.BlockSize = 111);

            Assert.Equal(CipherMode.CBC, alg.Mode);
            Assert.Equal(PaddingMode.PKCS7, alg.Padding);
        }
Ejemplo n.º 14
0
        private static void TestShims(Rijndael alg)
        {
            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.º 15
0
        private static void EncryptDecryptKnownECB192(Rijndael alg)
        {
            byte[] plainTextBytes =
                new ASCIIEncoding().GetBytes("This is a sentence that is longer than a block, it ensures that multi-block functions work.");

            byte[] encryptedBytesExpected = new byte[]
            {
                0xC9, 0x7F, 0xA5, 0x5B, 0xC3, 0x92, 0xDC, 0xA6,
                0xE4, 0x9F, 0x2D, 0x1A, 0xEF, 0x7A, 0x27, 0x03,
                0x04, 0x9C, 0xFB, 0x56, 0x63, 0x38, 0xAE, 0x4F,
                0xDC, 0xF6, 0x36, 0x98, 0x28, 0x05, 0x32, 0xE9,
                0xF2, 0x6E, 0xEC, 0x0C, 0x04, 0x9D, 0x12, 0x17,
                0x18, 0x35, 0xD4, 0x29, 0xFC, 0x01, 0xB1, 0x20,
                0xFA, 0x30, 0xAE, 0x00, 0x53, 0xD4, 0x26, 0x25,
                0xA4, 0xFD, 0xD5, 0xE6, 0xED, 0x79, 0x35, 0x2A,
                0xE2, 0xBB, 0x95, 0x0D, 0xEF, 0x09, 0xBB, 0x6D,
                0xC5, 0xC4, 0xDB, 0x28, 0xC6, 0xF4, 0x31, 0x33,
                0x9A, 0x90, 0x12, 0x36, 0x50, 0xA0, 0xB7, 0xD1,
                0x35, 0xC4, 0xCE, 0x81, 0xE5, 0x2B, 0x85, 0x6B,
            };

            byte[] aes192Key = new byte[]
            {
                0xA6, 0x1E, 0xC7, 0x54, 0x37, 0x4D, 0x8C, 0xA5,
                0xA4, 0xBB, 0x99, 0x50, 0x35, 0x4B, 0x30, 0x4D,
                0x6C, 0xFE, 0x3B, 0x59, 0x65, 0xCB, 0x93, 0xE3,
            };

            // The CipherMode and KeySize are different than the default values; this ensures the type
            // forwards the state properly to Aes.
            alg.Mode = CipherMode.ECB;
            alg.Key = aes192Key;

            byte[] encryptedBytes = alg.Encrypt(plainTextBytes);
            Assert.Equal(encryptedBytesExpected, encryptedBytes);

            byte[] decryptedBytes = alg.Decrypt(encryptedBytes);
            Assert.Equal(plainTextBytes, decryptedBytes);
        }