Esempio n. 1
0
        public ICrypt Initialize(string key)
        {
            _algo?.Dispose();

            using (var hashProvider = new MD5CryptoServiceProvider())
                _algo = new TripleDESCryptoServiceProvider()
                {
                    Mode    = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7,
                    Key     = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(key))
                };

            return(this);
        }
 public void Dispose()
 {
     if (_algo != null)
     {
         _algo.Dispose();
     }
 }
Esempio n. 3
0
 /// <summary>
 /// DES3 CBC模式解密
 /// </summary>
 /// <param name="key">密钥</param>
 /// <param name="iv">IV</param>
 /// <param name="data">密文的byte数组</param>
 /// <returns>明文的byte数组</returns>
 public static byte[] Des3DecodeCBC(byte[] key, byte[] iv, byte[] data)
 {
     try
     {
         // Create a new MemoryStream using the passed
         // array of encrypted data.
         MemoryStream msDecrypt = new MemoryStream(data);
         TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
         tdsp.Mode    = CipherMode.CBC;
         tdsp.Padding = PaddingMode.PKCS7;
         // Create a CryptoStream using the MemoryStream
         // and the passed key and initialization vector (IV).
         CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                                                   tdsp.CreateDecryptor(key, iv),
                                                   CryptoStreamMode.Read);
         // Create buffer to hold the decrypted data.
         byte[] fromEncrypt = new byte[data.Length];
         // Read the decrypted data out of the crypto stream
         // and place it into the temporary buffer.
         csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
         //Convert the buffer into a string and return it.
         msDecrypt.Dispose();
         tdsp.Dispose();
         csDecrypt.Dispose();
         return(fromEncrypt);
     }
     catch (CryptographicException ex)
     {
         Logging.Log4NetHelper.Error(typeof(EncryptionLib), ex);
         throw;
     }
 }
Esempio n. 4
0
        //使用TripleDES加密
        public static byte[] Crypt(byte[] source, byte[] key)
        {
            if ((source.Length == 0) || (source == null) || (key == null) || (key.Length == 0))
            {
                throw new ArgumentException("Invalid Argument");
            }

            TripleDESCryptoServiceProvider dsp = null;

            try
            {
                dsp      = new TripleDESCryptoServiceProvider();
                dsp.Mode = CipherMode.ECB;

                ICryptoTransform des = dsp.CreateEncryptor(key, null);

                return(des.TransformFinalBlock(source, 0, source.Length));
            }
            finally
            {
                if (dsp != null)
                {
                    dsp.Dispose();
                }
            }
        }
        /// <summary>
        /// Loads serialized object from the file
        /// </summary>
        public static T LoadDecryptedDes <T>(string key, string iv, string fileName = null) where T : class
        {
            // build file path
            fileName = SerializationHelper.GetFilePath <T>(fileName);

            // check if file exists
            if (!System.IO.File.Exists(fileName))
            {
                return(null);
            }

            T res;

            using (var decryptor = new TripleDESCryptoServiceProvider())
            {
                decryptor.Key = Encoding.Default.GetBytes(key);
                decryptor.IV  = Encoding.Default.GetBytes(iv);

                res = SerializationHelper.DecryptAndDeserialize(fileName, typeof(T), new Type[] { }, decryptor) as T;

                decryptor.Dispose();
            }

            return(res);
        }
Esempio n. 6
0
        /// <summary>
        /// EncryptBase64
        /// </summary>
        /// <param name="StringToEncrypt"></param>
        /// <param name="Key"></param>
        /// <param name="IV"></param>
        /// <returns></returns>
        private static string EncryptBase64(string StringToEncrypt, byte[] Key, byte[] IV)
        {
            TripleDESCryptoServiceProvider tripledes;
            MemoryStream ms;
            CryptoStream cs;

            try
            {
                tripledes = new TripleDESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.UTF8.GetBytes(StringToEncrypt);
                ms = new MemoryStream();
                cs = new CryptoStream(ms, tripledes.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                String str = Convert.ToBase64String(ms.ToArray());
                cs.Clear();
                tripledes.Dispose();
                return(str);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                tripledes = null;
                ms        = null;
                cs        = null;
            }
        }
Esempio n. 7
0
 /// <summary>
 /// Encrypt a string using a static key and TripleDES
 /// </summary>
 /// <param name="data">The string that needs to be encrypted</param>
 /// <returns>Encrypted string</returns>
 public static string BBSEncrypt(string data)
 {
     if (Testing)
     {
         return(data);
     }
     else
     {
         MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
         byte[] keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes("bbspabx"));
         TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider
         {
             Mode    = CipherMode.ECB,
             Padding = PaddingMode.PKCS7,
             Key     = keyArray
         };
         try
         {
             ICryptoTransform cTransform  = tdes.CreateEncryptor();
             byte[]           resultArray = cTransform.TransformFinalBlock(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
             tdes.Clear();
             return(Convert.ToBase64String(resultArray, 0, resultArray.Length));
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
             return(ex.Message);
         }
         finally
         {
             hashmd5.Dispose();
             tdes.Dispose();
         }
     }
 }
Esempio n. 8
0
        public static string Encrypt(string mString, string mKey)
        {
            if (mString == "")
            {
                return(mString);
            }
            TripleDESCryptoServiceProvider cryptdes3 = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider       hash      = new MD5CryptoServiceProvider();

            try
            {
                cryptdes3.Key  = hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(mKey));
                cryptdes3.Mode = CipherMode.ECB;
                ICryptoTransform enc  = cryptdes3.CreateEncryptor();
                byte[]           buff = ASCIIEncoding.ASCII.GetBytes(mString);

                return(Convert.ToBase64String(enc.TransformFinalBlock(buff, 0, buff.Length)));
            }
            catch (Exception ex)
            {
                throw new Exception("Bad Data", ex);
            }
            finally
            {
                cryptdes3.Dispose();
                hash.Dispose();
            }
        }
        /// <summary>
        /// Decrypt the given string using the specified key.
        /// </summary>
        /// <param name="textToDecrypt">The string to be encrypted</param>
        /// <param name="SecurePhrase">The Secure Phrase used to decryption</param>
        /// <returns>The Decrypted string.</returns>
        public static string Decrypt(string textToDecrypt, string SecurePhrase)
        {
            try
            {
                var oTripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
                var oMD5CryptoServiceProvider       = new MD5CryptoServiceProvider();

                byte[] byteHash, byteBuff;

                byteHash = oMD5CryptoServiceProvider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(SecurePhrase));


                oTripleDESCryptoServiceProvider.Key  = byteHash;
                oTripleDESCryptoServiceProvider.Mode = CipherMode.ECB; //CBC, CFB

                byteBuff = Convert.FromBase64String(textToDecrypt);

                string Aux = ASCIIEncoding.ASCII.GetString(oTripleDESCryptoServiceProvider.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));

                oTripleDESCryptoServiceProvider.Dispose();
                oMD5CryptoServiceProvider.Dispose();

                return(Aux);
            }
            catch (Exception ex)
            {
                return("Framework.Cryptography: " + ex.Message);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string DES3Decrypt(string data, string key)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();

            DES.Key     = ASCIIEncoding.ASCII.GetBytes(key);
            DES.Mode    = CipherMode.CBC;
            DES.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            ICryptoTransform DESDecrypt = DES.CreateDecryptor();

            string result = "";

            try
            {
                byte[] Buffer = Convert.FromBase64String(data);
                result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch (Exception ex)
            {
                Logging.Log4NetHelper.Error(typeof(EncryptionLib), ex);
                throw;
            }
            DES.Dispose();
            return(result);
        }
        /// <summary>
        /// This method is used to convert the plain text to Encrypted/Un-Readable Text format.
        /// </summary>
        /// <param name="PlainText">Plain Text to Encrypt before transferring over the network.</param>
        /// <returns>Cipher Text</returns>
        public string EncryptPassword(string input)
        {
            string hash = string.Empty;
            MD5CryptoServiceProvider       objMD5CryptoService       = null;
            TripleDESCryptoServiceProvider objTripleDESCryptoService = null;

            try
            {
                objStringBuilder.AppendLine("Begin: Utility-Common-EncryptPassword using MD5");
                //Getting the bytes of Input String.
                byte[] toEncryptedArray = UTF8Encoding.UTF8.GetBytes(input);

                objMD5CryptoService = new MD5CryptoServiceProvider();

                //Gettting the bytes from the Security Key and Passing it to compute the Corresponding Hash Value.
                byte[] securityKeyArray = objMD5CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(_securityKey));

                //De-allocatinng the memory after doing the Job.
                objMD5CryptoService.Clear();

                objTripleDESCryptoService = new TripleDESCryptoServiceProvider();

                //Assigning the Security key to the TripleDES Service Provider.
                objTripleDESCryptoService.Key = securityKeyArray;

                //Mode of the Crypto service is Electronic Code Book.
                objTripleDESCryptoService.Mode = CipherMode.ECB;

                //Padding Mode is PKCS7 if there is any extra byte is added.
                objTripleDESCryptoService.Padding = PaddingMode.PKCS7;

                var objCrytpoTransform = objTripleDESCryptoService.CreateEncryptor();

                //Transform the bytes array to resultArray
                byte[] resultArray = objCrytpoTransform.TransformFinalBlock(toEncryptedArray, 0, toEncryptedArray.Length);

                //Releasing the Memory Occupied by TripleDES Service Provider for Encryption.
                objTripleDESCryptoService.Clear();

                //Convert and return the encrypted data/byte into string format.
                hash = Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch (Exception error)
            {
                LogManager.LogManagerInstance.WriteErrorLog(error);
            }
            finally
            {
                objMD5CryptoService.Dispose();
                objTripleDESCryptoService.Dispose();
                objStringBuilder.AppendLine("End: Utility-Common-EncryptDecrypt-EncryptString");
                LogManager.LogManagerInstance.WriteTraceLog(objStringBuilder);
            }
            return(hash);
        }
Esempio n. 12
0
 // IDisposable
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             TripleDes.Dispose();
         }
     }
     disposedValue = true;
 }
        private static string SubDecrypt(string cipherString, bool useHashing, string customKey)
        {
            MD5CryptoServiceProvider       hashmd5 = null;
            TripleDESCryptoServiceProvider tdes    = null;
            ICryptoTransform cTransform            = null;

            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = toEncryptArray = Convert.FromBase64String(cipherString);

                if (useHashing)
                {
                    hashmd5  = new MD5CryptoServiceProvider();
                    keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(customKey));
                    hashmd5.Clear();
                }
                else
                {
                    keyArray = UTF8Encoding.UTF8.GetBytes(Key);
                }

                tdes         = new TripleDESCryptoServiceProvider();
                tdes.Key     = keyArray;
                tdes.Mode    = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;

                cTransform = tdes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                tdes.Clear();
                return(UTF8Encoding.UTF8.GetString(resultArray));
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (hashmd5 != null)
                {
                    hashmd5.Dispose();
                }

                if (tdes != null)
                {
                    tdes.Dispose();
                }
                if (cTransform != null)
                {
                    cTransform.Dispose();
                }
            }
        }
        public byte[] CreateEncryptionKey()
        {
            var keyProvider = new TripleDESCryptoServiceProvider();

            keyProvider.KeySize = 192;
            keyProvider.GenerateKey();

            var key = keyProvider.Key;

            keyProvider.Dispose();
            EncryptionKey = key;
            return(key);
        }
Esempio n. 15
0
 protected virtual void Dispose(bool _disposing)
 {
     if (_disposing)
     {
         if (tdes == null)
         {
             return;
         }
         tdes.Clear();
         tdes.Dispose();
         tdes = null;
     }
 }
Esempio n. 16
0
        /// <summary>
        /// Saves object to the file
        /// </summary>
        public static void SaveEncryptedDes <T>(T obj, string key, string iv, string fileName = null) where T : class
        {
            fileName = SerializationHelper.GetFilePath <T>(fileName);

            using (var encryptor = new TripleDESCryptoServiceProvider())
            {
                encryptor.Key = Encoding.Default.GetBytes(key);
                encryptor.IV  = Encoding.Default.GetBytes(iv);

                SerializationHelper.EncryptAndSerialize(fileName, obj, new Type[] { }, encryptor);

                encryptor.Dispose();
            }
        }
Esempio n. 17
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string DES3Encrypt(string data, string key)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();

            DES.Key     = ASCIIEncoding.ASCII.GetBytes(key);
            DES.Mode    = CipherMode.CBC;
            DES.Padding = PaddingMode.PKCS7;

            ICryptoTransform DESEncrypt = DES.CreateEncryptor();

            byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(data);
            DES.Dispose();
            return(Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)));
        }
        public static string Encrypt(string toEncrypt, bool useHashing, string customKey)
        {
            MD5CryptoServiceProvider       hashmd5 = null;
            TripleDESCryptoServiceProvider tdes    = null;
            ICryptoTransform cTransform            = null;

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

            if (useHashing)
            {
                hashmd5  = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(customKey));
                hashmd5.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(Key);
            }

            tdes         = new TripleDESCryptoServiceProvider();
            tdes.Key     = keyArray;
            tdes.Mode    = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdes.Clear();

            if (hashmd5 != null)
            {
                hashmd5.Dispose();
            }

            if (tdes != null)
            {
                tdes.Dispose();
            }

            if (cTransform != null)
            {
                cTransform.Dispose();
            }

            return(Convert.ToBase64String(resultArray, 0, resultArray.Length) + delimited);
        }
Esempio n. 19
0
        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the
        // runtime from inside the finalizer and you should not reference
        // other objects. Only unmanaged resources can be disposed.
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this.disposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    tripleDes.Dispose();
                }

                // Note disposing has been done.
                disposed = true;
            }
        }
Esempio n. 20
0
 /// <summary>
 ///  Generic DES Decryption Function
 /// </summary>
 /// <param name="data"></param>
 /// <param name="key"></param>
 /// <param name="iv"></param>
 /// <param name="padding"></param>
 /// <param name="mode"></param>
 /// <returns></returns>
 internal static byte[] TripleDESDecrypt(byte[] data, byte[] key, byte[] iv, PaddingMode padding, CipherMode mode)
 {
     try
     {
         var algorithm = new TripleDESCryptoServiceProvider {
             Padding = padding, Mode = mode
         };
         ICryptoTransform decryptor = algorithm.CreateDecryptor(key, iv);
         var retVal = Crypter(data, key, iv, decryptor);
         decryptor.Dispose();
         algorithm.Dispose();
         return(retVal);
     }
     catch (CryptographicException ex)
     {
         throw new ApplicationException("Error during Triple DES decryption of license code.", ex);
     }
 }
Esempio n. 21
0
        /// <summary>
        /// Encripta el texto que se le pasa como parámetro
        /// </summary>
        /// <param name="text">Texto a encriptar</param>
        /// <returns>Resultado de la encriptación</returns>
        public string EncryptKey(string text)
        {
            byte[] keyArray;
            byte[] arrayToEncript = UTF8Encoding.UTF8.GetBytes(text);

            TripleDESCryptoServiceProvider tdes = null;

            byte[] result;
            MD5CryptoServiceProvider hashmd5 = null;

            try
            {
                //MD5
                hashmd5  = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();

                //3DAS
                tdes = new TripleDESCryptoServiceProvider
                {
                    Key     = keyArray,
                    Mode    = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };
                ICryptoTransform cTransform = tdes.CreateEncryptor();

                result = cTransform.TransformFinalBlock(arrayToEncript, 0, arrayToEncript.Length);
                tdes.Clear();
            }
            finally
            {
                if (tdes != null)
                {
                    tdes.Dispose();
                }
                if (hashmd5 != null)
                {
                    hashmd5.Dispose();
                }
            }
            //Result
            return(Convert.ToBase64String(result, 0, result.Length));
        }
Esempio n. 22
0
        /// <summary>
        /// Private method to DES3 decryption.
        /// </summary>
        /// <param name="encryptedValue">DES3 encrypted string</param>
        /// <returns>clear text string</returns>
        /// <remarks></remarks>
        private static string decryptTripleDES(string encryptedValue)
        {
            string mRetVal = string.Empty;
            TripleDESCryptoServiceProvider mCryptoProvider = null;
            MemoryStream mMemoryStream = null;

            if (!string.IsNullOrEmpty(encryptedValue))
            {
                try
                {
                    mCryptoProvider = new TripleDESCryptoServiceProvider();
                    if (isBase64String(encryptedValue))
                    {
                        //convert from string to byte array
                        byte[] buffer = Convert.FromBase64String(encryptedValue);
                        mMemoryStream = new MemoryStream(buffer);
                        CryptoStream mCryptoStream = new CryptoStream(mMemoryStream, mCryptoProvider.CreateDecryptor(s_KEY_192, s_IV_192), CryptoStreamMode.Read);
                        StreamReader mStreamReader = new StreamReader(mCryptoStream);
                        mRetVal = mStreamReader.ReadToEnd();
                    }
                    else
                    {
                        mRetVal = encryptedValue;
                    }
                }
                catch (Exception ex)
                {
                    throw new CryptoUtilityException("error using Decrypt Triple DES", ex);
                }
                finally
                {
                    if (mCryptoProvider != null)
                    {
                        mCryptoProvider.Dispose();
                    }
                    if (mMemoryStream != null)
                    {
                        mMemoryStream.Dispose();
                    }
                }
            }
            return(mRetVal);
        }
Esempio n. 23
0
        public static string Decrypt(string encryptedData)
        {
            try
            {
                byte[] inputArray = Convert.FromBase64String(encryptedData);

                SecurityCodecs codec = new SecurityCodecs();
                TripleDESCryptoServiceProvider provider = codec.DES3Provider();

                ICryptoTransform cTransform  = provider.CreateDecryptor();
                byte[]           resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);

                provider.Clear();
                provider.Dispose();
                codec.Dispose();

                return(UTF32Encoding.UTF32.GetString(resultArray));
            }
            catch { return(encryptedData); }
        }
Esempio n. 24
0
        /// <summary>
        /// Private method to perform DES3 encryption
        /// </summary>
        /// <param name="valueToEncrypt">String to be DES3 encrypted</param>
        /// <returns>Encrypted string</returns>
        /// <remarks></remarks>
        private static string encryptTripleDES(string valueToEncrypt)
        {
            string retVal = valueToEncrypt;

            if (!string.IsNullOrEmpty(valueToEncrypt))
            {
                TripleDESCryptoServiceProvider mCryptoProvider = null;
                MemoryStream mMemoryStream = null;
                try
                {
                    mCryptoProvider = new TripleDESCryptoServiceProvider();
                    mMemoryStream   = new MemoryStream();
                    CryptoStream mCryptoStream = new CryptoStream(mMemoryStream, mCryptoProvider.CreateEncryptor(s_KEY_192, s_IV_192), CryptoStreamMode.Write);
                    StreamWriter mStreamWriter = new StreamWriter(mCryptoStream);
                    mStreamWriter.Write(valueToEncrypt);
                    mStreamWriter.Flush();
                    mCryptoStream.FlushFinalBlock();
                    mMemoryStream.Flush();
                    //convert back to a string
                    retVal = Convert.ToBase64String(mMemoryStream.GetBuffer(), 0, int.Parse(mMemoryStream.Length.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture));
                }
                catch (Exception ex)
                {
                    throw new CryptoUtilityException("error using encrypt Triple DES", ex);
                }
                finally
                {
                    if (mCryptoProvider != null)
                    {
                        mCryptoProvider.Dispose();
                    }
                    if (mMemoryStream != null)
                    {
                        mMemoryStream.Dispose();
                    }
                }
            }
            return(retVal);
        }
Esempio n. 25
0
 /// <summary>
 /// Descrypt a string using a static key and TripleDES
 /// </summary>
 /// <param name="data">The encrypted string</param>
 /// <returns>Decrypted string</returns>
 public static string BBSDecrypt(string data)
 {
     if (Testing)
     {
         return(data);
     }
     else
     {
         MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
         byte[] keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes("bbspabx"));
         TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider
         {
             Mode    = CipherMode.ECB,
             Padding = PaddingMode.PKCS7,
             Key     = keyArray
         };
         ICryptoTransform cTransform = tdes.CreateDecryptor();
         try
         {
             byte[] b            = Convert.FromBase64String(data);
             byte[] resultArrayA = cTransform.TransformFinalBlock(Convert.FromBase64String(data), 0, Convert.FromBase64String(data).Length);
             tdes.Clear();
             return(Encoding.UTF8.GetString(resultArrayA));
         }
         catch (FormatException e)
         {
             MessageBox.Show(e.ToString());
             File.Delete("login_details.bbs");   //If there's an illegal character then the file is probably corrupt or hasn't been encrypted properly
             return(e.Message);
         }
         finally
         {
             hashmd5.Dispose();
             tdes.Dispose();
         }
     }
 }
Esempio n. 26
0
 /// <summary>
 /// DES3 CBC模式加密
 /// </summary>
 /// <param name="key">密钥</param>
 /// <param name="iv">IV</param>
 /// <param name="data">明文的byte数组</param>
 /// <returns>密文的byte数组</returns>
 public static byte[] Des3EncodeCBC(byte[] key, byte[] iv, byte[] data)
 {
     //复制于MSDN
     try
     {
         // Create a MemoryStream.
         MemoryStream mStream = new MemoryStream();
         TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
         tdsp.Mode    = CipherMode.CBC;          //默认值
         tdsp.Padding = PaddingMode.PKCS7;       //默认值
         // Create a CryptoStream using the MemoryStream
         // and the passed key and initialization vector (IV).
         CryptoStream cStream = new CryptoStream(mStream,
                                                 tdsp.CreateEncryptor(key, iv),
                                                 CryptoStreamMode.Write);
         // Write the byte array to the crypto stream and flush it.
         cStream.Write(data, 0, data.Length);
         cStream.FlushFinalBlock();
         // Get an array of bytes from the
         // MemoryStream that holds the
         // encrypted data.
         byte[] ret = mStream.ToArray();
         // Close the streams.
         cStream.Close();
         mStream.Close();
         mStream.Dispose();
         tdsp.Dispose();
         cStream.Dispose();
         // Return the encrypted buffer.
         return(ret);
     }
     catch (CryptographicException ex)
     {
         Logging.Log4NetHelper.Error(typeof(EncryptionLib), ex);
         throw;
     }
 }
Esempio n. 27
0
        public static byte[] Decrypt(byte[] source, byte[] key)
        {
            if ((source.Length == 0) || (source == null) || (key == null) || (key.Length == 0))
            {
                throw new ArgumentNullException("Invalid Argument");
            }

            TripleDESCryptoServiceProvider dsp = null;

            try
            {
                dsp      = new TripleDESCryptoServiceProvider();
                dsp.Mode = CipherMode.ECB;

                ICryptoTransform des = dsp.CreateDecryptor(key, null);

                byte[] ret = new byte[source.Length + 8];

                int num;
                num = des.TransformBlock(source, 0, source.Length, ret, 0);

                ret = des.TransformFinalBlock(source, 0, source.Length);
                ret = des.TransformFinalBlock(source, 0, source.Length);
                num = ret.Length;

                byte[] RealByte = new byte[num];
                Array.Copy(ret, RealByte, num);
                ret = RealByte;
                return(ret);
            }finally
            {
                if (dsp != null)
                {
                    dsp.Dispose();
                }
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Encrypts/decrypts a byte array
        /// </summary>
        /// <param name="buffer">Bytes to crypt</param>
        /// <param name="key">"Password" for encryption</param>
        /// <param name="iv">"Salt" for encryption. A starting point for encryption.</param>
        /// <param name="encrypt">Do you wish to encrypt or decrypt?</param>
        /// <param name="algorithm">Encryption algorithm. AES/DES/TripleDES</param>
        /// <returns></returns>
        public static byte[] Crypt(byte[] buffer, byte[] key, byte[] iv, bool encrypt = true, string algorithm = "aes")
        {
            AesCryptoServiceProvider       aes      = null;
            DESCryptoServiceProvider       des      = null;
            TripleDESCryptoServiceProvider tripsDes = null;

            ICryptoTransform cryptor;

            switch (algorithm.ToLower())
            {
            case "aes":
                aes     = new AesCryptoServiceProvider();
                aes.Key = key;
                aes.IV  = iv;
                //aes.Padding = PaddingMode.None;

                if (encrypt)
                {
                    cryptor = aes.CreateEncryptor();
                }
                else
                {
                    cryptor = aes.CreateDecryptor();
                }

                break;

            case "des":
                des     = new DESCryptoServiceProvider();
                des.Key = key;
                des.IV  = iv;
                //des.Padding = PaddingMode.None;

                if (encrypt)
                {
                    cryptor = des.CreateEncryptor();
                }
                else
                {
                    cryptor = des.CreateDecryptor();
                }

                break;

            case "tripledes":
                tripsDes     = new TripleDESCryptoServiceProvider();
                tripsDes.Key = key;
                tripsDes.IV  = iv;
                //tripsDes.Padding = PaddingMode.None;


                if (encrypt)
                {
                    cryptor = tripsDes.CreateEncryptor();
                }
                else
                {
                    cryptor = tripsDes.CreateDecryptor();
                }

                break;

            default:
                throw new ArgumentException(algorithm + " is not an implemented encryption algorithm. Use AES/DES/TripleDES.");
            }
            try
            {
                return(cryptor.TransformFinalBlock(buffer, 0, buffer.Length));
            }
            catch (CryptographicException)
            {
                throw new ArgumentException("Ensure you have the right key/IV.");
            }
            finally
            {
                cryptor.Dispose();
                if (aes != null)
                {
                    aes.Dispose();
                }
                if (des != null)
                {
                    des.Dispose();
                }
                if (tripsDes != null)
                {
                    tripsDes.Dispose();
                }
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Obtiene a partir de la firma, el versionid y el nombre del elemento
        /// </summary>
        /// <param name="signature">Firma</param>
        /// <param name="name">Nombre del elemento</param>
        /// para después desencriptar la firma de la aplicación</param>
        /// <returns>Version id y firma de la aplicación</returns>
        public KeyValuePair <Guid, string> GetInfoFromSignature(string signature, string name = null)
        {
            KeyValuePair <Guid, string> pairResult = new KeyValuePair <Guid, string>();

            try
            {
                string result = string.Empty;
                if (!string.IsNullOrEmpty(signature))
                {
                    result = DecryptKey(signature);
                    if (!string.IsNullOrEmpty(result))
                    {
                        Guid   versionId = new Guid(result.Split(delimiter).FirstOrDefault());
                        string text      = GetSubString(result);
                        if (versionId != null && !string.IsNullOrEmpty(text))
                        {
                            pairResult = new KeyValuePair <Guid, string>(versionId, text);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //log.ErrorException("Exception getting info from signature: ", ex);
            }
            return(pairResult);

            /// <summary>
            /// Obtener cadena a partir de un elemento delimitador
            /// </summary>
            /// <param name="text">Texto original</param>
            /// <returns>Texto a partir del delimietador</returns>
            string GetSubString(string text)
            {
                int init = 0;

                for (int i = text.Length - 1; i >= 0; i--)
                {
                    if (text[i] == delimiter)
                    {
                        init = i;
                        break;
                    }
                }
                text = text.Substring(init + 1, text.Length - init - 1);
                return(text);
            }

            //Desencriptado de la firma
            string DecryptKey(string text)
            {
                byte[] keyArray;
                byte[] arrayToEncript = Convert.FromBase64String(text);

                TripleDESCryptoServiceProvider tdes = null;

                byte[] resultArray;
                MD5CryptoServiceProvider hashmd5 = null;

                try
                {
                    //MD5
                    hashmd5  = new MD5CryptoServiceProvider();
                    keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                    hashmd5.Clear();
                    //3DAS
                    tdes = new TripleDESCryptoServiceProvider
                    {
                        Key     = keyArray,
                        Mode    = CipherMode.ECB,
                        Padding = PaddingMode.PKCS7
                    };
                    ICryptoTransform cTransform = tdes.CreateDecryptor();

                    resultArray = cTransform.TransformFinalBlock(arrayToEncript, 0, arrayToEncript.Length);
                    tdes.Clear();
                }
                finally
                {
                    if (tdes != null)
                    {
                        tdes.Dispose();
                    }
                    if (hashmd5 != null)
                    {
                        hashmd5.Dispose();
                    }
                }
                return(UTF8Encoding.UTF8.GetString(resultArray));
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Create a new SymCipher object with a random key based on the alg and mode supplied.
        /// </summary>
        /// <param name="symDef"></param>
        /// <param name="keyData"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static SymCipher Create(SymDefObject symDef = null,
                                       byte[] keyData      = null, byte[] iv = null)
        {
            if (symDef == null)
            {
                symDef = new SymDefObject(TpmAlgId.Aes, 128, TpmAlgId.Cfb);
            }

#if TSS_USE_BCRYPT
            BCryptAlgorithm alg = null;

            switch (symDef.Algorithm)
            {
            case TpmAlgId.Aes:
                alg = new BCryptAlgorithm(Native.BCRYPT_AES_ALGORITHM);
                break;

            case TpmAlgId.Tdes:
                alg = new BCryptAlgorithm(Native.BCRYPT_3DES_ALGORITHM);
                break;

            default:
                Globs.Throw <ArgumentException>("Unsupported symmetric algorithm "
                                                + symDef.Algorithm);
                return(null);
            }

            if (keyData == null)
            {
                keyData = Globs.GetRandomBytes(symDef.KeyBits / 8);
            }
            var key = alg.GenerateSymKey(symDef, keyData, GetBlockSize(symDef));
            //key = BCryptInterface.ExportSymKey(keyHandle);
            //keyHandle = alg.LoadSymKey(key, symDef, GetBlockSize(symDef));
            alg.Close();
            return(key == null ? null : new SymCipher(key, keyData, iv, GetBlockSize(symDef)));
#else // !TSS_USE_BCRYPT
            if (symDef.Mode == TpmAlgId.Ofb)
            {
                return(null);
            }

            var mode = GetCipherMode(symDef.Mode);
            if (mode == CipherMode_None)
            {
                return(null);
            }

            SymmetricAlgorithm alg = null; // = new RijndaelManaged();
            bool limitedSupport    = false;
            int  feedbackSize      = 0;

            switch (symDef.Algorithm)
            {
            case TpmAlgId.Aes:
                alg      = new RijndaelManaged();
                alg.Mode = mode == CipherMode.CFB ? CipherMode.ECB : mode;
                break;

            case TpmAlgId.Tdes:
                // DES and __3DES are not supported in TPM 2.0 rev. < 1.32
                alg      = new TripleDESCryptoServiceProvider();
                alg.Mode = mode;
                if (mode == CipherMode.CFB)
                {
                    feedbackSize = 8;
                }
                limitedSupport = true;
                break;

            default:
                //Globs.Throw<ArgumentException>("Unsupported symmetric algorithm " + symDef.Algorithm);
                return(null);
            }

            int blockSize = GetBlockSize(symDef);
            alg.KeySize      = symDef.KeyBits;
            alg.BlockSize    = blockSize * 8;
            alg.Padding      = PaddingMode.None;
            alg.FeedbackSize = feedbackSize == 0 ? alg.BlockSize : feedbackSize;

            if (keyData == null)
            {
                // Generate random key
                alg.IV = Globs.GetZeroBytes(blockSize);
                try
                {
                    alg.GenerateKey();
                }
                catch (Exception)
                {
                    alg.Dispose();
                    throw;
                }
            }
            else
            {
                // Use supplied key bits
                alg.Key = keyData;
                if (iv == null)
                {
                    iv = Globs.GetZeroBytes(blockSize);
                }
                else if (iv.Length != blockSize)
                {
                    Array.Resize(ref iv, blockSize);
                }
                alg.IV = iv;
            }

            var symCipher = new SymCipher(alg, mode);
            symCipher.LimitedSupport = limitedSupport;
            return(symCipher);
#endif // !TSS_USE_BCRYPT
        } // Create()