상속: DeriveBytes
예제 #1
1
파일: AES.cs 프로젝트: Robin--/RMLib
        /// <summary>
        /// Encrypts a string
        /// </summary>
        /// <param name="plaintext">Text to be encrypted</param>
        /// <param name="password">Password to encrypt with</param>
        /// <param name="salt">Salt to encrypt with</param>
        /// <returns>An encrypted string</returns>
        public static string Encrypt(string plaintext, string password, string salt)
        {
            string Result = "";

            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(password), Encoding.ASCII.GetBytes(salt), "SHA512", 12345);

            using (RijndaelManaged SymmetricKey = new RijndaelManaged())
            {
                SymmetricKey.Mode = CipherMode.CBC;
                using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(DerivedPassword.GetBytes(32), DerivedPassword.GetBytes(16)))
                {
                    using (MemoryStream MemStream = new MemoryStream())
                    {
                        using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                        {
                            byte[] PlainTextBytes = Encoding.ASCII.GetBytes(plaintext);
                            CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                            CryptoStream.FlushFinalBlock();
                            Result = Convert.ToBase64String(MemStream.ToArray());
                        }
                    }
                }
            }

            return Result;
        }
 public static string Encrypt(string plainText, string passPhrase)
 {
     byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                     {
                         cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                         cryptoStream.FlushFinalBlock();
                         byte[] cipherTextBytes = memoryStream.ToArray();
                         return Convert.ToBase64String(cipherTextBytes);
                     }
                 }
             }
         }
     }
 }
예제 #3
1
 protected static string DecryptString(string InputText, string Password)
 {
     try
     {
         RijndaelManaged RijndaelCipher = new RijndaelManaged();
         byte[] EncryptedData = Convert.FromBase64String(InputText);
         byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
         PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
         // Create a decryptor from the existing SecretKey bytes.
         ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
         MemoryStream memoryStream = new MemoryStream(EncryptedData);
         // Create a CryptoStream. (always use Read mode for decryption).
         CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
         // Since at this point we don't know what the size of decrypted data
         // will be, allocate the buffer long enough to hold EncryptedData;
         // DecryptedData is never longer than EncryptedData.
         byte[] PlainText = new byte[EncryptedData.Length];
         // Start decrypting.
         int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
         memoryStream.Close();
         cryptoStream.Close();
         // Convert decrypted data into a string.
         string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
         // Return decrypted string.
         return DecryptedData;
     }
     catch (Exception exception)
     {
         return (exception.Message);
     }
 }
예제 #4
0
        public static string Decrypt(string text)
        {
            string decryptedData = null;

            if (!string.IsNullOrEmpty(text)) {
                var rijndaelCipher = new RijndaelManaged();
                byte[] encryptedData = Convert.FromBase64String(text);
                byte[] salt = Encoding.ASCII.GetBytes(Password.Length.ToString());

                //Making of the key for decryption
                var secretKey = new PasswordDeriveBytes(Password, salt);

                //Creates a symmetric Rijndael decryptor object.
                ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
                var memoryStream = new MemoryStream(encryptedData);

                //Defines the cryptographics stream for decryption.THe stream contains decrpted data
                var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
                byte[] plainText = new byte[encryptedData.Length];
                int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                memoryStream.Close();
                cryptoStream.Close();

                //Converting to string
                decryptedData = Encoding.Unicode.GetString(plainText, 0, decryptedCount);
            }

            return decryptedData;
        }
예제 #5
0
        private static bool WriteObjectToXml(string path, object ob)
        {
            try
            {
                using (Stream fs = new FileStream(path, FileMode.Create))
                {
                    var rm = new RijndaelManaged();
                    rm.BlockSize = rm.KeySize;
                    var secretKey = new PasswordDeriveBytes(Encoding.Unicode.GetBytes(Salt),
                                                            Encoding.ASCII.GetBytes(Salt));
                    // ReSharper disable once CSharpWarnings::CS0618
                    rm.Key = secretKey.GetBytes(rm.KeySize/8);
                    rm.IV = rm.Key;
                    ICryptoTransform desEncrypt = rm.CreateEncryptor();

                    using (var cs = new CryptoStream(fs, desEncrypt, CryptoStreamMode.Write))
                    {
                        var xmlser = new XmlSerializer(typeof (Data));
                        xmlser.Serialize(cs, ob);
                    }
                    desEncrypt.Dispose();
                }
                return true;
            }
            catch (Exception ex)
            {
                Logger.Write(ex.Message);
                return false;
            }
        }
예제 #6
0
        /// <summary>
        /// Décrypte une chaine cryptée à partir d'un chiffreur symétrique
        /// </summary>
        /// <param name="base64String">chaine cryptée</param>
        /// <param name="pass">Mot de passe utilisé pour dériver la clé</param>
        /// <returns>Chaine décryptée</returns>
        private static string Decrypt(string base64String, string pass)
        {
            string result = string.Empty;

            System.Security.Cryptography.TripleDESCryptoServiceProvider des =
                new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            des.IV = new byte[8];
            System.Security.Cryptography.PasswordDeriveBytes pdb =
                new System.Security.Cryptography.PasswordDeriveBytes(pass, new byte[0]);
            des.Key = pdb.CryptDeriveKey("RC2", "SHA1", 128, new byte[8]);
            byte[] encryptedBytes = Convert.FromBase64String(base64String);

            using (MemoryStream ms = new MemoryStream(base64String.Length))
            {
                using (System.Security.Cryptography.CryptoStream decStream =
                           new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(),
                                                                         System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
                    decStream.FlushFinalBlock();
                    byte[] plainBytes = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(plainBytes, 0, (int)ms.Length);
                    result = Encoding.UTF8.GetString(plainBytes);
                }
            }
            return(result);
        }
예제 #7
0
        // ************************************** DEBUT 1 *****************************

        //public static string Encrypt(string original)
        //{
        //    MD5CryptoServiceProvider hashMd5 = new MD5CryptoServiceProvider();
        //    byte[] passwordHash = hashMd5.ComputeHash(
        //    UnicodeEncoding.Unicode.GetBytes(clefDuCryptage));

        //    TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
        //    des.Key = passwordHash;

        //    des.Mode = CipherMode.ECB;

        //    byte[] buffer = UnicodeEncoding.Unicode.GetBytes(original);

        //    return UnicodeEncoding.Unicode.GetString(
        //    des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));

        //}

        //public static String Decrypt(String StringToDecrypt)
        //{

        //    String StringDecrypted = "";
        //    MD5CryptoServiceProvider hashMd5 = new MD5CryptoServiceProvider();
        //    byte[] passwordHash = hashMd5.ComputeHash(
        //    UnicodeEncoding.Unicode.GetBytes(clefDuCryptage));

        //    TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
        //    des.Key = passwordHash;
        //    des.Mode = CipherMode.ECB;

        //    byte[] buffer = UnicodeEncoding.Unicode.GetBytes(StringToDecrypt);
        //    StringDecrypted = UnicodeEncoding.Unicode.GetString(
        //    des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length));

        //    return StringDecrypted;
        //}

        // ************************************** FIN 1 *****************************



        // ************************************** DEBUT 2 *****************************
        //public static string Encrypt(string input, string key)
        //{
        //    byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
        //    TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
        //    tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
        //    tripleDES.Mode = CipherMode.ECB;
        //    tripleDES.Padding = PaddingMode.PKCS7;
        //    ICryptoTransform cTransform = tripleDES.CreateEncryptor();
        //    byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
        //    tripleDES.Clear();
        //    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        //}

        //public static string Decrypt(string input, string key)
        //{
        //    byte[] inputArray = Convert.FromBase64String(input);
        //    TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
        //    tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
        //    tripleDES.Mode = CipherMode.ECB;
        //    tripleDES.Padding = PaddingMode.PKCS7;
        //    ICryptoTransform cTransform = tripleDES.CreateDecryptor();
        //    byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
        //    tripleDES.Clear();
        //    return UTF8Encoding.UTF8.GetString(resultArray);
        //}
        // **************************************  FIN 2 *****************************

        /// <summary>
        /// Crypte une chaine en utilisant un chiffreur symétrique
        /// </summary>
        /// <param name="plainText">Chaine à crypter</param>
        /// <param name="pass">Mot de passe utilisé pour dériver la clé</param>
        /// <returns>Chaine cryptée</returns>
        public static string Encrypt(string plainText, string pass)
        {
            string result = string.Empty;

            System.Security.Cryptography.TripleDESCryptoServiceProvider des =
                new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            des.IV = new byte[8];

            System.Security.Cryptography.PasswordDeriveBytes pdb =
                new System.Security.Cryptography.PasswordDeriveBytes(pass, new byte[0]);

            des.Key = pdb.CryptDeriveKey("RC2", "SHA1", 128, new byte[8]);

            using (MemoryStream ms = new MemoryStream(plainText.Length * 2))
            {
                using (System.Security.Cryptography.CryptoStream encStream = new
                                                                             System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(),
                                                                                                                       System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
                    encStream.Write(plainBytes, 0, plainBytes.Length);
                    encStream.FlushFinalBlock();
                    byte[] encryptedBytes = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(encryptedBytes, 0, (int)ms.Length);
                    encStream.Close();
                    ms.Close();
                    result = Convert.ToBase64String(encryptedBytes);
                }
            }
            return(result);
        }
예제 #8
0
        public static string Encrypt(string plainText)
        {
            // Encryption operates on byte arrays, not on strings.
            byte[] plainTextBytes =
              System.Text.Encoding.Unicode.GetBytes(plainText);

            // Derive a key from the password.
            PasswordDeriveBytes passwordDerivedBytes = new PasswordDeriveBytes(NOT_SECRET_KEY,
                new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});

            // Use Rijndael symmetric algorithm to do the encryption.
            Rijndael rijndaelAlgorithm = Rijndael.Create();
            rijndaelAlgorithm.Key = passwordDerivedBytes.GetBytes(32);
            rijndaelAlgorithm.IV = passwordDerivedBytes.GetBytes(16);

            MemoryStream memoryStream = new MemoryStream();

            CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelAlgorithm.CreateEncryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.Close();

            byte[] encryptedBytes = memoryStream.ToArray();

            return Convert.ToBase64String(encryptedBytes);
        }
예제 #9
0
        public static string Decrypt(string encryptedText)
        {
            RegistryKey registryKey =
                Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\10.0\PbsEncryptionKey");
            var password = (string)registryKey.GetValue("Key");
            var passwordDerivedBytes = new PasswordDeriveBytes(password, _salt);
            byte[] encryptedTextBytes = Convert.FromBase64String(encryptedText);

            using (var memoryStream = new MemoryStream())
            {
                using (var rijndael = Rijndael.Create())
                {
                    using (
                        var cryptoTransform = rijndael.CreateDecryptor(passwordDerivedBytes.GetBytes(32), 
                            passwordDerivedBytes.GetBytes(16)))
                    {
                        using (
                            var cryptoStream = new CryptoStream(memoryStream, cryptoTransform,
                                CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);
                            cryptoStream.Close();
                            return Encoding.Unicode.GetString(memoryStream.ToArray());
                        }
                    }
                }
            }
        }
예제 #10
0
파일: Cryptography.cs 프로젝트: ngocpq/MHX2
        // Decrypt a file into another file using a password
        public static void Decrypt(string fileIn, string fileOut, string Password)
        {
            // First we are going to open the file streams
            FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
            FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);

            // Then we are going to derive a Key and an IV from the Password and create an algorithm
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            Rijndael alg = Rijndael.Create();
            alg.Key = pdb.GetBytes(32);
            alg.IV = pdb.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.
            CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), 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 bufferLen = 4096;
            byte[] buffer = new byte[bufferLen];
            int bytesRead;

            do
            {
                // read a chunk of data from the input file
                bytesRead = fsIn.Read(buffer, 0, bufferLen);

                // Decrypt it
                cs.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);

            cs.Close();
            fsIn.Close();
        }
예제 #11
0
 /// <summary>
 /// Decrypts a byte array with a password
 /// </summary>
 /// <param name="data">Data to decrypt</param>
 /// <param name="password">Password to use</param>
 /// <param name="paddingMode">Padding mode to use</param>
 /// <returns>Decrypted byte array</returns>
 /// <exception cref="System.ArgumentNullException">
 /// data
 /// or
 /// password
 /// </exception>
 /// <exception cref="ArgumentNullException"></exception>
 public static byte[] DecryptData(byte[] data, string password, PaddingMode paddingMode)
 {
     if (data == null || data.Length == 0)
         throw new ArgumentNullException("data");
     if (password == null)
         throw new ArgumentNullException("password");
     var pdb = new PasswordDeriveBytes(password, Encoding.UTF8.GetBytes("Salt"));
     var rm = new RijndaelManaged { Padding = paddingMode };
     ICryptoTransform decryptor = rm.CreateDecryptor(pdb.GetBytes(16), pdb.GetBytes(16));
     pdb.Dispose();
     using (var msDecrypt = new MemoryStream(data))
     using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
     {
         // Decrypted bytes will always be less then encrypted bytes, so length of encrypted data will be big enough for buffer.
         byte[] fromEncrypt = new byte[data.Length];
         // Read as many bytes as possible.
         int read = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
         if (read < fromEncrypt.Length)
         {
             // Return a byte array of proper size.
             byte[] clearBytes = new byte[read];
             Buffer.BlockCopy(fromEncrypt, 0, clearBytes, 0, read);
             return clearBytes;
         }
         return fromEncrypt;
     }
 }
예제 #12
0
        public static string Decrypt(string cipherText, string passPhrase)
        {
            if (cipherText != null && cipherText != "")
            {
                byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
                using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
                {
                    byte[] keyBytes = password.GetBytes(keysize / 8);
                    using (RijndaelManaged symmetricKey = new RijndaelManaged())
                    {
                        symmetricKey.Mode = CipherMode.CBC;
                        using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                        {
                            using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                            {
                                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                                {
                                    byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                                    int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                    return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                                }
                            }
                        }
                    }
                }
            }

            return "";
        }
예제 #13
0
        public string Decrypt(string cipherText, string password)
        {
            if (string.IsNullOrEmpty(cipherText))
                return cipherText;
            try
            {
                if (System.Web.HttpContext.Current != null)
                    cipherText = System.Web.HttpContext.Current.Server.UrlDecode(cipherText);

                cipherText = cipherText.Replace(" ", "+");
                byte[] cipherBytes = Convert.FromBase64String(cipherText);

                PasswordDeriveBytes pdb = new PasswordDeriveBytes(password,
                    new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65,
            0x64, 0x76, 0x65, 0x64, 0x65, 0x76});

                byte[] decryptedData = Decrypt(cipherBytes,
                    pdb.GetBytes(32), pdb.GetBytes(16));

                return System.Text.Encoding.Unicode.GetString(decryptedData);
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// Encrypts a string
        /// </summary>
        /// <param name="plainText">Text to be encrypted</param>
        /// <param name="password">Password to encrypt with</param>
        /// <param name="salt">Salt to encrypt with</param>
        /// <param name="hashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="passwordIterations">Number of iterations to do. The number of times the algorithm is run on the text. </param>
        /// <param name="initialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="keySize">Can be 128, 192, or 256</param>
        /// <returns>An encrypted string</returns>
        public static string Encrypt(string plainText, string password, string salt = "69ad1bfbd6605f3f6a3011460cdfb9db7757e0f9", string hashAlgorithm = "SHA1", int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY", int keySize = 256)
        {
            if (string.IsNullOrEmpty(plainText))
                return "";

            byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
            byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            var derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations);
            byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
            var symmetricKey = new RijndaelManaged {Mode = CipherMode.CBC};
            byte[] cipherTextBytes;

            using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initialVectorBytes))
            {
                using (MemoryStream memStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        cipherTextBytes = memStream.ToArray();

                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }
            symmetricKey.Clear();

            return Convert.ToBase64String(cipherTextBytes);
        }
예제 #15
0
	public void Ctor_PasswordSaltNull ()
	{
		PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", null);
		Assert.AreEqual ("SHA1", pdb.HashName, "HashName");
		Assert.AreEqual (100, pdb.IterationCount, "IterationCount");
		Assert.IsNull (pdb.Salt, "Salt");
	}
예제 #16
0
파일: Encryption.cs 프로젝트: BjkGkh/R106
		/// <summary>
		/// Encrypts a string
		/// </summary>
		/// <param name="PlainText">Text to be encrypted</param>
		/// <param name="Password">Password to encrypt with</param>
		/// <param name="Salt">Salt to encrypt with</param>
		/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
		/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
		/// <param name="PasswordIterations">Number of iterations to do</param>
		/// <param name="KeySize">Can be 128, 192, or 256</param>
		/// <returns>An encrypted bytes</returns>
		public static byte[] Encrypt(byte[] PlainText, byte[] Password, byte[] InitialVector,
			byte[] Salt)
		{
			PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, Salt, HASH_ALGORITHM, PASSWORDITERATIONS);
			byte[] KeyBytes = DerivedPassword.GetBytes(KEY_SIZE / 8);
			RijndaelManaged SymmetricKey = new RijndaelManaged();
			SymmetricKey.Mode = CipherMode.CBC;
			byte[] CipherTextBytes = null;

			using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVector))
			{
				using (MemoryStream MemStream = new MemoryStream())
				{
					using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
					{
						CryptoStream.Write(PlainText, 0, PlainText.Length);
						CryptoStream.FlushFinalBlock();
						CipherTextBytes = MemStream.ToArray();
						MemStream.Close();
						CryptoStream.Close();
					}
				}
			}

			SymmetricKey.Clear();
			return CipherTextBytes;
			//return Encoding.UTF8.GetBytes(Convert.ToBase64String(CipherTextBytes));
		}
예제 #17
0
파일: EncDec.cs 프로젝트: bartvanderwal/Hre
        /// <summary>
        /// Encrypt a string into a string using a password. Uses Encrypt(byte[], byte[], byte[]) 
        /// </summary>
        public static string Encrypt(string clearText, string Password, bool useUrlEncoding)
        {
            // First we need to turn the input string into a byte array.
            byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);

            // Then, we need to turn the password into Key and IV
            // We are using salt to make it harder to guess our key
            // using a dictionary attack -
            // trying to guess a password by enumerating all possible words.
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
                new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});

            // Now get the key/IV and do the encryption using the function that accepts byte arrays.
            // Using PasswordDeriveBytes object we are first getting 32 bytes for the Key
            // (the default Rijndael key length is 256bit = 32bytes) and then 16 bytes for the IV.
            // IV should always be the block size, which is by default 16 bytes (128 bit) for Rijndael.
            // If you are using DES/TripleDES/RC2 the block size is 8 bytes and so should be the IV size.
            // You can also read KeySize/BlockSize properties off the algorithm to find out the sizes.
            byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));

            // Now we need to turn the resulting byte array into a string.
            // A common mistake would be to use an Encoding class for that.
            // It does not work because not all byte values can be represented by characters.
            // We are going to be using Base64 encoding that is designed exactly for what we are trying to do.
            string data = HttpUtility.UrlEncode(Convert.ToBase64String(encryptedData));

            // Optionally URL encode the encrypted data (use if data will be put in URL as URL parameter/querystring).
            if (useUrlEncoding) {
                data = HttpUtility.UrlEncode(data );
            }

            return data;
        }
예제 #18
0
 public static string Decrypt(string cipherText, string Password)
 {
     byte[] cipherData = Convert.FromBase64String(cipherText);
       PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 110, 0x20, 0x4d, 0x65, 100, 0x76, 0x65, 100, 0x65, 0x76 });
       byte[] buffer2 = Decrypt(cipherData, bytes.GetBytes(0x20), bytes.GetBytes(0x10));
       return Encoding.Unicode.GetString(buffer2);
 }
예제 #19
0
파일: Cryptography.cs 프로젝트: tonix/Onet
        // Decrypt a string into a string using a password
        //    Uses Decrypt(byte[], byte[], byte[])
        public static string Decrypt(string cipherText, string Password)
        {
            // First we need to turn the input string into a byte array.
            // We presume that Base64 encoding was used
            byte[] cipherBytes = Convert.FromBase64String(cipherText);

            // Then, we need to turn the password into Key and IV
            // We are using salt to make it harder to guess our key using a dictionary attack -
            // trying to guess a password by enumerating all possible words.
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
                                                              new byte[]
                                                                  {
                                                                      0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76,
                                                                      0x65, 0x64, 0x65, 0x76
                                                                  });

            // Now get the key/IV and do the decryption using the function that accepts byte arrays.
            // Using PasswordDeriveBytes object we are first getting 32 bytes for the Key
            // (the default Rijndael key length is 256bit = 32bytes) and then 16 bytes for the IV.
            // IV should always be the block size, which is by default 16 bytes (128 bit) for Rijndael.
            // If you are using DES/TripleDES/RC2 the block size is 8 bytes and so should be the IV size.
            // You can also read KeySize/BlockSize properties off the algorithm to find out the sizes.
            byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));

            // Now we need to turn the resulting byte array into a string.
            // A common mistake would be to use an Encoding class for that. It does not work
            // because not all byte values can be represented by characters.
            // We are going to be using Base64 encoding that is designedexactly for what we are
            // trying to do.
            return System.Text.Encoding.Unicode.GetString(decryptedData);
        }
 public string Encrypt(string Data, string Password, int Bits)
 {
     byte[] byteArray2;
     byte[] byteArray3;
     if (this._userKey != "bengkel1q2w3e")
     {
         return "Hubungi Admin";
     }
     byte[] byteArray1 = Encoding.Unicode.GetBytes(Data);
     PasswordDeriveBytes passwordDeriveBytes1 = new PasswordDeriveBytes(Password, new byte[] { byte.MinValue, 1, 2, 28, 29, 30, 3, 4, 5, 15, 32, 33, 173, 175, 164 });
     if (Bits == 128)
     {
         byteArray2 = this.Encrypt(byteArray1, passwordDeriveBytes1.GetBytes(16), passwordDeriveBytes1.GetBytes(16));
         return Convert.ToBase64String(byteArray2);
     }
     if (Bits == 192)
     {
         byteArray3 = this.Encrypt(byteArray1, passwordDeriveBytes1.GetBytes(24), passwordDeriveBytes1.GetBytes(16));
         return Convert.ToBase64String(byteArray3);
     }
     if (Bits != 256)
     {
         return string.Concat(Bits);
     }
     byte[] byteArray4 = this.Encrypt(byteArray1, passwordDeriveBytes1.GetBytes(32), passwordDeriveBytes1.GetBytes(16));
     return Convert.ToBase64String(byteArray4);
 }
예제 #21
0
파일: Rijndael.cs 프로젝트: Acraciel/Gale
        /// <summary>
        /// Desencripta dado el Cifrado Rijndael
        /// </summary>
        /// <param name="data">Información a Desencriptar</param>
        /// <param name="cypher">Clave a Utilizar para descifrar</param>
        /// <returns>Información Desencriptada</returns>
        public static string Decrypt(string data, string cypher, Boolean webSafe)
        {
            if (webSafe)
            {
                data = Gale.Serialization.FromBase64(data);
            }

            string ciphertext = data;
            try
            {
                RijndaelManaged rijndaelCipher = new RijndaelManaged();

                byte[] ciphertextByte = Convert.FromBase64String(ciphertext);
                byte[] saltByte = Encoding.ASCII.GetBytes(cypher.Length.ToString());

                PasswordDeriveBytes secretKey = new PasswordDeriveBytes(cypher, saltByte);
                ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(ciphertextByte);
                CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

                byte[] plainText = new byte[ciphertextByte.Length + 1];
                int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);

                memoryStream.Close();
                cryptoStream.Close();

                return Encoding.UTF8.GetString(plainText, 0, decryptedCount);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        public static string Decrypt(string TextToBeDecrypted)
        {
            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            string Password = "******";
            string DecryptedData;

            try
            {
                byte[] EncryptedData = Convert.FromBase64String(TextToBeDecrypted);

                byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
                //Making of the key for decryption
                PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
                //Creates a symmetric Rijndael decryptor object.
                ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

                MemoryStream memoryStream = new MemoryStream(EncryptedData);
                //Defines the cryptographics stream for decryption.THe stream contains decrpted data
                CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

                byte[] PlainText = new byte[EncryptedData.Length];
                int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
                memoryStream.Close();
                cryptoStream.Close();

                //Converting to string
                DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
            }
            catch
            {
                DecryptedData = TextToBeDecrypted;
            }
            return DecryptedData;
        }
예제 #23
0
        public static string Encrypt(string plainText)
        {
            var registryKey =
                Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\10.0\PbsEncryptionKey");
            var password = (string)registryKey.GetValue("Key");
            var passwordDerivedBytes = new PasswordDeriveBytes(password, _salt);
            var plainTextBytes = Encoding.Unicode.GetBytes(plainText);

            using (var memoryStream = new MemoryStream())
            {
                using (Rijndael rijndael = Rijndael.Create())
                {
                    using (
                        ICryptoTransform cryptoTransform = rijndael.CreateEncryptor(passwordDerivedBytes.GetBytes(32), rgbIV: passwordDerivedBytes.GetBytes(16)))
                    {
                        using (
                            var cryptoStream = new CryptoStream(memoryStream, cryptoTransform,
                                CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            return Convert.ToBase64String(memoryStream.ToArray());
                        }
                    }
                }
            }
        }
예제 #24
0
    internal static void Decrypt(string fileIn, string fileOut)
    {
        System.IO.FileStream fsIn  = new System.IO.FileStream(fileIn, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        System.IO.FileStream fsOut = new System.IO.FileStream(fileOut, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);

        System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(Password,
                                                                                                                    new byte[] { 0x49, 0x49, 0x35, 0x6e, 0x76, 0x4d,
                                                                                                                                 0x65, 0x64, 0x76, 0x76, 0x64, 0x65, 0x76 });
        System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
        alg.Key = pdb.GetBytes(32);
        alg.IV  = pdb.GetBytes(16);

        System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(fsOut, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

        int bufferLen = 4096;

        byte[] buffer = new byte[bufferLen];
        int    bytesRead;

        do
        {
            // read a chunk of data from the input file
            bytesRead = fsIn.Read(buffer, 0, bufferLen);
            // Decrypt it
            cs.Write(buffer, 0, bytesRead);
        } while (bytesRead != 0);
        cs.Close();
        fsIn.Close();
    }
예제 #25
0
 public static string Decrypt(string cipherTextPassword, string key)
 {
     byte[] cipherBytes = Convert.FromBase64String(cipherTextPassword);
     PasswordDeriveBytes pdb = new PasswordDeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
     byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
     return System.Text.Encoding.Unicode.GetString(decryptedData);
 }
예제 #26
0
 /// <summary>
 /// Encrypts a string
 /// </summary>
 /// <param name="PlainText">Text to be encrypted</param>
 /// <param name="Password">Password to encrypt with</param>
 /// <param name="Salt">Salt to encrypt with</param>
 /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
 /// <param name="PasswordIterations">Number of iterations to do</param>
 /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
 /// <param name="KeySize">Can be 128, 192, or 256</param>
 /// <returns>An encrypted string</returns>
 public static string Encrypt(string PlainText, string Password,
     string Salt = "Kosher", string HashAlgorithm = "SHA1",
     int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
     int KeySize = 256)
 {
     if (string.IsNullOrEmpty(PlainText))
         return "";
     byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
     byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
     byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
     PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
     byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
     RijndaelManaged SymmetricKey = new RijndaelManaged();
     SymmetricKey.Mode = CipherMode.CBC;
     byte[] CipherTextBytes = null;
     using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
     {
         using (MemoryStream MemStream = new MemoryStream())
         {
             using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
             {
                 CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                 CryptoStream.FlushFinalBlock();
                 CipherTextBytes = MemStream.ToArray();
                 MemStream.Close();
                 CryptoStream.Close();
             }
         }
     }
     SymmetricKey.Clear();
     return Convert.ToBase64String(CipherTextBytes);
 }
예제 #27
0
 public static string Encrypt(string password, string key)
 {
     byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(password);
     PasswordDeriveBytes pdb = new PasswordDeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
     byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
     return Convert.ToBase64String(encryptedData);
 }
예제 #28
0
	public void Ctor_PasswordSalt ()
	{
		PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt);
		Assert.AreEqual ("SHA1", pdb.HashName, "HashName");
		Assert.AreEqual (100, pdb.IterationCount, "IterationCount");
		Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt");
	}
예제 #29
0
        /// <summary>
        /// Decrypts a string which was encrypted using this class
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public String Decrypt(String text)
        {
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
            byte[] cipherTextBytes = Convert.FromBase64String(text);

            PasswordDeriveBytes password = new PasswordDeriveBytes(key,saltValueBytes,"SHA1",1);
            byte[] keyBytes = password.GetBytes(keySize / 8);

            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;

            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes,initVectorBytes);
            MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
            CryptoStream cryptoStream = new CryptoStream(memoryStream,decryptor,CryptoStreamMode.Read);

            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
            int decryptedByteCount = cryptoStream.Read(plainTextBytes,0,plainTextBytes.Length);

            memoryStream.Close();
            cryptoStream.Close();

            string plainText = Encoding.UTF8.GetString(plainTextBytes,0,decryptedByteCount);
            return plainText;
        }
예제 #30
0
파일: Encryption.cs 프로젝트: BjkGkh/R106
		/// <summary>
		/// Decrypts a string
		/// </summary>
		/// <param name="CipherText">Text to be decrypted</param>
		/// <param name="Password">Password to decrypt with</param>
		/// <param name="Salt">Salt to decrypt with</param>
		/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
		/// <param name="PasswordIterations">Number of iterations to do</param>
		/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
		/// <param name="KeySize">Can be 128, 192, or 256</param>
		/// <returns>A decrypted byte array in UTF-8 format</returns>
		public static byte[] Decrypt(byte[] CipherText, byte[] Password, byte[] InitialVector, byte[] Salt)
		{
			PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, Salt, HASH_ALGORITHM, PASSWORDITERATIONS);
			byte[] KeyBytes = DerivedPassword.GetBytes(KEY_SIZE / 8);
			RijndaelManaged SymmetricKey = new RijndaelManaged();
			SymmetricKey.Mode = CipherMode.CBC;
			byte[] PlainTextBytes = new byte[CipherText.Length];
			int ByteCount = 0;
			using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVector))
			{
				using (MemoryStream MemStream = new MemoryStream(CipherText))
				{
					using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
					{

						ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
						MemStream.Close();
						CryptoStream.Close();
					}
				}
			}
			SymmetricKey.Clear();
			byte[] decrypted = new byte[ByteCount];
			Array.Copy(PlainTextBytes, decrypted, ByteCount);
			return decrypted;
		}
예제 #31
0
        /// <summary>
        /// Decrypts a string
        /// </summary>
        /// <param name="CipherText">Text to be decrypted</param>
        /// <param name="Password">Password to decrypt with</param>
        /// <param name="Salt">Salt to decrypt with</param>
        /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="PasswordIterations">Number of iterations to do</param>
        /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="KeySize">Can be 128, 192, or 256</param>
        /// <returns>A decrypted string</returns>
        public static string Decrypt(string CipherText, string Password,
            string Salt = "Kosher", string HashAlgorithm = "SHA1",
            int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
            int KeySize = 256)
        {
            if (string.IsNullOrEmpty(CipherText))
                return "";
            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
            byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
            byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
            byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
            RijndaelManaged SymmetricKey = new RijndaelManaged();
            SymmetricKey.Mode = CipherMode.CBC;
            byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
            int ByteCount = 0;
            using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                    {

                        ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }
            SymmetricKey.Clear();
            return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
        }
        /// <summary>
        /// Decrypts a string
        /// </summary>
        /// <param name="cipherText">Text to be decrypted</param>
        /// <param name="password">Password to decrypt with</param>
        /// <param name="salt">Salt to decrypt with</param>
        /// <param name="hashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="passwordIterations">Number of iterations to do. The number of times the algorithm is run on the text. </param>
        /// <param name="initialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="keySize">Can be 128, 192, or 256</param>
        /// <returns>A decrypted string</returns>
        public static string Decrypt(string cipherText, string password, string salt = "69ad1bfbd6605f3f6a3011460cdfb9db7757e0f9", string hashAlgorithm = "SHA1", int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY", int keySize = 256)
        {
            if (string.IsNullOrEmpty(cipherText))
                return "";

            byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
            byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
            var derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations);
            byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
            var symmetricKey = new RijndaelManaged {Mode = CipherMode.CBC};
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
            int byteCount;

            using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes))
            {
                using (MemoryStream memStream = new MemoryStream(cipherTextBytes))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                    {
                        byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }
            symmetricKey.Clear();

            return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount);
        }
예제 #33
0
        // Decrypt a file into another file using a password
        public static void Decrypt(string fileIn, string fileOut)
        {
            FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
            FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(PASSWORD,
                new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
                0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
            Rijndael alg = Rijndael.Create();

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

            CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write);

            int bufferLen = 4096;
            byte[] buffer = new byte[bufferLen];
            int bytesRead;

            do
            {
                bytesRead = fsIn.Read(buffer, 0, bufferLen);
                cs.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);

            cs.Close(); // this will also close the unrelying fsOut stream
            fsIn.Close();
        }
예제 #34
0
    internal static byte[] Decrypt(byte[] cipherData)
    {
        System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(Password,
                                                                                                                    new byte[] { 0x49, 0x49, 0x35, 0x6e, 0x76, 0x4d,
                                                                                                                                 0x65, 0x64, 0x76, 0x76, 0x64, 0x65, 0x76 });

        return(Decrypt(cipherData, pdb.GetBytes(32), pdb.GetBytes(16)));
    }
예제 #35
0
    public static string Decrypt(string cipherText)
    {
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(Password,
                                                                                                                    new byte[] { 0x49, 0x49, 0x35, 0x6e, 0x76, 0x4d,
                                                                                                                                 0x65, 0x64, 0x76, 0x76, 0x64, 0x65, 0x76 });

        byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
        return(System.Text.Encoding.Unicode.GetString(decryptedData));
    }
예제 #36
0
    public static string Encrypt(string clearText)
    {
        byte[] clearBytes =
            System.Text.Encoding.Unicode.GetBytes(clearText);
        System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(Password,
                                                                                                                    new byte[] { 0x49, 0x49, 0x35, 0x6e, 0x76, 0x4d,
                                                                                                                                 0x65, 0x64, 0x76, 0x76, 0x64, 0x65, 0x76 });

        byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));

        return(Convert.ToBase64String(encryptedData));
    }
        public void PasswordDerivedBytes_Test()
        {
            byte[] randBytes = new byte[5];
            new Random(10032010).NextBytes(randBytes);


            var tdes  = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            var pwddb = new System.Security.Cryptography.PasswordDeriveBytes("1", new byte[] { 1 });

            tdes.Key = pwddb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);
            //string s = Convert.ToBase64String(tdes.Key);
        }
예제 #38
0
        public static string Encrypt(string clearText, string Password)
        {
            byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
            System.Security.Cryptography.PasswordDeriveBytes pdb =
                new System.Security.Cryptography.PasswordDeriveBytes
                    (Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
                                            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

            // PasswordDeriveBytes is for getting Key and IV.
            // Using PasswordDeriveBytes object we are first getting 32 bytes for the Key (the default
            //Rijndael key length is 256bit = 32bytes) and then 16 bytes for the IV.
            // IV should always be the block size, which is by default 16 bytes (128 bit) for Rijndael.

            byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return(Convert.ToBase64String(encryptedData));
        }
예제 #39
0
        public byte[] Decrypt(byte[] B, String PSW)
        {
            System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(PSW, new Byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            System.IO.MemoryStream           ms   = new System.IO.MemoryStream();
            System.Security.Cryptography.Aes AESE = new System.Security.Cryptography.AesManaged();

            AESE.Key = pdb.GetBytes(AESE.KeySize / 8);
            AESE.IV  = pdb.GetBytes(AESE.BlockSize / 8);

            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, AESE.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

            cs.Write(B, 0, B.Length);

            cs.Close();

            return(ms.ToArray());
        }
예제 #40
0
 public string AES_Encrypt(string input, string password)
 {
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input);
     System.Security.Cryptography.PasswordDeriveBytes passwordDeriveBytes = new System.Security.Cryptography.PasswordDeriveBytes(password, new byte[]
     {
         73,
         118,
         97,
         110,
         32,
         77,
         101,
         100,
         118,
         101,
         100,
         101,
         118
     });
     byte[] inArray = Methods.AES_Encrypt(bytes, passwordDeriveBytes.GetBytes(32), passwordDeriveBytes.GetBytes(16));
     return(System.Convert.ToBase64String(inArray));
 }
예제 #41
0
 public string AES_Decrypt(string input, string password)
 {
     byte[] cipherData = System.Convert.FromBase64String(input);
     System.Security.Cryptography.PasswordDeriveBytes passwordDeriveBytes = new System.Security.Cryptography.PasswordDeriveBytes(password, new byte[]
     {
         73,
         118,
         97,
         110,
         32,
         77,
         101,
         100,
         118,
         101,
         100,
         101,
         118
     });
     byte[] bytes = Methods.AES_Decrypt(cipherData, passwordDeriveBytes.GetBytes(32), passwordDeriveBytes.GetBytes(16));
     return(System.Text.Encoding.UTF8.GetString(bytes));
 }
예제 #42
0
파일: EnDec.cs 프로젝트: liyang-live/LabUI
    internal static string DecryptMD5(string cipherText, string p_strSaltValue)
    {
        string strReturn = String.Empty;

        //  Convert strings defining encryption key characteristics into byte
        //  arrays. Let us assume that strings only contain ASCII codes.
        //  If strings include Unicode characters, use Unicode, UTF7, or UTF8
        //  encoding.
        try
        {
            byte[] initVectorBytes;
            initVectorBytes = System.Text.Encoding.ASCII.GetBytes(m_strInitVector);
            byte[] saltValueBytes;
            saltValueBytes = System.Text.Encoding.ASCII.GetBytes(p_strSaltValue);
            //  Convert our ciphertext into a byte array.
            byte[] cipherTextBytes;
            cipherTextBytes = Convert.FromBase64String(cipherText);
            //  First, we must create a password, from which the key will be
            //  derived. This password will be generated from the specified
            //  passphrase and salt value. The password will be created using
            //  the specified hash algorithm. Password creation can be done in
            //  several iterations.
            System.Security.Cryptography.PasswordDeriveBytes password;
            // Dim password As Rfc2898DeriveBytes
            // password = New Rfc2898DeriveBytes(m_strPassPhrase, _
            //                                 saltValueBytes, _
            //                                 m_strPasswordIterations)
            password = new System.Security.Cryptography.PasswordDeriveBytes(m_strPassPhrase, saltValueBytes, m_strHashAlgorithm, m_strPasswordIterations);
            //  Use the password to generate pseudo-random bytes for the encryption
            //  key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes;
            int    intKeySize;
            intKeySize = ((int)((m_intKeySize / 8)));
            keyBytes   = password.GetBytes(intKeySize);
            //  Create uninitialized Rijndael encryption object.
            System.Security.Cryptography.RijndaelManaged symmetricKey;
            symmetricKey = new System.Security.Cryptography.RijndaelManaged();
            //  It is reasonable to set encryption mode to Cipher Block Chaining
            //  (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC;
            // symmetricKey.Padding = PaddingMode.Zeros
            //  Generate decryptor from the existing key bytes and initialization
            //  vector. Key size will be defined based on the number of the key
            //  bytes.
            System.Security.Cryptography.ICryptoTransform decryptor;
            decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
            //  Define memory stream which will be used to hold encrypted data.
            System.IO.MemoryStream memoryStream;
            memoryStream = new System.IO.MemoryStream(cipherTextBytes);
            //  Define memory stream which will be used to hold encrypted data.
            System.Security.Cryptography.CryptoStream cryptoStream;
            cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read);
            //  Since at this point we don't know what the size of decrypted data
            //  will be, allocate the buffer long enough to hold ciphertext;
            //  plaintext is never longer than ciphertext.
            byte[] plainTextBytes;
            plainTextBytes = new byte[cipherTextBytes.Length];
            int decryptedByteCount;
            decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            //  Close both streams.
            memoryStream.Close();
            cryptoStream.Close();
            //  Convert decrypted data into a string.
            //  Let us assume that the original plaintext string was UTF8-encoded.
            string plainText;
            plainText = System.Text.Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
            //  Return decrypted string.
            strReturn = plainText;
        }
        catch (Exception ex)
        {
            strReturn = null;
        }
        return(strReturn);
    }