Пример #1
0
        public static string decryptRJ256(string target, string key, string iv)
        {
            var rijndael = new System.Security.Cryptography.RijndaelManaged()
            {
                Padding   = System.Security.Cryptography.PaddingMode.Zeros,
                Mode      = System.Security.Cryptography.CipherMode.CBC,
                KeySize   = 256,
                BlockSize = 256
            };

            var keyBytes = Encoding.ASCII.GetBytes(key);
            var ivBytes  = Encoding.ASCII.GetBytes(iv);

            var decryptor   = rijndael.CreateDecryptor(keyBytes, ivBytes);
            var toDecrypt   = Convert.FromBase64String(target);
            var fromEncrypt = new byte[toDecrypt.Length];

            var msDecrypt = new System.IO.MemoryStream(toDecrypt);
            var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read);

            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            string data = Encoding.ASCII.GetString(fromEncrypt);

            data = data.Replace("\0", "");

            return(data);
        }
Пример #2
0
        private byte[] Encrypt(byte[] PlainData)
        {
            byte[] Result = null;


            try
            {
                System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged();
                Enc.KeySize = 256;
                Enc.Key     = this.Encryption_Key();
                Enc.IV      = this.Encryption_IV();

                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream cryptoStream = null;
                cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, Enc.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cryptoStream.Write(PlainData, 0, PlainData.Length);
                cryptoStream.FlushFinalBlock();
                Result = memoryStream.ToArray();
                cryptoStream.Close();
                memoryStream.Close();
                cryptoStream.Dispose();
                memoryStream.Dispose();
            }
            catch (Exception)
            {
                Result = null;
            }

            return(Result);
        }
Пример #3
0
        /// <summary>
        /// 通过公钥做key进行加密,AES算法
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string EncryptByPublicKey(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(null);
            }

            var content = File.ReadAllText(PublicKeySavePath.Replace("~", CallContext_Parameter.ServerRootPath));
            var key     = ComFunc.getMD5_String(ComFunc.Base64Code(content));


            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(text);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = Encoding.UTF8.GetBytes(key),
                Mode    = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(Convert.ToBase64String(resultArray, 0, resultArray.Length));
        }
Пример #4
0
        public static string encryptRJ256(string target, string key, string iv)
        {
            var rijndael = new System.Security.Cryptography.RijndaelManaged()
            {
                Padding   = System.Security.Cryptography.PaddingMode.Zeros,
                Mode      = System.Security.Cryptography.CipherMode.CBC,
                KeySize   = 256,
                BlockSize = 256
            };

            var bytesKey = Encoding.ASCII.GetBytes(key);
            var bytesIv  = Encoding.ASCII.GetBytes(iv);

            var encryptor = rijndael.CreateEncryptor(bytesKey, bytesIv);

            var msEncrypt = new System.IO.MemoryStream();
            var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write);

            var toEncrypt = Encoding.ASCII.GetBytes(target);

            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();

            var encrypted = msEncrypt.ToArray();

            return(Convert.ToBase64String(encrypted));
        }
Пример #5
0
        private void init()
        {
            this.mode = new SicBlockCipher(new AesFastEngine());

            // si las claves de encriptación no han sido inicializadas, las calculamos y las almacenamos en los valores estáticos.
            if (ClavesTokenizador.EncriptIV == null)
            {
                byte[] _salt = Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["Seguridad.Sal"]);

                System.Security.Cryptography.RijndaelManaged aesAlg = null;

                try
                {
                    // Calculamos los valores de las claves de encriptación para ser usadas en el algoritmo
                    System.Security.Cryptography.Rfc2898DeriveBytes key = new System.Security.Cryptography.Rfc2898DeriveBytes(ConfigurationManager.AppSettings["Seguridad.Secreto"], _salt);

                    aesAlg   = new System.Security.Cryptography.RijndaelManaged();
                    this.key = key.GetBytes(aesAlg.KeySize / 8);
                    this.iv  = key.GetBytes(aesAlg.BlockSize / 8);

                    // Asignamos las variables de claves de ecnriptación a memoria
                    ClavesTokenizador.EncriptKey = this.key;
                    ClavesTokenizador.EncriptKey = this.iv;
                }
                catch
                {
                };
            }
            else
            {
                // Obtenemos las variables de las claves del tokenizador de memoria
                this.key = ClavesTokenizador.EncriptKey;
                this.iv  = ClavesTokenizador.EncriptIV;
            }
        }
Пример #6
0
        /// <summary>
        /// 文字列を復号化
        /// </summary>
        /// <param name="sourceString">暗号化文字列</param>
        /// <param name="password">パスワード</param>
        /// <returns>復号化後文字列</returns>
        public string DecryptString(string sourceString, string password)
        {
            byte[] key, iv, strBytes, decBytes;
            System.Security.Cryptography.RijndaelManaged  rijndael;
            System.Security.Cryptography.ICryptoTransform decryptor;

            // 複合化(コンバートあり)
            try {
                // v2.0
                rijndael = new System.Security.Cryptography.RijndaelManaged();
                GenerateKeyFromPassword(password, rijndael.KeySize, out key, rijndael.BlockSize, out iv, 100);
                rijndael.Key = key;
                rijndael.IV  = iv;
                strBytes     = System.Convert.FromBase64String(sourceString);
                decryptor    = rijndael.CreateDecryptor();
                decBytes     = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
                decryptor.Dispose();
            } catch (Exception) {
                try {
                    // v1.0-1.3
                    rijndael = new System.Security.Cryptography.RijndaelManaged();
                    GenerateKeyFromPassword(password, rijndael.KeySize, out key, rijndael.BlockSize, out iv, 1000);
                    rijndael.Key = key;
                    rijndael.IV  = iv;
                    strBytes     = System.Convert.FromBase64String(sourceString);
                    decryptor    = rijndael.CreateDecryptor();
                    decBytes     = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
                    decryptor.Dispose();
                } catch (Exception) {
                    throw;
                }
            }

            return(System.Text.Encoding.UTF8.GetString(decBytes));
        }
Пример #7
0
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            try
            {
                Byte[] toEncryptArray = Convert.FromBase64String(str);

                System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
                {
                    Key     = Encoding.UTF8.GetBytes(key),
                    Mode    = System.Security.Cryptography.CipherMode.ECB,
                    Padding = System.Security.Cryptography.PaddingMode.PKCS7
                };

                System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                return(Encoding.UTF8.GetString(resultArray));
            }
            catch (Exception e)
            {
                return("");
            }
        }
Пример #8
0
        private byte[] Decrypt(byte[] EncData)
        {
            byte[] Result = null;

            try
            {
                System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged();
                Enc.KeySize = 256;
                Enc.Key     = this.Encryption_Key();
                Enc.IV      = this.Encryption_IV();

                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(EncData);
                System.Security.Cryptography.CryptoStream cryptoStream = null;
                cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, Enc.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read);

                byte[] TempDecryptArr = null;
                TempDecryptArr = new byte[EncData.Length + 1];
                int decryptedByteCount = 0;
                decryptedByteCount = cryptoStream.Read(TempDecryptArr, 0, EncData.Length);

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

                Result = new byte[decryptedByteCount + 1];
                Array.Copy(TempDecryptArr, Result, decryptedByteCount);
            }
            catch (Exception)
            {
                Result = null;
            }

            return(Result);
        }
Пример #9
0
        /// <summary>
        /// 暗号化された文字列を復号化する
        /// </summary>
        /// <param name="sourceString">暗号化された文字列</param>
        /// <param name="password">暗号化に使用したパスワード</param>
        /// <returns>復号化された文字列</returns>
        public static string DecryptString(string text, string password)
        {
            //RijndaelManagedオブジェクトを作成
            using (var rijndael = new System.Security.Cryptography.RijndaelManaged())
            {
                //パスワードから共有キーと初期化ベクタを作成
                GenerateKeyFromPassword(password, rijndael.KeySize, out byte[] key, rijndael.BlockSize, out byte[] iv);
                rijndael.Key = key;
                rijndael.IV  = iv;

                //文字列をバイト型配列に戻す
                byte[] strBytes = System.Convert.FromBase64String(text);

                //対称暗号化オブジェクトの作成
                using (var decryptor = rijndael.CreateDecryptor())
                {
                    //バイト型配列を復号化する
                    //復号化に失敗すると例外CryptographicExceptionが発生
                    byte[] decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);

                    //バイト型配列を文字列に戻して返す
                    return(System.Text.Encoding.UTF8.GetString(decBytes));
                }
            }
        }
Пример #10
0
        public static string DecodeUserInfoAsString(string encryptedData, string iv,
                                                    string session_key)
        {
            byte[] iv2 = Convert.FromBase64String(iv);

            if (string.IsNullOrEmpty(encryptedData))
            {
                throw new ArgumentNullException(nameof(encryptedData));
            }
            byte[] toEncryptArray = Convert.FromBase64String(encryptedData);


            var rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = Convert.FromBase64String(session_key),
                IV      = iv2,
                Mode    = System.Security.Cryptography.CipherMode.CBC,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            byte[] resultArray;
            using (rm)
            {
                var cTransform = rm.CreateDecryptor();
                resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            }
            return(Encoding.UTF8.GetString(resultArray));
        }
Пример #11
0
 public string AesDecrypt(string input)
 {
     if (string.IsNullOrEmpty(input) == false)
     {
         System.Security.Cryptography.RijndaelManaged          AES      = new System.Security.Cryptography.RijndaelManaged();
         System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider();
         try
         {
             byte[] hash = new byte[32];
             byte[] temp = Hash_AES.ComputeHash(System.Text.Encoding.UTF8.GetBytes(_hashKey));
             Array.Copy(temp, 0, hash, 0, 16);
             Array.Copy(temp, 0, hash, 15, 16);
             AES.Key  = hash;
             AES.Mode = System.Security.Cryptography.CipherMode.ECB;
             System.Security.Cryptography.ICryptoTransform DESDecrypter = AES.CreateDecryptor();
             byte[] buffer    = Convert.FromBase64String(input);
             var    decrypted = System.Text.Encoding.UTF8.GetString(DESDecrypter.TransformFinalBlock(buffer, 0, buffer.Length));
             return(decrypted);
         }
         catch (Exception)
         {
             return("");
         }
     }
     else
     {
         return("");
     }
 }
Пример #12
0
        /// <summary>
        /// 暗号化された文字列を復号化する
        /// </summary>
        /// <param name="sourceString">暗号化された文字列</param>
        /// <param name="password">暗号化に使用したパスワード</param>
        /// <returns>復号化された文字列</returns>
        public static string DecryptString(string sourceString, string password)
        {
            if (String.IsNullOrEmpty(sourceString))
            {
                return "";
            }

            //RijndaelManagedオブジェクトを作成
            System.Security.Cryptography.RijndaelManaged rijndael =
                new System.Security.Cryptography.RijndaelManaged();

            //パスワードから共有キーと初期化ベクタを作成
            byte[] key, iv;
            GenerateKeyFromPassword(
                password, rijndael.KeySize, out key, rijndael.BlockSize, out iv);
            rijndael.Key = key;
            rijndael.IV = iv;

            //文字列をバイト型配列に戻す
            byte[] strBytes = System.Convert.FromBase64String(sourceString);

            //対称暗号化オブジェクトの作成
            System.Security.Cryptography.ICryptoTransform decryptor =
                rijndael.CreateDecryptor();
            //バイト型配列を復号化する
            byte[] decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
            //閉じる
            decryptor.Dispose();

            //バイト型配列を文字列に戻して返す
            return System.Text.Encoding.UTF8.GetString(decBytes);
        }
Пример #13
0
        public static string AES_Encrypt(string input_text, string security_Code)
        {
            // ''' security_Code= [email protected]
            System.Security.Cryptography.RijndaelManaged          AES      = new System.Security.Cryptography.RijndaelManaged();
            System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider();
            string encrypted = "";

            try
            {
                byte[] hash = new byte[32];
                byte[] temp = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(security_Code));
                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);
                AES.Key  = hash;
                AES.Mode = System.Security.Cryptography.CipherMode.ECB;
                //'Security.Cryptography.CipherMode.ECB
                System.Security.Cryptography.ICryptoTransform DESEncrypter = AES.CreateEncryptor();
                byte[] Buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(input_text);
                encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch (Exception ex)
            {
            }
            return(encrypted);
        }
Пример #14
0
        public static string Encrypt(string[] keyArray)
        {
            string key = "";

            foreach (string s in keyArray)
            {
                key = key + s + ";";
            }
            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
            byte[] SaltValueBytes     = Encoding.ASCII.GetBytes(Salt);
            byte[] PlainTextBytes     = Encoding.UTF8.GetBytes(key);
            System.Security.Cryptography.PasswordDeriveBytes DerivedPassword = new System.Security.Cryptography.PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
            byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
            System.Security.Cryptography.RijndaelManaged SymmetricKey = new System.Security.Cryptography.RijndaelManaged();
            SymmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC;
            byte[] CipherTextBytes = null;
            using (System.Security.Cryptography.ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
            {
                using (System.IO.MemoryStream MemStream = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream CryptoStream = new System.Security.Cryptography.CryptoStream(MemStream, Encryptor, System.Security.Cryptography.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
        private static System.Security.Cryptography.SymmetricAlgorithm GetKeyInstance(string algorithm)
        {
            System.Security.Cryptography.SymmetricAlgorithm result;
            switch (algorithm)
            {
            case System.Security.Cryptography.Xml.EncryptedXml.XmlEncTripleDESUrl:
                result = System.Security.Cryptography.TripleDES.Create();
                break;

            case System.Security.Cryptography.Xml.EncryptedXml.XmlEncAES128Url:
                result         = new System.Security.Cryptography.RijndaelManaged();
                result.KeySize = 128;
                break;

            case System.Security.Cryptography.Xml.EncryptedXml.XmlEncAES192Url:
                result         = new System.Security.Cryptography.RijndaelManaged();
                result.KeySize = 192;
                break;

            case System.Security.Cryptography.Xml.EncryptedXml.XmlEncAES256Url:
                result         = new System.Security.Cryptography.RijndaelManaged();
                result.KeySize = 256;
                break;

            default:
                result         = new System.Security.Cryptography.RijndaelManaged();
                result.KeySize = 256;
                break;
            }
            return(result);
        }
Пример #16
0
        private static string Decrypt(string cipherText, string passPhrase)
        {
            byte[]    initVectorBytes = System.Text.Encoding.ASCII.GetBytes("tu89geji340t89u2");
            const int keysize         = 256;

            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
            using (System.Security.Cryptography.PasswordDeriveBytes password = new System.Security.Cryptography.PasswordDeriveBytes(passPhrase, null))
            {
                byte[] keyBytes = password.GetBytes(keysize / 8);
                using (System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged())
                {
                    symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC;
                    using (System.Security.Cryptography.ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                    {
                        using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                            {
                                byte[] plainTextBytes     = new byte[cipherTextBytes.Length];
                                int    decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                return(System.Text.Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount));
                            }
                        }
                    }
                }
            }
        }
Пример #17
0
        public static String Encriptar(String input, String pass)
        {
            System.Security.Cryptography.RijndaelManaged          AES      = new System.Security.Cryptography.RijndaelManaged();
            System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider();
            string encrypted = "";

            try
            {
                byte[] hash = new byte[32];
                byte[] temp = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass));
                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);
                AES.Key  = hash;
                AES.Mode = System.Security.Cryptography.CipherMode.ECB;
                System.Security.Cryptography.ICryptoTransform DESEncrypter = AES.CreateEncryptor();
                byte[] Buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(input);
                encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length));
                return(encrypted);
            }
            catch (Exception ex)
            {
                String error = ex.Message;
                return(null);
            }
        }
Пример #18
0
        public static void KriptoFile(string dosyalar, string password = "******", string uzanti = ".uzanti")
        {
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(password, @byte);
            System.IO.FileStream fs = new System.IO.FileStream(dosyalar + uzanti, System.IO.FileMode.Create);
            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged();
            System.Security.Cryptography.CryptoStream    cs = new System.Security.Cryptography.CryptoStream(fs, rm.CreateEncryptor(rfc.GetBytes(32), rfc.GetBytes(16)), System.Security.Cryptography.CryptoStreamMode.Write);
            System.IO.FileStream fs2 = new System.IO.FileStream(dosyalar, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            int temp;

            temp = fs2.ReadByte();
            while (temp != -1)
            {
                cs.WriteByte((byte)temp);
                temp = fs2.ReadByte();
            }


            //Close işlemleri , silmeyin. Mümkünse hiç bi' yeri ellemeyin.

            cs.Close();
            fs.Close();
            fs2.Close();
            System.IO.File.Delete(dosyalar);     //Bu biraz farklı , ilk önce dosyaların kopyasını oluşturup şifreler. Daha sonra siler.
        }
Пример #19
0
        public string Descriptografar(string criptografia)
        {
            string chave = "--";

            // Cria objeto para criptografia AES
            System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged();
            rijndael.Mode    = System.Security.Cryptography.CipherMode.CBC;
            rijndael.KeySize = 128;

            byte[] chaveBytes;
            byte[] criptografiaBytes;
            byte[] mensagemBytes;
            string mensagem;

            // Transforma chave e mensagem em array de byts
            chaveBytes    = Encoding.UTF8.GetBytes(chave);
            mensagemBytes = Convert.FromBase64String(criptografia);


            // Realiza criptografia
            System.Security.Cryptography.ICryptoTransform cryptor = rijndael.CreateDecryptor(chaveBytes, chaveBytes);
            criptografiaBytes = cryptor.TransformFinalBlock(mensagemBytes, 0, mensagemBytes.Length);
            cryptor.Dispose();

            // Transforma criptografia em string
            mensagem = Encoding.UTF8.GetString(criptografiaBytes);
            return(mensagem);
        }
Пример #20
0
        public static string Encrypt(string plainText, string passPhrase)
        {
            byte[]    initVectorBytes = Encoding.ASCII.GetBytes("tu89geji340t89u2");
            const int keysize         = 256;

            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            using (System.Security.Cryptography.PasswordDeriveBytes password = new System.Security.Cryptography.PasswordDeriveBytes(passPhrase, null))
            {
                byte[] keyBytes = password.GetBytes(keysize / 8);
                using (System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged())
                {
                    symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC;
                    using (System.Security.Cryptography.ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
                    {
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                byte[] cipherTextBytes = memoryStream.ToArray();
                                return(Convert.ToBase64String(cipherTextBytes));
                            }
                        }
                    }
                }
            }
        }
Пример #21
0
        public static string decryptRJ256(string target, string key, string iv)
        {
            var rijndael = new System.Security.Cryptography.RijndaelManaged()
            {
                Padding = System.Security.Cryptography.PaddingMode.Zeros,
                Mode = System.Security.Cryptography.CipherMode.CBC,
                KeySize = 256,
                BlockSize = 256
            };

            var keyBytes = Encoding.ASCII.GetBytes(key);
            var ivBytes = Encoding.ASCII.GetBytes(iv);

            var decryptor = rijndael.CreateDecryptor(keyBytes, ivBytes);
            var toDecrypt = Convert.FromBase64String(target);
            var fromEncrypt = new byte[toDecrypt.Length];

            var msDecrypt = new System.IO.MemoryStream(toDecrypt);
            var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read);
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            string data = Encoding.ASCII.GetString(fromEncrypt);
            data = data.Replace("\0", "");

            return data;
        }
Пример #22
0
        public string EncryptString(string sourceString, string password)
        {
            //RijndaelManagedオブジェクトを作成
            System.Security.Cryptography.RijndaelManaged rijndael =
                new System.Security.Cryptography.RijndaelManaged();

            //パスワードから共有キーと初期化ベクタを作成
            byte[] key, iv;
            GenerateKeyFromPassword(
                password, rijndael.KeySize, out key, rijndael.BlockSize, out iv);
            rijndael.Key = key;
            rijndael.IV  = iv;

            //文字列をバイト型配列に変換する
            byte[] strBytes = System.Text.Encoding.UTF8.GetBytes(sourceString);

            //対称暗号化オブジェクトの作成
            System.Security.Cryptography.ICryptoTransform encryptor =
                rijndael.CreateEncryptor();
            //バイト型配列を暗号化する
            byte[] encBytes = encryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
            //閉じる
            encryptor.Dispose();

            //バイト型配列を文字列に変換して返す
            return(System.Convert.ToBase64String(encBytes));
        }
Пример #23
0
        public RijndaelEncryption(string key, string iv)
            : base(key, iv)
        {
            System.Security.Cryptography.RijndaelManaged rijnManaged = new System.Security.Cryptography.RijndaelManaged();

            /* used to generate key and IV */

            /*
             * GenerateKeyIV gen = new GenerateKeyIV(rijnManaged);
             * string s = Convert.ToBase64String(gen.GenerateKey());
             * string sa = Convert.ToBase64String(gen.GenerateIV());
             *
             * rijnManaged.IV = Convert.FromBase64String(sa);
             * rijnManaged.Key = Convert.FromBase64String(s);
             * agent = new Crypto.SymmetricEncryption(rijnManaged);
             * string enc = Convert.ToBase64String(agent.Encrypt(System.Text.ASCIIEncoding.ASCII.GetBytes("sa123")));
             */

            try
            {
                rijnManaged.Key = Convert.FromBase64String(key);
                rijnManaged.IV  = Convert.FromBase64String(iv);
                agent           = new Crypto.SymmetricEncryption(rijnManaged);
            }
            catch (System.Security.Cryptography.CryptographicException)
            {
                rijnManaged.Dispose();
                throw new System.Security.Cryptography.CryptographicException("Invalid key or iv.");
            }
        }
Пример #24
0
 /// <summary>
 ///  AES 解密
 /// </summary>
 /// <param name="str">明文(待解密)</param>
 /// <param name="key">密文</param>
 /// <returns></returns>
 public static string AESDecrypt(string str, string key)
 {
     if (string.IsNullOrEmpty(str))
     {
         return(null);
     }
     if (key.Length < 16)
     {
         key = key.PadRight(16, ' ');
     }
     else
     {
         key = key.Substring(0, 16);
     }
     Byte[] toEncryptArray = Convert.FromBase64String(str);
     System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
     {
         Key     = Encoding.UTF8.GetBytes(key),
         Mode    = System.Security.Cryptography.CipherMode.ECB,
         Padding = System.Security.Cryptography.PaddingMode.PKCS7
     };
     System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
     Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
     return(Encoding.UTF8.GetString(resultArray));
 }
Пример #25
0
        public static string Decrypt(string sSrc, string sKey)
        {
            try
            {
                // if (string.IsNullOrEmpty(sKey) || string.IsNullOrEmpty(sSrc) || sKey.Length != 16) return null;

                Byte[] toEncryptArray = Convert.FromBase64String(sSrc);

                System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
                {
                    Key     = Encoding.UTF8.GetBytes(sKey),
                    Mode    = System.Security.Cryptography.CipherMode.ECB,
                    Padding = System.Security.Cryptography.PaddingMode.PKCS7
                };

                System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                return(Encoding.UTF8.GetString(resultArray));
            }
            catch
            {
                return(null);
            }
        }
Пример #26
0
        public static string encryptRJ256(string target, string key, string iv)
        {
            var rijndael = new System.Security.Cryptography.RijndaelManaged()
            {
                Padding = System.Security.Cryptography.PaddingMode.Zeros,
                Mode = System.Security.Cryptography.CipherMode.CBC,
                KeySize = 256,
                BlockSize = 256
            };

            var bytesKey = Encoding.ASCII.GetBytes(key);
            var bytesIv = Encoding.ASCII.GetBytes(iv);

            var encryptor = rijndael.CreateEncryptor(bytesKey, bytesIv);

            var msEncrypt = new System.IO.MemoryStream();
            var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write);

            var toEncrypt = Encoding.ASCII.GetBytes(target);

            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();

            var encrypted = msEncrypt.ToArray();
            return Convert.ToBase64String(encrypted);
        }
Пример #27
0
            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);
                System.Security.Cryptography.PasswordDeriveBytes DerivedPassword = new System.Security.Cryptography.PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
                byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
                System.Security.Cryptography.RijndaelManaged SymmetricKey = new System.Security.Cryptography.RijndaelManaged();
                SymmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC;
                byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
                int    ByteCount      = 0;

                using (System.Security.Cryptography.ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
                {
                    using (System.IO.MemoryStream MemStream = new System.IO.MemoryStream(CipherTextBytes))
                    {
                        using (System.Security.Cryptography.CryptoStream CryptoStream = new System.Security.Cryptography.CryptoStream(MemStream, Decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                        {
                            ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                            MemStream.Close();
                            CryptoStream.Close();
                        }
                    }
                }
                SymmetricKey.Clear();
                return(Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount));
            }
Пример #28
0
        public RijndaelEncryption(string key, string iv)
            : base(key, iv)
        {
            System.Security.Cryptography.RijndaelManaged rijnManaged = new System.Security.Cryptography.RijndaelManaged();

            /* used to generate key and IV */
            /*
            GenerateKeyIV gen = new GenerateKeyIV(rijnManaged);
            string s = Convert.ToBase64String(gen.GenerateKey());
            string sa = Convert.ToBase64String(gen.GenerateIV());

            rijnManaged.IV = Convert.FromBase64String(sa);
            rijnManaged.Key = Convert.FromBase64String(s);
            agent = new Crypto.SymmetricEncryption(rijnManaged);
            string enc = Convert.ToBase64String(agent.Encrypt(System.Text.ASCIIEncoding.ASCII.GetBytes("sa123")));
            */

            try
            {
                rijnManaged.Key = Convert.FromBase64String(key);
                rijnManaged.IV = Convert.FromBase64String(iv);
                agent = new Crypto.SymmetricEncryption(rijnManaged);
            }
            catch (System.Security.Cryptography.CryptographicException)
            {
                rijnManaged.Dispose();
                throw new System.Security.Cryptography.CryptographicException("Invalid key or iv.");
            }
        }
Пример #29
0
        /// <summary>
        /// 文字列を暗号化する
        /// </summary>
        /// <param name="sourceString">暗号化する文字列</param>
        /// <param name="password">暗号化に使用するパスワード</param>
        /// <returns>暗号化された文字列</returns>
        public static string EncryptString(string sourceString, string password)
        {
            //RijndaelManagedオブジェクトを作成
            System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged();

            //パスワードから共有キーと初期化ベクタを作成
            byte[] key, iv;
            GenerateKeyFromPassword(password, rijndael.KeySize, out key, rijndael.BlockSize, out iv);
            rijndael.Key = key;
            rijndael.IV = iv;

            //文字列をバイト型配列に変換
            byte[] strBytes = System.Text.Encoding.UTF8.GetBytes(sourceString);

            //対称暗号化オブジェクトの作成
            System.Security.Cryptography.ICryptoTransform encryptor = rijndael.CreateEncryptor();

            //バイト型配列を暗号化する
            byte[] encBytes = encryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
            //閉じる
            encryptor.Dispose();

            //バイト型配列を文字列に変換して返す
            return System.Convert.ToBase64String(encBytes);
        }
Пример #30
0
        /// <summary>
        /// AES 加密
        /// </summary>
        /// <param name="encryptKey"></param>
        /// <param name="bizContent"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string AesEncrypt(string encryptKey, string bizContent, string charset)
        {
            Byte[] keyArray       = Convert.FromBase64String(encryptKey);
            Byte[] toEncryptArray = null;

            if (string.IsNullOrEmpty(charset))
            {
                toEncryptArray = Encoding.UTF8.GetBytes(bizContent);
            }
            else
            {
                toEncryptArray = Encoding.GetEncoding(charset).GetBytes(bizContent);
            }

            System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged();
            rDel.Key     = keyArray;
            rDel.Mode    = System.Security.Cryptography.CipherMode.CBC;
            rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            rDel.IV      = AES_IV;

            System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateEncryptor(rDel.Key, rDel.IV);
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);


            return(Convert.ToBase64String(resultArray));
        }
Пример #31
0
 static Enc()
 {
     //RijndaelManagedオブジェクトを作成
     rijndael = new System.Security.Cryptography.RijndaelManaged();
     byte[] key, iv;
     GenerateKeyFromPassword(rijndael.KeySize, out key, rijndael.BlockSize, out iv);
     rijndael.Key = key;
     rijndael.IV  = iv;
 }
Пример #32
0
        private static async System.Threading.Tasks.Task <ResultType> TaskMain(Fee.Crypt.OnCryptTask_CallBackInterface a_callback_interface, byte[] a_binary, int a_index, int a_length, string a_pass, string a_salt, Fee.TaskW.CancelToken a_cancel)
                #endif
        {
            ResultType t_ret;

            {
                t_ret.binary      = null;
                t_ret.errorstring = null;
            }

            try{
                //RijndaelManaged
                System.Security.Cryptography.RijndaelManaged t_rijndael = new System.Security.Cryptography.RijndaelManaged();
                t_rijndael.KeySize   = 256;
                t_rijndael.BlockSize = 128;
                t_rijndael.Mode      = System.Security.Cryptography.CipherMode.CBC;

                {
                    byte[] t_salt = System.Text.Encoding.UTF8.GetBytes(a_salt);
                    System.Security.Cryptography.Rfc2898DeriveBytes t_derivebyte = new System.Security.Cryptography.Rfc2898DeriveBytes(a_pass, t_salt);
                    t_derivebyte.IterationCount = 1000;

                    t_rijndael.Key = t_derivebyte.GetBytes(t_rijndael.KeySize / 8);
                    t_rijndael.IV  = t_derivebyte.GetBytes(t_rijndael.BlockSize / 8);

                    Tool.Log("Key", System.BitConverter.ToString(t_rijndael.Key));
                    Tool.Log("IV", System.BitConverter.ToString(t_rijndael.IV));
                }

                //TransformFinalBlock
                using (System.Security.Cryptography.ICryptoTransform t_decryptor = t_rijndael.CreateDecryptor()){
                    t_ret.binary = t_decryptor.TransformFinalBlock(a_binary, a_index, a_length);
                }
            }catch (System.Exception t_exception) {
                t_ret.binary      = null;
                t_ret.errorstring = "Task_DecryptPass : "******"Task_DecryptPass : Cancel";

                a_cancel.ThrowIfCancellationRequested();
            }

            if (t_ret.binary == null)
            {
                if (t_ret.errorstring == null)
                {
                    t_ret.errorstring = "Task_DecryptPass : null";
                }
            }

            return(t_ret);
        }
Пример #33
0
        private void CreateVerifier(byte[] key)
        {
            // Much of the commmentary in this function is taken from 2.3.3
            // The EncryptionVerifier structure MUST be set using the following process:

            // 1)	Random data are generated and written into the Salt field.
            // 2)	The encryption key is derived from the password and salt, as specified in section
            //		2.3.4.7 or 2.3.5.2, with block number 0.

            //		This is passed in as parameter key

            // 3)	Generate 16 bytes of additional random data as the Verifier.

            System.Security.Cryptography.RijndaelManaged aes = new System.Security.Cryptography.RijndaelManaged();
            byte[] verifier = aes.IV;
            aes = null;

            // Console.WriteLine("Verifier");
            // Console.WriteLine( Lyquidity.OLEStorage.Utilities.FormatData(verifier, 32, 0) );
            // Console.WriteLine();

            // 4)	Results of step 3 are encrypted and written into the EncryptedVerifier field.

            encryptedVerifier = AESEncrypt(verifier, key);

            // Console.WriteLine("encryptedVerifier");
            // Console.WriteLine( Lyquidity.OLEStorage.Utilities.FormatData(encryptedVerifier, 32, 0) );
            // Console.WriteLine();

            // 5)	For the hashing algorithm chosen, obtain the size of the hash data and write this value
            //		into the VerifierHashSize field.

            // Not applicable right now

            // 6)	Obtain the hashing algorithm output using an input of data generated in step 3.

            byte[] verifierHash = SHA1Hash(verifier);
            // Console.WriteLine("verifierHash");
            // Console.WriteLine( Lyquidity.OLEStorage.Utilities.FormatData(verifierHash, 32, 0) );
            // Console.WriteLine();

            // 7)	Encrypt the hashing algorithm output from step 6 using the encryption algorithm
            //		chosen, and write the output into the EncryptedVerifierHash field.

            // First pad to 32 bytes
            byte[] tempHash = new byte[0x20];
            Array.Copy(verifierHash, tempHash, verifierHash.Length);
            verifierHash = tempHash;

            encryptedVerifierHash = AESEncrypt(verifierHash, key);

            // Console.WriteLine("encryptedVerifierHash");
            // Console.WriteLine( Lyquidity.OLEStorage.Utilities.FormatData(encryptedVerifierHash, 32, 0) );
            // Console.WriteLine();
        }
Пример #34
0
 ///<summary>
 ///解密
 ///</summary>
 ///<param name="toDecrypt">需要被解密的数据</param>
 ///<returns></returns>
 public static byte[] Decrypt(byte[] toDecrypt)
 {
     Byte[] keyArray = System.Text.UTF8Encoding.UTF8.GetBytes(key);
     System.Security.Cryptography.RijndaelManaged aes = new System.Security.Cryptography.RijndaelManaged();
     aes.Key     = keyArray;
     aes.Mode    = System.Security.Cryptography.CipherMode.ECB;
     aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
     System.Security.Cryptography.ICryptoTransform transform = aes.CreateDecryptor();
     Byte[] resultArray = transform.TransformFinalBlock(toDecrypt, 0, toDecrypt.Length);
     return(resultArray);
 }
Пример #35
0
        /// <summary>Szyfruje przekazany strumień danych.</summary>
        /// <param name="streamToEncrypt">Strumień danych do zaszyfrowania.</param>
        /// <param name="streamEncrypted">Zaszyfrowany strumień danych. Uwaga strumień zostanie zamknięty,
        /// ale w razie konieczności można będzie użyć metody 'ToArray()'.</param>
        /// <param name="key">Klucz szyfrujący. Maksymalnie 256 bitów, minimalnie 128 bitów, przeskok o 64 bity.</param>
        /// <param name="iv">Wektor inicjalizacji. Rozmiar 128 bitów.</param>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="System.ArgumentException"></exception>
        /// <exception cref="System.InvalidOperationException"></exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException"></exception>
        public static void Encrypt(System.IO.Stream streamToEncrypt, System.IO.Stream streamEncrypted, byte[] key, byte[] iv)
        {
            if (streamToEncrypt == null)
            {
                throw new System.ArgumentNullException("streamToEncrypt");
            }
            if (streamToEncrypt.CanRead == false)
            {
                throw new System.ArgumentException("Argument 'streamToEncrypt' is not readable.");
            }

            if (streamEncrypted == null)
            {
                throw new System.ArgumentNullException("streamEncrypted");
            }
            if (streamEncrypted.CanWrite == false)
            {
                throw new System.ArgumentException("Argument 'streamEncrypted' is not writable.");
            }

            if (key == null)
            {
                throw new System.ArgumentNullException("key");
            }
            if (key.Length != 16 && key.Length != 22 && key.Length != 32)
            {
                throw new System.ArgumentException("Argument 'key' does not mach the block size for this algorithm.");
            }

            if (iv == null)
            {
                throw new System.ArgumentNullException("iv");
            }
            if (iv.Length != 16)
            {
                throw new System.ArgumentException("Argument 'iv' does not mach the block size for this algorithm.");
            }

            streamToEncrypt.Position = 0;
            streamEncrypted.Position = 0;

            using (System.Security.Cryptography.RijndaelManaged algoritmCrypt = new System.Security.Cryptography.RijndaelManaged())
            {
                using (System.Security.Cryptography.ICryptoTransform encryptor = algoritmCrypt.CreateEncryptor(key, iv))
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(
                               streamEncrypted, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        streamToEncrypt.CopyTo(cs);
                        cs.FlushFinalBlock();
                    }
                }
            }
        }
Пример #36
0
 /// <summary>  
 /// AES加密  
 /// </summary>  
 /// <param name="str">要加密字符串</param>  
 /// <returns>返回加密后字符串</returns>  
 public static String Encrypt_AES(String str, String strAesKey)
 {
     Byte[] keyArray = System.Text.UTF8Encoding.UTF8.GetBytes(strAesKey);
     Byte[] toEncryptArray = System.Text.UTF8Encoding.UTF8.GetBytes(str);
     System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged();
     rDel.Key = keyArray;
     rDel.Mode = System.Security.Cryptography.CipherMode.ECB;
     rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
     System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateEncryptor();
     Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
     return Convert.ToBase64String(resultArray, 0, resultArray.Length);
 }
Пример #37
0
        public static string DeCrypt(string strEncryptedInput)
        {
            string strReturnValue = null;

            if (string.IsNullOrEmpty(strEncryptedInput))
            {
                throw new System.ArgumentNullException("strEncryptedInput", "strEncryptedInput may not be string.Empty or NULL, because these are invid values.");
            }

            // Dim encASCII As New System.Text.ASCIIEncoding()
            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            System.Security.Cryptography.RijndaelManaged objRijndael = new System.Security.Cryptography.RijndaelManaged();

            byte[] baCipherTextBuffer = HexStringToByteArray(strEncryptedInput);

            byte[] baDecryptionKey = HexStringToByteArray(strKey);
            byte[] baInitializationVector = HexStringToByteArray(strIV);

            // This is where the message would be transmitted to a recipient
            // who already knows your secret key. Optionally, you can
            // also encrypt your secret key using a public key algorithm
            // and pass it to the mesage recipient along with the RijnDael
            // encrypted message.
            //Get a decryptor that uses the same key and IV as the encryptor.
            System.Security.Cryptography.ICryptoTransform ifaceAESdecryptor = objRijndael.CreateDecryptor(baDecryptionKey, baInitializationVector);

            //Now decrypt the previously encrypted message using the decryptor
            // obtained in the above step.
            System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(baCipherTextBuffer);
            System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, ifaceAESdecryptor, System.Security.Cryptography.CryptoStreamMode.Read);

            //Dim baPlainTextBuffer() As Byte
            //baPlainTextBuffer = New Byte(baCipherTextBuffer.Length) {}
            byte[] baPlainTextBuffer = new byte[baCipherTextBuffer.Length + 1];

            //Read the data out of the crypto stream.
            csDecrypt.Read(baPlainTextBuffer, 0, baPlainTextBuffer.Length);

            //Convert the byte array back into a string.
            strReturnValue = enc.GetString(baPlainTextBuffer);
            if (!string.IsNullOrEmpty(strReturnValue))
                strReturnValue = strReturnValue.Trim('\0');

            return strReturnValue;
        }
Пример #38
0
        public static string Encrypt(string strPlainText)
        {
            //Dim roundtrip As String
            //Dim encASCII As New System.Text.ASCIIEncoding()
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            System.Security.Cryptography.RijndaelManaged objRijndael = new System.Security.Cryptography.RijndaelManaged();
            //Dim fromEncrypt() As Byte
            byte[] baCipherTextBuffer = null;
            byte[] baPlainTextBuffer = null;
            byte[] baEncryptionKey = null;
            byte[] baInitializationVector = null;

            //Create a new key and initialization vector.
            //objRijndael.GenerateKey()
            //objRijndael.GenerateIV()
            objRijndael.Key = HexStringToByteArray(strKey);
            objRijndael.IV = HexStringToByteArray(strIV);

            //Get the key and initialization vector.
            baEncryptionKey = objRijndael.Key;
            baInitializationVector = objRijndael.IV;
            //strKey = ByteArrayToHexString(baEncryptionKey)
            //strIV = ByteArrayToHexString(baInitializationVector)

            //Get an encryptor.
            System.Security.Cryptography.ICryptoTransform ifaceAESencryptor = objRijndael.CreateEncryptor(baEncryptionKey, baInitializationVector);

            //Encrypt the data.
            System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, ifaceAESencryptor, System.Security.Cryptography.CryptoStreamMode.Write);

            //Convert the data to a byte array.
            baPlainTextBuffer = enc.GetBytes(strPlainText);

            //Write all data to the crypto stream and flush it.
            csEncrypt.Write(baPlainTextBuffer, 0, baPlainTextBuffer.Length);
            csEncrypt.FlushFinalBlock();

            //Get encrypted array of bytes.
            baCipherTextBuffer = msEncrypt.ToArray();

            return ByteArrayToHexString(baCipherTextBuffer);
        }
Пример #39
0
        // Decrypt a string.
        public static string DecryptString(string sourceString, string password)
        {
            System.Security.Cryptography.RijndaelManaged rijndael =
                new System.Security.Cryptography.RijndaelManaged();

            byte[] key, iv;
            GenerateKeyFromPassword(
                password, rijndael.KeySize, out key, rijndael.BlockSize, out iv);
            rijndael.Key = key;
            rijndael.IV = iv;

            byte[] strBytes = System.Convert.FromBase64String(sourceString);

            System.Security.Cryptography.ICryptoTransform decryptor =
                rijndael.CreateDecryptor();
            byte[] decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
            decryptor.Dispose();

            return System.Text.Encoding.UTF8.GetString(decBytes);
        }
        /// <summary>
        /// 文字列を復号化
        /// </summary>
        /// <param name="sourceString">暗号化文字列</param>
        /// <param name="password">パスワード</param>
        /// <returns>復号化後文字列</returns>
        public string DecryptString(string sourceString, string password)
        {
            byte[] key, iv, strBytes, decBytes;
            System.Security.Cryptography.RijndaelManaged rijndael;
            System.Security.Cryptography.ICryptoTransform decryptor;

            // 複合化(コンバートあり)
            try {
                // v2.0
                rijndael = new System.Security.Cryptography.RijndaelManaged();
                GenerateKeyFromPassword(password, rijndael.KeySize, out key, rijndael.BlockSize, out iv, 100);
                rijndael.Key = key;
                rijndael.IV = iv;
                strBytes = System.Convert.FromBase64String(sourceString);
                decryptor = rijndael.CreateDecryptor();
                decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
                decryptor.Dispose();
            } catch (Exception) {
                try {
                    // v1.0-1.3
                    rijndael = new System.Security.Cryptography.RijndaelManaged();
                    GenerateKeyFromPassword(password, rijndael.KeySize, out key, rijndael.BlockSize, out iv, 1000);
                    rijndael.Key = key;
                    rijndael.IV = iv;
                    strBytes = System.Convert.FromBase64String(sourceString);
                    decryptor = rijndael.CreateDecryptor();
                    decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
                    decryptor.Dispose();
                } catch (Exception) {
                    throw;
                }
            }

            return System.Text.Encoding.UTF8.GetString(decBytes);
        }
Пример #41
0
        public static string GenerateKey()
        {
            System.Security.Cryptography.RijndaelManaged objRijndael = new System.Security.Cryptography.RijndaelManaged();

            objRijndael.GenerateKey();
            objRijndael.GenerateIV();

            byte[] bIV = objRijndael.IV;
            byte[] bKey = objRijndael.Key;
            objRijndael.Clear();

            return "IV: " + ByteArrayToHexString(bIV) + System.Environment.NewLine + "Key: " + ByteArrayToHexString(bKey);
        }
Пример #42
0
            public static string Decrypt(string CipherText, string Password,
                string Salt, string HashAlgorithm,
                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);
                System.Security.Cryptography.PasswordDeriveBytes DerivedPassword = new System.Security.Cryptography.PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
                byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
                System.Security.Cryptography.RijndaelManaged SymmetricKey = new System.Security.Cryptography.RijndaelManaged();
                SymmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC;
                byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
                int ByteCount = 0;
                using (System.Security.Cryptography.ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
                {
                    using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                    {
                        using (System.Security.Cryptography.CryptoStream CryptoStream = new System.Security.Cryptography.CryptoStream(MemStream, Decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                        {

                            ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                            MemStream.Close();
                            CryptoStream.Close();
                        }
                    }
                }
                SymmetricKey.Clear();
                return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
            }
Пример #43
0
        private byte[] Decrypt(byte[] EncData)
        {
            byte[] Result = null;

            try
            {
                System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged();
                Enc.KeySize = 256;
                Enc.Key = this.Encryption_Key();
                Enc.IV = this.Encryption_IV();

                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(EncData);
                System.Security.Cryptography.CryptoStream cryptoStream = null;
                cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, Enc.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read);

                byte[] TempDecryptArr = null;
                TempDecryptArr = new byte[EncData.Length + 1];
                int decryptedByteCount = 0;
                decryptedByteCount = cryptoStream.Read(TempDecryptArr, 0, EncData.Length);

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

                Result = new byte[decryptedByteCount + 1];
                Array.Copy(TempDecryptArr, Result, decryptedByteCount);
            }
            catch (Exception)
            {
                Result = null;
            }

            return Result;
        }
Пример #44
0
        /// <summary>
        /// Encrypts a package (zip) file using a supplied password and returns 
        /// an array to create an encryption information stream and a byte array 
        /// of the encrypted package.
        /// </summary>
        /// <param name="packageContents">The package (zip) file to be encrypted</param>
        /// <param name="password">The password to decrypt the package</param>
        /// <param name="encryptionInfo">An array of bytes containing the encrption info</param>
        /// <param name="encryptedPackage">The encrpyted package</param>
        /// <returns></returns>
        public void EncryptPackage(byte[] packageContents, string password, out byte[] encryptionInfo, out byte[] encryptedPackage)
        {
            versionMajor = 3;
            versionMinor = 2;

            // Console.WriteLine(password);

            // this.algId = AlgId.AES256;
            // this.keySize = 0x100;

            // Generate a salt
            System.Security.Cryptography.RijndaelManaged aes = new System.Security.Cryptography.RijndaelManaged();
            saltSize = 0x10;
            byte[] tempSalt = SHA1Hash(aes.IV);
            aes = null;
            this.verifierHashSize = tempSalt.Length;

            salt = new byte[saltSize];
            Array.Copy(tempSalt, salt, saltSize);

            // Generate a key from salt and password
            byte[] key = GeneratePasswordHashUsingSHA1(password);

            CreateVerifier(key);

            int originalLength = packageContents.Length;

            // Pad the array to the nearest 16 byte boundary
            int remainder = packageContents.Length % 0x10;
            if (remainder != 0)
            {
                byte[] tempContents = new byte[packageContents.Length + 0x10 - remainder];
                Array.Copy(packageContents, tempContents, packageContents.Length);
                packageContents = tempContents;
            }

            byte[] encryptionResult = AESEncrypt(packageContents, key);

            // Need to prepend the original package size as a Int64 (8 byte) field
            encryptedPackage = new byte[encryptionResult.Length +  8];
            // MUST record the original length here
            Array.Copy(BitConverter.GetBytes((long)originalLength), encryptedPackage, 8);
            Array.Copy(encryptionResult, 0, encryptedPackage, 8, encryptionResult.Length);

            byte[] encryptionHeader = null;

            // Generate the encryption header structure
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                System.IO.BinaryWriter br = new System.IO.BinaryWriter(ms);
                br.Write((int)this.encryptionFlags);
                br.Write((int)this.sizeExtra);
                br.Write((int)this.algId);
                br.Write((int)this.algHashId);
                br.Write((int)this.keySize);
                br.Write((int)this.providerType);
                br.Write(new byte[] { 0xA0, 0xC7, 0xDC, 0x02, 0x00, 0x00, 0x00, 0x00 } );
                br.Write(System.Text.UnicodeEncoding.Unicode.GetBytes("Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)\0"));

                ms.Flush();
                encryptionHeader = ms.ToArray();
            }

            byte[] encryptionVerifier = null;

            // Generate the encryption header structure
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                System.IO.BinaryWriter br = new System.IO.BinaryWriter(ms);
                br.Write((int)salt.Length);
                br.Write(this.salt);
                br.Write(this.encryptedVerifier);
                br.Write(this.verifierHashSize); // Hash length
                br.Write(this.encryptedVerifierHash);

                ms.Flush();
                encryptionVerifier = ms.ToArray();
            }

            // Now generate the encryption info structure
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                System.IO.BinaryWriter br = new System.IO.BinaryWriter(ms);
                br.Write(versionMajor);
                br.Write(versionMinor);
                br.Write((int)this.encryptionFlags);
                br.Write((int)encryptionHeader.Length);
                br.Write(encryptionHeader);
                br.Write(encryptionVerifier);

                ms.Flush();
                encryptionInfo = ms.ToArray();
            }

            // Console.WriteLine( Lyquidity.OLEStorage.Utilities.FormatData(encryptionInfo, 128, 0) );
        }
Пример #45
0
        private byte[] Encrypt(byte[] PlainData)
        {
            byte[] Result = null;

            try
            {
                System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged();
                Enc.KeySize = 256;
                Enc.Key = this.Encryption_Key();
                Enc.IV = this.Encryption_IV();

                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream cryptoStream = null;
                cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, Enc.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cryptoStream.Write(PlainData, 0, PlainData.Length);
                cryptoStream.FlushFinalBlock();
                Result = memoryStream.ToArray();
                cryptoStream.Close();
                memoryStream.Close();
                cryptoStream.Dispose();
                memoryStream.Dispose();

            }
            catch (Exception)
            {
                Result = null;
            }

            return Result;
        }
Пример #46
0
        private byte[] AESDecrypt(byte[] data, int index, int count, byte[] key)
        {
            byte[] decryptedBytes = null;

            //  Create uninitialized Rijndael encryption object.
             System.Security.Cryptography.RijndaelManaged symmetricKey = new  System.Security.Cryptography.RijndaelManaged();

            // It is required that the encryption mode is Electronic Codebook (ECB)
            // see MS-OFFCRYPTO v1.0 2.3.4.7 pp 39.
            symmetricKey.Mode = System.Security.Cryptography.CipherMode.ECB;
            symmetricKey.Padding = System.Security.Cryptography.PaddingMode.None;
            symmetricKey.KeySize = keySize;
            // symmetricKey.IV = null; // new byte[16];
            // symmetricKey.Key = key;

            //  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(key, null);

            //  Define memory stream which will be used to hold encrypted data.
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(data, index, count))
            {
                //  Define memory stream which will be used to hold encrypted data.
                using (System.Security.Cryptography.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.
                    decryptedBytes = new byte[data.Length];
                    int decryptedByteCount = cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length);

                    return decryptedBytes;
                }
            }
        }
Пример #47
0
        //[MenuItem("Hugula AES/GenerateKey", false, 12)]
        public static void GenerateKey()
        {
            using (System.Security.Cryptography.RijndaelManaged myRijndael = new System.Security.Cryptography.RijndaelManaged())
            {

                myRijndael.GenerateKey();
                byte[] Key = myRijndael.Key;

                KeyVData KeyScri = ScriptableObject.CreateInstance<KeyVData>();
                KeyScri.KEY = Key;
                AssetDatabase.CreateAsset(KeyScri, Path.Combine(ConfigPath, "I81.asset"));

                Debug.Log("key Generate " + Key.Length);

            }
        }
Пример #48
0
        bool ProcessEncryptionPwd()
        {
            System.Security.Cryptography.Rfc2898DeriveBytes pbkdf2 = null;
            if (tbEncryptionPwd.Text == "[UNCHANGED]")   // Password hasn't changed from when the package was loaded
                return true;
            if (string.IsNullOrEmpty(tbEncryptionPwd.Text))
                return true;   // Nothing to do really
            if (!string.IsNullOrEmpty(virtPackage.GetProperty("EncryptionPwdKey")) &&
                !string.IsNullOrEmpty(virtPackage.GetProperty("EncryptionPwdHash")) &&
                !string.IsNullOrEmpty(virtPackage.GetProperty("EncryptionPwdSalt")) &&
                !string.IsNullOrEmpty(virtPackage.GetProperty("EncryptionPwdIV")))
            {
                // EncryptionPwd* properties are already set. Only need to re-generate them if password has changed (different from EncryptionPwdHash)
                string pwdSaltStr = virtPackage.GetProperty("EncryptionPwdSalt");
                var pwdSalt = Utils.HexUndump(pwdSaltStr);

                // Check if password is unchanged
                // PBKDF2 first time on entered password
                pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(tbEncryptionPwd.Text, pwdSalt, Pbkdf2Iterations);
                var enteredPwdHash = pbkdf2.GetBytes(KeySizeBytes);
                // PBKDF2 second time on entered password
                pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(enteredPwdHash, pwdSalt, Pbkdf2Iterations);
                enteredPwdHash = pbkdf2.GetBytes(KeySizeBytes);

                var savedPwdHash = Utils.HexUndump(virtPackage.GetProperty("EncryptionPwdHash"));
                bool equals = true;
                for (int i = 0; i < enteredPwdHash.Length; i++)
                {
                    if (enteredPwdHash[i] != savedPwdHash[i])
                        equals = false;
                }
                if (equals)
                    return true;   // Password hasn't changed
            }

            bool Ret = true;
            var rngCsp = new System.Security.Cryptography.RNGCryptoServiceProvider();

            // Steps for password-based key:
            // 1. Generate a long key (this is just a randomly generated amount of bytes in hex, you can use 128 bytes).
            //    Use this key to encrypt your file with AES (meaning you use it as a password)
            byte[] randomKey = new byte[KeySizeBytes];   // Our AES algorithm uses a 128-bit key (16 bytes)
            rngCsp.GetBytes(randomKey);   // <-- The key with which files will be encrypted / decrypted

            // 2. Encrypt the key itself with AES using your password (which is a bit shorter but easier to remember.
            //    Now AES requires this again to be either 128, 192 or 256 bits of length so you need to make your
            //    password of that length. Hence you can just use PBKDF2 (or scrypt or bcrypt) to create a fixed key
            //    length from your password. DO NOT STORE THIS.
            byte[] salt = new byte[SaltSize];
            rngCsp.GetBytes(salt);

            // Transform user password into a key that we can encrypt randomKey with
            pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(Encoding.ASCII.GetBytes(tbEncryptionPwd.Text), salt, Pbkdf2Iterations);
            var keyEncryptionKey = pbkdf2.GetBytes(KeySizeBytes);   // tbEncryptionPwd.Text -> Key. This key will be used for encrypting randomKey.
            var keyEncryptor = new System.Security.Cryptography.RijndaelManaged();
            keyEncryptor.BlockSize = 128;
            keyEncryptor.Mode = System.Security.Cryptography.CipherMode.CFB;
            keyEncryptor.Padding = System.Security.Cryptography.PaddingMode.None;
            keyEncryptor.Key = keyEncryptionKey;
            keyEncryptor.GenerateIV();
            var encryptor = keyEncryptor.CreateEncryptor(keyEncryptor.Key, keyEncryptor.IV);
            var msEncrypt = new MemoryStream();
            using (var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
            {
                using (var swEncrypt = new BinaryWriter(csEncrypt))
                {
                    byte[] toWrite = randomKey;//Encoding.ASCII.GetBytes("1234567890123456");
                    swEncrypt.Write(toWrite);
                }
            }
            var encryptedKey = msEncrypt.ToArray();   // <-- randomKey encrypted with AES, whose key = PBKDF2(tbEncryptionPwd.Text)

            // 3. Keep a hash of your hashed password using PBKDF2 (or bcrypt or scrypt). This will allow you to check
            //    if the password is correct before trying to decrypt your encrypted key:
            //       hash(hash(password)) --> can be stored
            //       hash(password) --> should not be stored
            pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(keyEncryptionKey, salt, Pbkdf2Iterations);   // Iterations slow down hashing (which helps against brute-force)
            var keyEncryptionKeyHashed = pbkdf2.GetBytes(KeySizeBytes);                                       // Second PBKDF2 hash

            // Store
            Ret &= virtPackage.SetProperty("EncryptionPwdKey", Utils.HexDump(encryptedKey));             // Encryption key, in encrypted form
            Ret &= virtPackage.SetProperty("EncryptionPwdHash", Utils.HexDump(keyEncryptionKeyHashed));  // Password hash, for user password validation
            Ret &= virtPackage.SetProperty("EncryptionPwdSalt", Utils.HexDump(salt));                    // Salt used for both PBKDF2 password hashes (first and second)
            Ret &= virtPackage.SetProperty("EncryptionPwdIV", Utils.HexDump(keyEncryptor.IV));           // IV used for encrypting the key with AES

            return Ret;
        }
        /// <summary>
        /// 文字列を暗号化
        /// </summary>
        /// <param name="sourceString">暗号化文字列</param>
        /// <param name="password">暗号化パスワード</param>
        /// <returns>暗号化後文字列</returns>
        public string EncryptString(string sourceString, string password)
        {
            byte[] key, iv, strBytes, encBytes;
            System.Security.Cryptography.RijndaelManaged rijndael;
            System.Security.Cryptography.ICryptoTransform encryptor;

            try {
                rijndael = new System.Security.Cryptography.RijndaelManaged();
                GenerateKeyFromPassword(password, rijndael.KeySize, out key, rijndael.BlockSize, out iv, 100);
                rijndael.Key = key;
                rijndael.IV = iv;
                strBytes = System.Text.Encoding.UTF8.GetBytes(sourceString);
                encryptor = rijndael.CreateEncryptor();
                encBytes = encryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
                encryptor.Dispose();
            } catch (Exception) {
                throw;
            }

            return System.Convert.ToBase64String(encBytes);
        }
Пример #50
0
        /// <summary>
        /// Initializa os objetos necessários para realizar criptografia e descriptografia.
        /// </summary>
        private void Initialize()
        {
            System.Security.Cryptography.RijndaelManaged v_rijndael;
            System.Security.Cryptography.Rfc2898DeriveBytes v_passwordbytes;
            byte[] v_initvectorbytes;
            byte[] v_keybytes;

            v_rijndael = new System.Security.Cryptography.RijndaelManaged();
            v_rijndael.Mode = System.Security.Cryptography.CipherMode.CBC;

            v_initvectorbytes = System.Text.Encoding.ASCII.GetBytes(this.v_initvector);

            v_passwordbytes = new System.Security.Cryptography.Rfc2898DeriveBytes(this.v_password, v_initvectorbytes, 1);
            v_keybytes = v_passwordbytes.GetBytes(this.v_keysize / 8);

            this.v_encryptor = v_rijndael.CreateEncryptor(v_keybytes, v_initvectorbytes);
            this.v_decryptor = v_rijndael.CreateDecryptor(v_keybytes, v_initvectorbytes);
        }
Пример #51
0
        private byte[] AESEncrypt(byte[] data, byte[] key)
        {
            byte[] cipherTextBytes = null;

            //  Create uninitialized Rijndael encryption object.
            System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged();

            // It is required that the encryption mode is Electronic Codebook (ECB)
            // see MS-OFFCRYPTO v1.0 2.3.4.7 pp 39.
            symmetricKey.Mode = System.Security.Cryptography.CipherMode.ECB;
            symmetricKey.Padding = System.Security.Cryptography.PaddingMode.None; // System.Security.Cryptography.PaddingMode.None;
            symmetricKey.KeySize = this.keySize;
            // symmetricKey.Key = key;
            // symmetricKey.IV = new byte[16];

            // Generate encryptor 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 encryptor = symmetricKey.CreateEncryptor(key, null);

            //  Define memory stream which will be used to hold encrypted data.
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                //  Define cryptographic stream (always use Write mode for encryption).
                using (System.Security.Cryptography.CryptoStream cryptoStream
                        = new System.Security.Cryptography.CryptoStream(memoryStream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    //  Start encrypting.
                    cryptoStream.Write(data, 0, data.Length);

                    //  Finish encrypting.
                    cryptoStream.FlushFinalBlock();
                }

                //  Convert our encrypted data from a memory stream into a byte array.
                cipherTextBytes = memoryStream.ToArray();
                return cipherTextBytes;
            }
        }
Пример #52
0
        //[MenuItem("Hugula AES/GenerateIV", false, 13)]
        public static void GenerateIV()
        {
            using (System.Security.Cryptography.RijndaelManaged myRijndael = new System.Security.Cryptography.RijndaelManaged())
            {

                myRijndael.GenerateIV();
                byte[] IV = myRijndael.IV;

                KeyVData KeyScri = ScriptableObject.CreateInstance<KeyVData>();
                KeyScri.IV = IV;
                AssetDatabase.CreateAsset(KeyScri, Path.Combine(ConfigPath, "K81.asset"));
                Debug.Log("IV Generate " + IV.Length);
            }
        }
Пример #53
0
 private static System.Security.Cryptography.SymmetricAlgorithm GetKeyInstance(string algorithm)
 {
     System.Security.Cryptography.SymmetricAlgorithm result;
     switch (algorithm)
     {
         case System.Security.Cryptography.Xml.EncryptedXml.XmlEncTripleDESUrl:
             result = System.Security.Cryptography.TripleDES.Create();
             break;
         case System.Security.Cryptography.Xml.EncryptedXml.XmlEncAES128Url:
             result = new System.Security.Cryptography.RijndaelManaged();
             result.KeySize = 128;
             break;
         case System.Security.Cryptography.Xml.EncryptedXml.XmlEncAES192Url:
             result = new System.Security.Cryptography.RijndaelManaged();
             result.KeySize = 192;
             break;
         case System.Security.Cryptography.Xml.EncryptedXml.XmlEncAES256Url:
             result = new System.Security.Cryptography.RijndaelManaged();
             result.KeySize = 256;
             break;
         default:
             result = new System.Security.Cryptography.RijndaelManaged();
             result.KeySize = 256;
             break;
     }
     return result;
 }
Пример #54
0
        private void CreateVerifier(byte[] key)
        {
            // Much of the commmentary in this function is taken from 2.3.3
            // The EncryptionVerifier structure MUST be set using the following process:

            // 1)	Random data are generated and written into the Salt field.
            // 2)	The encryption key is derived from the password and salt, as specified in section
            //		2.3.4.7 or 2.3.5.2, with block number 0.

            //		This is passed in as parameter key

            // 3)	Generate 16 bytes of additional random data as the Verifier.

            System.Security.Cryptography.RijndaelManaged aes = new System.Security.Cryptography.RijndaelManaged();
            byte[] verifier = aes.IV;
            aes = null;

            // Console.WriteLine("Verifier");
            // Console.WriteLine( Lyquidity.OLEStorage.Utilities.FormatData(verifier, 32, 0) );
            // Console.WriteLine();

            // 4)	Results of step 3 are encrypted and written into the EncryptedVerifier field.

            encryptedVerifier = AESEncrypt( verifier, key);

            // Console.WriteLine("encryptedVerifier");
            // Console.WriteLine( Lyquidity.OLEStorage.Utilities.FormatData(encryptedVerifier, 32, 0) );
            // Console.WriteLine();

            // 5)	For the hashing algorithm chosen, obtain the size of the hash data and write this value
            //		into the VerifierHashSize field.

            // Not applicable right now

            // 6)	Obtain the hashing algorithm output using an input of data generated in step 3.

            byte[] verifierHash = SHA1Hash( verifier );
            // Console.WriteLine("verifierHash");
            // Console.WriteLine( Lyquidity.OLEStorage.Utilities.FormatData(verifierHash, 32, 0) );
            // Console.WriteLine();

            // 7)	Encrypt the hashing algorithm output from step 6 using the encryption algorithm
            //		chosen, and write the output into the EncryptedVerifierHash field.

            // First pad to 32 bytes
            byte[] tempHash = new byte[0x20];
            Array.Copy(verifierHash, tempHash, verifierHash.Length);
            verifierHash = tempHash;

            encryptedVerifierHash = AESEncrypt( verifierHash, key );

            // Console.WriteLine("encryptedVerifierHash");
            // Console.WriteLine( Lyquidity.OLEStorage.Utilities.FormatData(encryptedVerifierHash, 32, 0) );
            // Console.WriteLine();
        }