GetBytes() private method

private GetBytes ( int cb ) : byte[]
cb int
return byte[]
Exemplo n.º 1
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);
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// 문자열을 복호화
        /// </summary>
        /// <param name="InputText"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        internal string GetDecryptedString(string InputText, string Password)
        {
            byte[] EncryptedData = Convert.FromBase64String(InputText);
            #region 복호화 키 객체 만들기
            RijndaelManaged RijndaelCipher = new RijndaelManaged();
            byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
            // Decryptor 객체를 만듭니다.
            ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
            #endregion
            #region 복호화
            byte[] PlainText = null;
            int DecryptedCount = 0;
            using (MemoryStream memoryStream = new MemoryStream(EncryptedData))
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read))
                {
                    /*
                     * 복호화된 데이터를 담을 바이트 배열을 선언합니다.
                       길이는 알 수 없지만, 일단 복호화되기 전의 데이터의 길이보다는
                       길지 않을 것이기 때문에 그 길이로 선언합니다
                     */
                    PlainText = new byte[EncryptedData.Length];

                    // 복호화 시작
                    DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
                }
            }
            // 복호화된 데이터를 문자열로 바꿉니다.
            string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
            //복호화 키 객체 해제
            Decryptor.Dispose();
            #endregion
            return DecryptedData;
        }
Exemplo n.º 3
0
        public static void EncryptData(String inName, String outName, String password)
        {
            FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, keySalt);

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

            CryptoStream cs = new CryptoStream(fout, alg.CreateEncryptor(), CryptoStreamMode.Write);

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

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

            cs.Close();
            fin.Close();
        }
 public string Encrypt(string clearText)
 {
     passwordDeriveBytes = new PasswordDeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
     var clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
     var encryptedData = Encrypt(clearBytes, passwordDeriveBytes.GetBytes(32), passwordDeriveBytes.GetBytes(16));
     return Convert.ToBase64String(encryptedData);
 }
Exemplo n.º 5
0
        /// <summary>
        /// Encrypt string
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        public static string EncryptString(string inputString)
        {
            try
            {
                if (inputString != null)
                {
                    // First we need to turn the input string into a byte array.
                    byte[] queryStringBytes = Encoding.UTF8.GetBytes(inputString);//Encoding.Unicode.GetBytes(queryString) ovo je izbacivalo pogrešku;

                    // 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(passwordStr, Encoding.UTF8.GetBytes(saltStr));

                    // 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.
                    byte[] encryptedData = Encrypt(queryStringBytes,
                        pdb.GetBytes(32), pdb.GetBytes(16));

                    return Convert.ToBase64String(encryptedData);
                }
                else
                    return null;
            }
            catch
            {
                return null;
            }
            finally
            { }
        }
Exemplo n.º 6
0
        public byte[] DecryptBinary( byte [] encryptedBytes, string key )
        {
            RijndaelManaged RijndaelCipher = new RijndaelManaged ();

            byte [] EncryptedData = encryptedBytes;
            byte [] Salt = Encoding.ASCII.GetBytes ( key.Length.ToString () );

            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes ( key, Salt );

            // Create a decryptor from the existing SecretKey bytes.
            ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor ( SecretKey.GetBytes ( 32 ), 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 ();

            // Return decrypted string.
            return PlainText;
        }
Exemplo n.º 7
0
        public static string omDecryptEx(string strEncryptedString)
        {
            if (!string.IsNullOrEmpty(strEncryptedString))
            {
                try
                {
                    string strPassword = "******";
                    RijndaelManaged managed = new RijndaelManaged();
                    byte[] buffer = Convert.FromBase64String(strEncryptedString);
                    byte[] rgbSalt = Encoding.ASCII.GetBytes(strPassword.Length.ToString());
                    PasswordDeriveBytes bytes = new PasswordDeriveBytes(strPassword, rgbSalt);
                    ICryptoTransform transform = managed.CreateDecryptor(bytes.GetBytes(0x20), bytes.GetBytes(0x10));
                    MemoryStream stream = new MemoryStream(buffer);
                    CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Read);
                    byte[] buffer3 = new byte[buffer.Length];
                    int count = stream2.Read(buffer3, 0, buffer3.Length);
                    stream.Close();
                    stream2.Close();
                    return Encoding.Unicode.GetString(buffer3, 0, count);
                }
                catch
                {
                    throw new SecurityException("Could not decrypt string");
                }
            }

            return string.Empty;
        }
Exemplo n.º 8
0
        private static string Decrypt(string inputText)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            Byte[] encryptedData = Convert.FromBase64String(inputText);

            //Rfc2898DeriveBytes pwdGen = new Rfc2898DeriveBytes(ENCRYPTION_KEY, ENCRYPTION_SALT, 1000);
            PasswordDeriveBytes pwdGen = new PasswordDeriveBytes(ENCRYPTION(), ENCRYPTION_SALT());
            byte[] Key = pwdGen.GetBytes(32);
            byte[] IV = pwdGen.GetBytes(16);

            using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(Key, IV))
            {
                using (MemoryStream memoryStream = new MemoryStream(encryptedData))
                {
                    using (
                        CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
                        )
                    {
                        byte[] plainText = new Byte[encryptedData.Length];
                        int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                        return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
                    }
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Passwort-Verschlüsselung
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string Encrypt(string text)
        {
            if (text.Length < 1)
            {
                return text;
            }

            string code = "";

            System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
            byte[] bytes = enc.GetBytes(text);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(code, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

            using (MemoryStream ms = new MemoryStream())
            {
                Rijndael alg = Rijndael.Create();
                alg.Key = pdb.GetBytes(32);
                alg.IV = pdb.GetBytes(16);

                using (CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(bytes, 0, bytes.Length);
                }

                bytes = ms.ToArray();
            }
            return Convert.ToBase64String(bytes);
        }
Exemplo n.º 10
0
        /**
         * AES 256 bits encrypt with salt
        **/
        private static byte[] Encrypt(byte[] plainTextBytes, byte[] passwordBytes, byte[] saltBytes)
        {
            byte[] cipherTextBytes = null;
            ICryptoTransform encryptor = null;

            PasswordDeriveBytes key = new PasswordDeriveBytes(passwordBytes, saltBytes, DEFAULT_HASH_ALGORITHM, PASSWORD_ITERATIONS);

            RijndaelManaged AES = new RijndaelManaged();
            AES.KeySize = DEFAULT_KEY_SIZE;
            AES.Mode = CipherMode.CBC;

            // Get Key And IV From Password And Salt
            AES.Key = key.GetBytes(AES.KeySize / 8);
            AES.IV = key.GetBytes(AES.BlockSize / 8);
            encryptor = AES.CreateEncryptor();

            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

            cryptoStream.FlushFinalBlock();
            cipherTextBytes = memoryStream.ToArray();

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

            return cipherTextBytes;
        }
Exemplo n.º 11
0
      public static string EncryptString(string InputText, string Password)
      {
         RijndaelManaged RijndaelCipher = new RijndaelManaged();

         byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);

         byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());

         PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);

         ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

         MemoryStream memoryStream = new MemoryStream();

         CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);

         cryptoStream.Write(PlainText, 0, PlainText.Length);

         cryptoStream.FlushFinalBlock();

         byte[] CipherBytes = memoryStream.ToArray();

         memoryStream.Close();

         cryptoStream.Close();

         string EncryptedData = Convert.ToBase64String(CipherBytes);

         // Return encrypted string.
         return EncryptedData;
      }
Exemplo n.º 12
0
        /// <summary>
        /// Triple DES Descrypt
        /// </summary>
        /// <param name="input">String to decrypt</param>
        /// <param name="key">Encryption Key</param>
        /// <returns></returns>
        public static string Decrypt(string input, string key)
        {
            TripleDESCryptoServiceProvider crp =new TripleDESCryptoServiceProvider();
            System.Text.UnicodeEncoding uEncode = new UnicodeEncoding();
            System.Text.ASCIIEncoding aEncode =new ASCIIEncoding();

            Byte[] bytCipherText = System.Convert.FromBase64String(input);
            MemoryStream stmPlainText =new MemoryStream();
            MemoryStream stmCipherText = new MemoryStream(bytCipherText);

            Byte[] slt= {0x12};

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(key, slt);
            Byte[] bytDerivedKey = pdb.GetBytes(24);
            crp.Key = bytDerivedKey;

            crp.IV = pdb.GetBytes(8);
            CryptoStream csDecrypted = new CryptoStream(stmCipherText, crp.CreateDecryptor(), CryptoStreamMode.Read);

            StreamWriter sw = new StreamWriter(stmPlainText);
            StreamReader sr = new StreamReader(csDecrypted);
            sw.Write(sr.ReadToEnd());

            sw.Flush();

            crp.Clear();

            return uEncode.GetString(stmPlainText.ToArray());
        }
Exemplo n.º 13
0
        // 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 designed exactly for what we are
            // trying to do.
            return System.Text.Encoding.Unicode.GetString(decryptedData);
        }
Exemplo n.º 14
0
        public static String Cryption(string text, string password, bool boolCrypt)
        {
            byte[] utf8_Salt = new byte[] { 0x26, 0x19, 0x81, 0x4E, 0xA0, 0x6D, 0x95, 0x34, 0x26, 0x75, 0x64, 0x05, 0xF6 };

            PasswordDeriveBytes i_Pass = new PasswordDeriveBytes(password, utf8_Salt);

            Rijndael i_Alg = Rijndael.Create();
            i_Alg.Key = i_Pass.GetBytes(32);
            i_Alg.IV = i_Pass.GetBytes(16);

            ICryptoTransform i_Trans = (boolCrypt) ? i_Alg.CreateEncryptor() : i_Alg.CreateDecryptor();

            MemoryStream i_Mem = new MemoryStream();
            CryptoStream i_Crypt = new CryptoStream(i_Mem, i_Trans, CryptoStreamMode.Write);

            byte[] utf8_Data;
            if (boolCrypt) utf8_Data = Encoding.Unicode.GetBytes(text);
            else utf8_Data = Convert.FromBase64String(text);

            try
            {
                i_Crypt.Write(utf8_Data, 0, utf8_Data.Length);
                i_Crypt.Close();
            }
            catch { return null; }

            if (boolCrypt) return Convert.ToBase64String(i_Mem.ToArray());
            else return Encoding.Unicode.GetString(i_Mem.ToArray());
        }
Exemplo n.º 15
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());
                        }
                    }
                }
            }
        }
Exemplo n.º 16
0
 public EncryptedAttribute( string password )
 {
     byte[] salt = new byte[] { 0x26, 0x19, 0x81, 0x4E, 0xA0, 0x6D, 0x95, 0x34, 0x26, 0x75, 0x64, 0x05, 0xF6 };
     PasswordDeriveBytes pass = new PasswordDeriveBytes( password, salt );
     this.Key = pass.GetBytes( 32 );
     this.Vector = pass.GetBytes( 16 );
 }
Exemplo n.º 17
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());
                        }
                    }
                }
            }
        }
Exemplo n.º 18
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;
        }
Exemplo n.º 19
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;
            }
        }
Exemplo n.º 20
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);
 }
Exemplo n.º 21
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;
     }
 }
Exemplo n.º 22
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);
 }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
0
        public static String DecryptString(String Text, String Key)
        {
            if (Text.IsNullOrEmpty())
                throw new BPAExtensionException("DecryptString Text Not Found!");

            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            byte[] EncryptedData = Convert.FromBase64String(Text.Replace("_", "/").Replace("-", "+"));
            byte[] Salt = new UTF8Encoding().GetBytes(Key.Length.ToString());

            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Key, Salt);
            ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
            MemoryStream memoryStream = new MemoryStream(EncryptedData);
            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();

            String DecryptedData = new UTF8Encoding().GetString(PlainText, 0, DecryptedCount);

            if (HttpContext.Current != null)
                return HttpContext.Current.Server.HtmlDecode(DecryptedData);
            else
                return DecryptedData;
        }
Exemplo n.º 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);
 }
Exemplo n.º 26
0
        /// <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;
            }
        }
Exemplo n.º 27
0
        /// <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;
        }
Exemplo n.º 28
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();
        }
        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;
        }
Exemplo n.º 30
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();
    }
Exemplo n.º 31
0
        // Decrypt bytes into bytes using a password
        public static byte[] Decrypt(byte[] cipherData)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(PASSWORD,
                new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
                0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});

            return Decrypt(cipherData, pdb.GetBytes(32), pdb.GetBytes(16));
        }
Exemplo n.º 32
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)));
    }
Exemplo n.º 33
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));
    }
Exemplo n.º 34
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));
    }
Exemplo n.º 35
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));
        }
Exemplo n.º 36
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());
        }
Exemplo n.º 37
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));
 }
Exemplo n.º 38
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));
 }
Exemplo n.º 39
0
    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);
    }