示例#1
1
        private byte[] DecryptManaged(byte[] Key, byte[] Vector, byte[] Data, PaddingMode Padding = PaddingMode.Zeros)
        {
            byte[] decryptedBytes;
            int count = 0;

            using (MemoryStream stream = new MemoryStream(Data))
            {
                using (RijndaelManaged cipher = new RijndaelManaged())
                {
                    cipher.Mode = CipherMode.CBC;
                    cipher.Padding = Padding;
                    cipher.KeySize = Key.Length * 8;
                    cipher.BlockSize = Vector.Length * 8;

                    using (ICryptoTransform decryptor = cipher.CreateDecryptor(Key, Vector))
                    {
                        using (CryptoStream reader = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
                        {
                            decryptedBytes = new byte[stream.Length];
                            count = reader.Read(decryptedBytes, 0, decryptedBytes.Length);
                        }
                    }
                    cipher.Clear();
                }
            }
            return decryptedBytes;
        }
        /// <summary>
        /// AES解密(无向量)
        /// </summary>
        /// <param name="encryptedBytes">被加密的明文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static string AESDecryptWithoutVector(String Data, String Key)
        {
            Byte[] encryptedBytes = Convert.FromBase64String(Data);
            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);

            MemoryStream mStream = new MemoryStream(encryptedBytes);
            //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
            //mStream.Seek( 0, SeekOrigin.Begin );
            RijndaelManaged aes = new RijndaelManaged();
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = 128;
            aes.Key = bKey;
            //aes.IV = _iV;
            CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
            try
            {
                byte[] tmp = new byte[encryptedBytes.Length + 32];
                int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
                byte[] ret = new byte[len];
                Array.Copy(tmp, 0, ret, 0, len);
                return Encoding.UTF8.GetString(ret);
            }
            finally
            {
                cryptoStream.Close();
                mStream.Close();
                aes.Clear();
            }
        }
示例#3
1
        public static string Descriptografar(string codigo)
        {
            try
            {
                if (string.IsNullOrEmpty(codigo))
                    return String.Empty;
                string retorno;
                var chave = new Rfc2898DeriveBytes(Segredo, Complemento);

                var algoritimo = new RijndaelManaged();
                algoritimo.Key = chave.GetBytes(algoritimo.KeySize / 8);
                algoritimo.IV = chave.GetBytes(algoritimo.BlockSize / 8);

                var descriptografor = algoritimo.CreateDecryptor(algoritimo.Key, algoritimo.IV);
                var bytes = Convert.FromBase64String(codigo);

                using (var memoryStream = new MemoryStream(bytes))
                using (var cryptoStream = new CryptoStream(memoryStream, descriptografor, CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream))
                    retorno = streamReader.ReadToEnd();

                algoritimo.Clear();

                return retorno;
            }
            catch (Exception)
            {
                return "DEU PAU";
            }
        }
示例#4
1
    private static String encrypt (Dictionary<String, String> data, String api_key)
    {
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      String json_data = serializer.Serialize(data);

      String iv = api_key.Substring(16, 16);
      api_key = api_key.Substring(0, 16);

      byte[] data_bytes = Encoding.UTF8.GetBytes(json_data);
      byte[] api_bytes = Encoding.ASCII.GetBytes(api_key);
      byte[] iv_bytes = Encoding.ASCII.GetBytes(iv);

      RijndaelManaged AES = new RijndaelManaged();

      AES.Padding = PaddingMode.PKCS7;
      AES.Mode = CipherMode.CBC;
      AES.BlockSize = 128;
      AES.KeySize = 128;

      MemoryStream memStream = new MemoryStream();
      CryptoStream cryptoStream = new CryptoStream(memStream, AES.CreateEncryptor(api_bytes, iv_bytes), CryptoStreamMode.Write);
      cryptoStream.Write(data_bytes, 0, data_bytes.Length);
      cryptoStream.FlushFinalBlock();

      byte[] encryptedMessageBytes = new byte[memStream.Length];
      memStream.Position = 0;
      memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);

      string encryptedMessage = System.Convert.ToBase64String(encryptedMessageBytes);

      return HttpUtility.UrlEncode(encryptedMessage);
    }
示例#5
1
 // Methods
 public EncryptionHelper()
 {
     RijndaelManaged managed = new RijndaelManaged();
     this.EncryptorTransform = managed.CreateEncryptor(this.Key, this.Vector);
     this.DecryptorTransform = managed.CreateDecryptor(this.Key, this.Vector);
     this.UTFEncoder = new UTF8Encoding();
 }
示例#6
1
文件: AES.cs 项目: Robin--/RMLib
        /// <summary>
        /// Encrypts a string
        /// </summary>
        /// <param name="plaintext">Text to be encrypted</param>
        /// <param name="password">Password to encrypt with</param>
        /// <param name="salt">Salt to encrypt with</param>
        /// <returns>An encrypted string</returns>
        public static string Encrypt(string plaintext, string password, string salt)
        {
            string Result = "";

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

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

            return Result;
        }
 public AesEncryption(byte[] Key, byte[] Vector)
 {
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     this.EncryptorTransform = rijndaelManaged.CreateEncryptor(Key, Vector);
     this.DecryptorTransform = rijndaelManaged.CreateDecryptor(Key, Vector);
     this.UTFEncoder = new UTF8Encoding();
 }
示例#8
1
        public static string Criptografar(string texto)
        {
            if(string.IsNullOrEmpty(texto))
                return String.Empty;

            string outStr;

            RijndaelManaged aesAlg = null;
            try
            {
                var key = new Rfc2898DeriveBytes(Segredo, Complemento);
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(texto);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            return outStr;
        }
示例#9
1
        public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
        {
            byte[] encryptedBytes = null;

            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
                    }
                    encryptedBytes = ms.ToArray();
                }
            }

            return encryptedBytes;
        }
        public static void DecryptFile(string strKey, string pathCypheredTextFile, string pathPlainTextFile)
        {
            // Place la clé de déchiffrement dans un tableau d'octets
            byte[] key = GenerateAlgotihmInputs(strKey);

            // Place le vecteur d'initialisation dans un tableau d'octets
            byte[] iv = GenerateAlgotihmInputs(strKey);

            // Filestream of the new file that will be decrypted.
            Directory.CreateDirectory(Directory.GetParent(pathPlainTextFile).FullName);
            FileStream fsCrypt = new FileStream(pathPlainTextFile, FileMode.Create);

            RijndaelManaged rijndael = new RijndaelManaged();
            rijndael.Mode = CipherMode.CBC;
            rijndael.Key = key;
            rijndael.IV = iv;

            ICryptoTransform aesDecryptor = rijndael.CreateDecryptor();

            CryptoStream cs = new CryptoStream(fsCrypt, aesDecryptor, CryptoStreamMode.Write);

            // FileStream of the file that is currently encrypted.
            FileStream fsIn = new FileStream(pathCypheredTextFile, FileMode.OpenOrCreate);

            int data;

            while ((data = fsIn.ReadByte()) != -1)
                cs.WriteByte((byte)data);
            cs.Close();
            fsIn.Close();
            fsCrypt.Close();
        }
示例#11
1
 public static string Encrypt(string plainText, string passPhrase)
 {
     // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
     // so that the same Salt and IV values can be used when decrypting.
     var saltStringBytes = Generate256BitsOfRandomEntropy();
     var ivStringBytes = Generate256BitsOfRandomEntropy();
     var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations);
     var keyBytes = password.GetBytes(Keysize / 8);
     using (var symmetricKey = new RijndaelManaged())
     {
         symmetricKey.BlockSize = 256;
         symmetricKey.Mode = CipherMode.CBC;
         symmetricKey.Padding = PaddingMode.PKCS7;
         using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
         {
             using (var memoryStream = new MemoryStream())
             {
                 using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                 {
                     cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                     cryptoStream.FlushFinalBlock();
                     // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                     var cipherTextBytes = saltStringBytes;
                     cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                     cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                     memoryStream.Close();
                     cryptoStream.Close();
                     return Convert.ToBase64String(cipherTextBytes);
                 }
             }
         }
     }
 }
示例#12
1
        public static string EncryptString(
            string plainText,
            string passPhrase,
            string saltValue,
            int passwordIterations,
            string initVector,
            int keySize)
        {

            byte[] initVectorBytes = initVector == null ? new byte[16] : Encoding.ASCII.GetBytes(initVector);
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] keyBytes = GetKeyBytes(passPhrase, saltValue, passwordIterations, keySize);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            byte[] cipherTextBytes;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                }
            }
            string cipherText = Convert.ToBase64String(cipherTextBytes);
            return cipherText;
        }
示例#13
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);
     }
 }
示例#14
1
        /// <summary>
        /// Decrypts the specified data using a 128-bit cipher. The key can be any length.
        /// </summary>
        /// <param name="Data">The data to be decrypted.</param>
        /// <param name="Key">The key used to decrypt the data.</param>
        /// <returns>A string containing the decoded data.</returns>
        public static byte[] Decrypt128Byte(byte[] Data, byte[] Key)
        {
            RijndaelManaged AES = null;
            var MS = new MemoryStream(Data);
            CryptoStream CS = null;
            StreamReader DS = null;
            try
            {
                //Get the IV and length corrected Key.
                KeyData KeyData = GenerateKeyIV128(Key);
                //Create the AES crytpograhy object.
                AES = new RijndaelManaged { BlockSize = 128, KeySize = 128, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
                CS = new CryptoStream(MS, AES.CreateDecryptor(), CryptoStreamMode.Read);
                DS = new StreamReader(CS);

                var D = new byte[CS.Length];
                CS.Read(D, 0, (int)CS.Length - 1);
                return D;
            }
            finally
            {
                if (AES != null) AES.Clear();
                MS.Dispose();
                if (CS != null) CS.Dispose();
                if (DS != null) DS.Dispose();
            }
        }
示例#15
1
文件: AES.cs 项目: nicoriff/NinoJS
 /// -------------- Two Utility Methods (not used but may be useful) -----------
 /// Generates an encryption key.
 public static byte[] GenerateEncryptionKey()
 {
     //Generate a Key.
     RijndaelManaged rm = new RijndaelManaged();
     rm.GenerateKey();
     return rm.Key;
 }
示例#16
1
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="text"></param>
        /// <param name="password"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string AESDecrypt(string text, string password, string iv)
        {
            var rijndaelCipher = new RijndaelManaged
            {
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7,
                KeySize = 128,
                BlockSize = 128
            };

            var encryptedData = Convert.FromBase64String(text);

            var pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);

            var keyBytes = new byte[24];

            var len = pwdBytes.Length;

            if (len > keyBytes.Length) len = keyBytes.Length;

            System.Array.Copy(pwdBytes, keyBytes, len);

            rijndaelCipher.Key = keyBytes;

            var ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
            rijndaelCipher.IV = ivBytes;

            var transform = rijndaelCipher.CreateDecryptor();

            var plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

            return Encoding.UTF8.GetString(plainText);
        }
        public static string DecryptString(String cipherText, string Key)
        {
            byte[] tmpCipherText = Convert.FromBase64String(cipherText);
            byte[] tmpKey = GenerateAlgotihmInputs(Key);

            using (RijndaelManaged alg = new RijndaelManaged())
            {
                alg.Key = tmpKey;
                alg.IV = tmpKey;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = alg.CreateDecryptor(alg.Key, alg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(tmpCipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        // Place les données déchiffrées dans un tableau d'octet
                        byte[] plainTextData = new byte[tmpCipherText.Length];

                        int decryptedByteCount = csDecrypt.Read(plainTextData, 0, plainTextData.Length);
                        return Encoding.UTF8.GetString(plainTextData, 0, decryptedByteCount);
                    }

                }

            }
        }
 public static string Encrypt(string plainText, string passPhrase)
 {
     byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                     {
                         cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                         cryptoStream.FlushFinalBlock();
                         byte[] cipherTextBytes = memoryStream.ToArray();
                         return Convert.ToBase64String(cipherTextBytes);
                     }
                 }
             }
         }
     }
 }
示例#19
1
        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations);
            var keyBytes = password.GetBytes(Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = 256;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            var plainTextBytes = new byte[cipherTextBytes.Length];
                            var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            memoryStream.Close();
                            cryptoStream.Close();
                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Finishes the Writing Process
        /// </summary>
        public void Finish()
        {
            if (encrypt)
            {
                byte[] plainText = Encoding.UTF8.GetBytes(EFile);
                byte[] cryptText;
                RijndaelManaged rm = new RijndaelManaged(){ Padding = PaddingMode.Zeros };

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, rm.CreateEncryptor(Key, Key ), CryptoStreamMode.Write)){

                        cs.Write(plainText, 0, plainText.Length);
                        cs.FlushFinalBlock();

                        cryptText = ms.ToArray();
                        cs.Close();
                    }

                    ms.Close();
                }

                sw.Write(Convert.ToBase64String(cryptText));
            }
        }
示例#21
1
 byte[] EncryptKeyForArchival(byte[] keyToExport, string passphrase, byte[] salt)
 {
     RijndaelManaged archivalEncryptionAlgorithm = new RijndaelManaged();
     byte[] rgbKey = this.GenerateArchivalKey(archivalEncryptionAlgorithm, passphrase, salt);
     byte[] rgbIV = new byte[archivalEncryptionAlgorithm.BlockSize / 8];
     return CryptographyUtility.Transform(archivalEncryptionAlgorithm.CreateEncryptor(rgbKey, rgbIV), keyToExport);
 }
示例#22
1
 public string Decrypt(string strEncryptedText)
 {
     if (strEncryptedText == null || strEncryptedText.Equals(""))
         return strEncryptedText;
     string strDecryptedText = null;
     RijndaelManaged rijndael = new RijndaelManaged();
     ICryptoTransform decryptor = rijndael.CreateDecryptor(Key, IV);
     byte[] byteEncryptedText = Convert.FromBase64String(strEncryptedText);
     MemoryStream memStream = new MemoryStream(byteEncryptedText);
     CryptoStream decryptStream = null;
     try
     {
         decryptStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read);
         byte[] byteDecryptedText = new byte[byteEncryptedText.Length];
         int decryptedByteCount = decryptStream.Read(byteDecryptedText, 0, byteDecryptedText.Length);
         strDecryptedText = Encoding.UTF8.GetString(byteDecryptedText, 0, decryptedByteCount);
     }
     finally
     {
         if (rijndael != null) rijndael.Clear();
         if (decryptor != null) decryptor.Dispose();
         if (memStream != null) memStream.Close();
         if (decryptStream != null) decryptStream.Close();
     }
     if (UseSalt)
         strDecryptedText = strDecryptedText.Substring(8);
     return strDecryptedText;
 }
示例#23
0
        public static SymmetricAlgorithm GetAlgorithmByName(String algorithmName)
        {
            SymmetricAlgorithm symmetricAlgorithm     = null;
            String             algorithmNameLoverCase = algorithmName.ToLower();

            switch (algorithmNameLoverCase)
            {
            case "aes":
                symmetricAlgorithm = new System.Security.Cryptography.AesCryptoServiceProvider();
                break;

            case "des":
                symmetricAlgorithm = new System.Security.Cryptography.DESCryptoServiceProvider();
                break;

            case "rc2":
                symmetricAlgorithm = new System.Security.Cryptography.RC2CryptoServiceProvider();
                break;

            case "rijndael":
                symmetricAlgorithm = new System.Security.Cryptography.RijndaelManaged();
                break;
            }
            return(symmetricAlgorithm);
        }
示例#24
0
文件: AES.cs 项目: zz110/WKT2015
        public static string AesEncrypt(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            Byte[] tmpArray       = { };

            //加密数据不足16位时用0补齐
            if (toEncryptArray.Length % 16 != 0)
            {
                int len = 16 - (toEncryptArray.Length % 16);
                tmpArray = Enumerable.Repeat((byte)0, len).ToArray();
            }
            toEncryptArray = toEncryptArray.Concat(tmpArray).ToArray();
            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.None
            };
            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return(Convert.ToBase64String(resultArray, 0, resultArray.Length));
        }
        /// <summary>
        /// Encrypts a string
        /// </summary>
        /// <param name="plainText">Text to be encrypted</param>
        /// <param name="password">Password to encrypt with</param>
        /// <param name="salt">Salt to encrypt with</param>
        /// <param name="hashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="passwordIterations">Number of iterations to do. The number of times the algorithm is run on the text. </param>
        /// <param name="initialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="keySize">Can be 128, 192, or 256</param>
        /// <returns>An encrypted string</returns>
        public static string Encrypt(string plainText, string password, string salt = "69ad1bfbd6605f3f6a3011460cdfb9db7757e0f9", string hashAlgorithm = "SHA1", int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY", int keySize = 256)
        {
            if (string.IsNullOrEmpty(plainText))
                return "";

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

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

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

            return Convert.ToBase64String(cipherTextBytes);
        }
示例#26
0
        /// <summary>
        /// AES解密,与JAVA通用
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str))
            {
                return("");
            }
            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)
            {
                Log.Error(e.Message);
                return("");
            }
        }
示例#27
0
 public static byte[] DecryptAES(byte[] input, string key)
 {
     System.Security.Cryptography.RijndaelManaged          AES      = new System.Security.Cryptography.RijndaelManaged();
     System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] decrypted;
     try
     {
         byte[] hash = new byte[32];
         byte[] temp = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key));
         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);
         //byte[] Buffer = Convert.for;
         //decrypted = System.Text.ASCIIEncoding.UTF8.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length));
         decrypted = DESDecrypter.TransformFinalBlock(input, 0, input.Length);
         return(decrypted);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
示例#28
0
    /// <summary>
    /// 暗号化された文字列を復号化する
    /// </summary>
    /// <param name="sourceString">暗号化された文字列</param>
    /// <returns>復号化された文字列</returns>
    public static string DecryptString(string sourceString)
    {
        //RijndaelManagedオブジェクトを作成
        System.Security.Cryptography.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;

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

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

        //バイト型配列を復号化する
        //復号化に失敗すると例外CryptographicExceptionが発生
        byte[] decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);

        //閉じる
        decryptor.Dispose();

        //バイト型配列を文字列に戻して返す
        return(System.Text.Encoding.UTF8.GetString(decBytes));
    }
示例#29
0
    /// <summary>
    /// 文字列を暗号化する
    /// </summary>
    /// <param name="sourceString">暗号化する文字列</param>
    /// <returns>暗号化された文字列</returns>
    public static string EncryptString(string sourceString)
    {
        //RijndaelManagedオブジェクトを作成
        System.Security.Cryptography.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;

        //文字列をバイト型配列に変換する
        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>
        /// Cryptographic transformation
        /// </summary>
        /// <param name="password"></param>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        private static ICryptoTransform GetTransform(bool Encrypt)
        {
            // Create an instance of the Rihndael class.
            RijndaelManaged Cipher = new System.Security.Cryptography.RijndaelManaged();

            // Calculate salt to make it harder to guess key by using a dictionary attack.
            byte[] Salt = SaltFromPassword();

            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            Rfc2898DeriveBytes SecretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(Keys.KEY, Salt, 10);

            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            byte[]           SecretKeyBytes            = SecretKey.GetBytes(32);
            byte[]           InitializationVectorBytes = SecretKey.GetBytes(16);
            ICryptoTransform Cryptor = null;

            if (Encrypt)
            {
                Cryptor = Cipher.CreateEncryptor(SecretKeyBytes, InitializationVectorBytes);
            }
            else
            {
                Cryptor = Cipher.CreateDecryptor(SecretKeyBytes, InitializationVectorBytes);
            }
            return(Cryptor);
        }
示例#31
0
                /// <summary>
                /// Método para encriptar em AES
                /// </summary>
                /// <param name="plaintext"></param>
                /// <param name="text"></param>
                /// <returns></returns>
                public static byte[] Encrypt(byte[] plaintext, string text)
                {
                    /*
                     * Block Length: 128bit
                     * Block Mode: ECB
                     * Data Padding: Padded by bytes which Asc() equal for number of padded bytes (done automagically)
                     * Key Padding: 0x00 padded to multiple of 16 bytes
                     * IV: None
                     */
                    byte[] key = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
                    System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();
                    AES.BlockSize = 128;
                    AES.Mode      = System.Security.Cryptography.CipherMode.ECB;
                    AES.Key       = key;

                    System.Security.Cryptography.ICryptoTransform encryptor = AES.CreateEncryptor();
                    MemoryStream mem = new MemoryStream();

                    System.Security.Cryptography.CryptoStream cryptStream = new System.Security.Cryptography.CryptoStream(mem, encryptor,
                                                                                                                          System.Security.Cryptography.CryptoStreamMode.Write);

                    cryptStream.Write(plaintext, 0, plaintext.Length);
                    cryptStream.FlushFinalBlock();

                    byte[] cypher = mem.ToArray();

                    cryptStream.Close();
                    cryptStream = null;
                    encryptor.Dispose();
                    AES = null;

                    return(cypher);
                }
示例#32
0
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str">需解密字符串</param>
        /// <param name="key">密钥</param>
        /// <param name="isDecodeUrl">是否需要URL解码</param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key, bool isDecodeUrl = true)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            if (isDecodeUrl)
            {
                str = System.Web.HttpUtility.UrlDecode(str);
            }

            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));
        }
示例#33
0
        public static string AES_Decrypt(string input_text)
        {
            //Please dont change or EDIT ANY PART of THIS CODE
            // ''' security_Code= [email protected]
            string securitycode = "[email protected]";

            System.Security.Cryptography.RijndaelManaged          AES      = new System.Security.Cryptography.RijndaelManaged();
            System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider();
            string decrypted = "";

            try
            {
                byte[] hash = new byte[32];
                byte[] temp = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(securitycode));
                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);
                AES.Key  = hash;
                AES.Mode = CipherMode.ECB;
                // Security.Cryptography.CipherMode.ECB
                System.Security.Cryptography.ICryptoTransform DESDecrypter = AES.CreateDecryptor();
                byte[] Buffer = Convert.FromBase64String(input_text);
                decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(decrypted);
        }
示例#34
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));
        }
        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;
        }
示例#36
0
文件: Isv.cs 项目: zwkjgs/XKD
        private string SaveConfig(string connectionstr)
        {
            string result;

            try
            {
                Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath);
                using (System.Security.Cryptography.RijndaelManaged cryptographer = this.GetCryptographer())
                {
                    configuration.AppSettings.Settings["IV"].Value  = System.Convert.ToBase64String(cryptographer.IV);
                    configuration.AppSettings.Settings["Key"].Value = System.Convert.ToBase64String(cryptographer.Key);
                }
                System.Web.Configuration.MachineKeySection machineKeySection = (System.Web.Configuration.MachineKeySection)configuration.GetSection("system.web/machineKey");
                machineKeySection.ValidationKey = Isv.CreateKey(20);
                machineKeySection.DecryptionKey = Isv.CreateKey(24);
                machineKeySection.Validation    = System.Web.Configuration.MachineKeyValidation.SHA1;
                machineKeySection.Decryption    = "3DES";
                configuration.ConnectionStrings.ConnectionStrings["HidistroSqlServer"].ConnectionString = connectionstr;
                configuration.ConnectionStrings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                configuration.Save();
                configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath);
                configuration.AppSettings.Settings.Remove("Installer");
                configuration.Save();
                result = "";
            }
            catch (System.Exception ex)
            {
                result = ex.Message;
            }
            return(result);
        }
示例#37
0
 //add near end of Terraria.Player.LoadPlayer before accessory check
 internal static void ReadModFile(Player player, string path, bool isCloudSave)
 {
     path = Path.ChangeExtension(path, ".tplr");
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     rijndaelManaged.Padding = PaddingMode.None;
     if (!FileUtilities.Exists(path, isCloudSave))
     {
         return;
     }
     byte[] buffer = FileUtilities.ReadAllBytes(path, isCloudSave);
     using (MemoryStream stream = new MemoryStream(buffer))
     {
         using (CryptoStream cryptoStream = new CryptoStream(stream, rijndaelManaged.CreateDecryptor(Player.ENCRYPTION_KEY, Player.ENCRYPTION_KEY), CryptoStreamMode.Read))
         {
             using (BinaryReader reader = new BinaryReader(cryptoStream))
             {
                 byte limit = reader.ReadByte();
                 if (limit == 0)
                 {
                     return;
                 }
                 byte[] flags = reader.ReadBytes(limit);
                 if (flags.Length < numFlagBytes)
                 {
                     Array.Resize(ref flags, numFlagBytes);
                 }
                 ReadModPlayer(player, flags, reader);
             }
         }
     }
 }
示例#38
0
        static void Main(string[] args)
        {
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(args[0]);
            System.Security.Cryptography.RijndaelManaged rijndaelManaged = new System.Security.Cryptography.RijndaelManaged();
            rijndaelManaged.Key = bytes;

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.PreserveWhitespace = true;
            xmlDocument.Load("needfiles");

            XmlElement    xmlElement    = xmlDocument.GetElementsByTagName("EncryptedData")[0] as XmlElement;
            EncryptedData encryptedData = new EncryptedData();

            encryptedData.LoadXml(xmlElement);
            EncryptedXml encryptedXml = new EncryptedXml();

            byte[] decryptedData = encryptedXml.DecryptData(encryptedData, rijndaelManaged);
            encryptedXml.ReplaceData(xmlElement, decryptedData);


            if (rijndaelManaged != null)
            {
                rijndaelManaged.Clear();
            }
            Console.WriteLine(xmlDocument.OuterXml);
        }
        private ICryptoTransform GetTransform(string password, bool encrypt)
        {
            // Create an instance of the Rihndael class.
            RijndaelManaged cipher = new System.Security.Cryptography.RijndaelManaged();

            // Calculate salt to make it harder to guess key by using a dictionary attack.
            byte[] salt = SaltFromPassword(password);
            WriteLog("// salt = " + System.BitConverter.ToString(salt).Replace("-", ""));
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            Rfc2898DeriveBytes secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 10);

            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            byte[] key = secretKey.GetBytes(32);
            byte[] iv  = secretKey.GetBytes(16);
            WriteLog("// key = " + System.BitConverter.ToString(key).Replace("-", ""));
            WriteLog("// iv = " + System.BitConverter.ToString(iv).Replace("-", ""));
            ICryptoTransform cryptor = null;

            if (encrypt)
            {
                cryptor = cipher.CreateEncryptor(key, iv);
            }
            else
            {
                cryptor = cipher.CreateDecryptor(key, iv);
            }
            return(cryptor);
        }
示例#40
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="text"></param>
        /// <param name="password"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string AESDecrypt(string text, string password, string iv)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            rijndaelCipher.Mode = CipherMode.CBC;

            rijndaelCipher.Padding = PaddingMode.PKCS7;

            rijndaelCipher.KeySize = 128;

            rijndaelCipher.BlockSize = 128;

            byte[] encryptedData = Convert.FromBase64String(text);

            byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);

            byte[] keyBytes = new byte[16];

            int len = pwdBytes.Length;

            if (len > keyBytes.Length) len = keyBytes.Length;

            System.Array.Copy(pwdBytes, keyBytes, len);

            rijndaelCipher.Key = keyBytes;

            byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
            rijndaelCipher.IV = ivBytes;

            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();

            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

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

                        ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }
            SymmetricKey.Clear();
            return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
        }
        public override SymmetricAlgorithm GetSymmetricAlgorithm(string algorithm)
        {
            SymmetricAlgorithm s = null;

            switch (algorithm)
            {
            case SecurityAlgorithms.Aes128Encryption:
            case SecurityAlgorithms.Aes192Encryption:
            case SecurityAlgorithms.Aes256Encryption:
            case SecurityAlgorithms.Aes128KeyWrap:
            case SecurityAlgorithms.Aes192KeyWrap:
            case SecurityAlgorithms.Aes256KeyWrap:
                s = new AES();
                break;

            case SecurityAlgorithms.TripleDesEncryption:
            case SecurityAlgorithms.TripleDesKeyWrap:
                if (key.Length == 24)
                {
                    throw new CryptographicException("The key size is 24 bytes, which known as vulnerable and thus not allowed.");
                }
                s = TripleDES.Create();
                break;

            default:
                throw new NotSupportedException(String.Format("This symmetric security key does not support specified algorithm '{0}'", algorithm));
            }
            s.Mode = CipherMode.CBC;
            s.GenerateIV();
            s.Key = key;
            return(s);
        }
示例#43
0
        private void encryptFile(string inputFile, string cryptFile)
        {
            FileStream fsCrypt = null;
            CryptoStream cryptStream = null;

            try
            {
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(TPW);
                fsCrypt = new FileStream(cryptFile, FileMode.Create);
                RijndaelManaged RMCrypto = new RijndaelManaged();
                cryptStream = new CryptoStream(fsCrypt,
                                                RMCrypto.CreateEncryptor(key, key),
                                                CryptoStreamMode.Write);

                byte[] inBytes = File.ReadAllBytes(inputFile);
                cryptStream.Write(inBytes, 0, inBytes.Length);

            }
            finally
            {
                if (cryptStream != null)
                    cryptStream.Close();

                if ( fsCrypt != null )
                    fsCrypt.Close();
            }
        }
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="encryptStr">明文</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string Encrypt()
        {
            //获取mac地址
            string str = GetFirstMacAddress();
            //获取下一天日期
            string key = DateTime.Now.AddDays(1).ToString("yyyyMMdd");

            //补全key为16个字符的字符串
            for (int i = key.Length; i < 16; i++)
            {
                key += "0";
            }
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            //开始AES加密
            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 //填白模式,对于AES, C# 框架中的 PKCS #7等同与Java框架中 PKCS #5
            };
            //字节编码, 将有特等含义的字符串转化为字节流
            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            //加密
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            //将加密后的字节流转化为字符串,以便网络传输与储存。
            return(Convert.ToBase64String(resultArray, 0, resultArray.Length));
        }
示例#45
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="text">加密字符</param>
        /// <param name="password">加密的密码</param>
        /// <param name="iv">密钥</param>
        /// <returns></returns>
        // 加密

        /// <summary>
        ///  AES 加密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesEncrypt(string str, string key)
        {
            if (key == null)
            {
                return("Key為空null");
            }
            // 判断Key是否为16位
            if (key.Length != 16)
            {
                return("Key長度不是16位元");
            }
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(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.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(Convert.ToBase64String(resultArray, 0, resultArray.Length));
        }
示例#46
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);
        }
示例#47
0
        private bool SaveConfig(out string errorMsg)
        {
            bool result;

            try
            {
                Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(base.Request.ApplicationPath);
                using (System.Security.Cryptography.RijndaelManaged cryptographer = this.GetCryptographer())
                {
                    configuration.AppSettings.Settings["IV"].Value  = System.Convert.ToBase64String(cryptographer.IV);
                    configuration.AppSettings.Settings["Key"].Value = System.Convert.ToBase64String(cryptographer.Key);
                }
                System.Web.Configuration.MachineKeySection machineKeySection = (System.Web.Configuration.MachineKeySection)configuration.GetSection("system.web/machineKey");
                machineKeySection.ValidationKey = Install.CreateKey(20);
                machineKeySection.DecryptionKey = Install.CreateKey(24);
                machineKeySection.Validation    = System.Web.Configuration.MachineKeyValidation.SHA1;
                machineKeySection.Decryption    = "3DES";
                configuration.ConnectionStrings.ConnectionStrings["HidistroSqlServer"].ConnectionString = this.GetConnectionString();
                configuration.ConnectionStrings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                configuration.Save();
                errorMsg = null;
                result   = true;
            }
            catch (System.Exception ex)
            {
                errorMsg = ex.Message;
                result   = false;
            }
            return(result);
        }
示例#48
0
    /// <summary>
    ///  AES 加密
    /// </summary>
    /// <param name="str"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static byte[] AesEncrypt(byte[] str, int count_, int index_ = 0, string key = _key)
    {
        // *remark*: ignore
        //if (string.IsNullOrEmpty(Encoding.UTF8.GetString(str, index_, count_))) return null;
        //Byte[] toEncryptArray = str;
        byte[] toEncryptArray = new byte[count_];
        Array.Copy(str, index_, toEncryptArray, 0, count_);

        System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
        {
            Key     = Encoding.ASCII.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 resultArray;

        string ret = Convert.ToBase64String(resultArray, 0, resultArray.Length);

        //UnityEngine.Debug.Log("<b>encrypted</b>:" + ret);
        //return Encoding.Default.GetBytes(ret);
        return(Encoding.ASCII.GetBytes(ret));
    }
示例#49
0
        public void init(int mode, byte[] key, byte[] iv)
        {
            this.mode        = mode;
            rijndael         = new RijndaelManaged();
            rijndael.Mode    = CipherMode.ECB;
            rijndael.Padding = PaddingMode.None;
            byte[] tmp;
            if (iv.Length > ivsize)
            {
                tmp = new byte[ivsize];
                Array.Copy(iv, 0, tmp, 0, tmp.Length);
                iv = tmp;
            }
            if (key.Length > bsize)
            {
                tmp = new byte[bsize];
                Array.Copy(key, 0, tmp, 0, tmp.Length);
                key = tmp;
            }

            counter = new byte[iv.Length];
            Array.Copy(iv, counter, iv.Length);

            try {
                cipher = rijndael.CreateEncryptor(key, null);
            }
            catch (Exception e) {
                Console.WriteLine(e);
                cipher = null;
            }
        }
        /// <summary>
        /// Recibe un texto plano  y lo devuelve cifrado
        /// Cifrado Simetrico
        /// </summary>
        /// <param name="contenido"></param>
        /// <param name="clave"></param>
        /// <returns></returns>
        public static String Cifrar(String contenido, String clave)
        {
            var encoding = new UTF8Encoding();
            var cripto = new RijndaelManaged(); // es un algotimo de cifrado, para cifrar
            //var iv = cripto.GenerateIV(); // Vector de inicialización: es un vector que tiene la semilla de inicialización
            // Este IV

            byte[] cifrado;
            byte[] retorno;
            byte[] key = GetKey(clave); // recibo una clave alfanumerica y devuelvo los bytes desde una cadena UTF8

            cripto.Key = key;
            cripto.GenerateIV(); // genera numeros aleatorios (semillas)
            // voy a crear el encriptador
            byte[] aEncriptar = encoding.GetBytes(contenido); // recibo contenido y lo convierto a array de bites

            // ya lo tengo cifrado
            cifrado = cripto.CreateEncryptor().TransformFinalBlock(aEncriptar, 0, aEncriptar.Length); // transforma el contenido desde 0 hasta que termine

            // creo mi retorno
            retorno = new byte[cripto.IV.Length + cifrado.Length]; // longitud del IV + el tamaño del cifrado

            cripto.IV.CopyTo(retorno, 0); // donde quiero copiar, en que posición quiero copiar
            cifrado.CopyTo(retorno, cripto.IV.Length);
            // la mejor forma es convertirlo a base 64, datos binarios, para almacenar array de bytes
            return Convert.ToBase64String(retorno); //  conjunto de bytes transformados en string
            // muy util para guardar imagenes
        }
示例#51
0
文件: AES.cs 项目: zz110/WKT2015
        /// <summary>
        /// AES解密/ECB/NoPadding
        /// </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);
            }
            Byte[] toEncryptArray = Convert.FromBase64String(str);
            //key不足16位时用1补齐
            if (key.Length % 16 != 0)
            {
                int keyLen = 16 - (key.Length % 16);
                for (int i = 0; i < keyLen; i++)
                {
                    key += "1";
                }
            }
            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.None
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return(Encoding.UTF8.GetString(resultArray).Replace("\0", ""));
        }
示例#52
0
文件: AES.cs 项目: nicoriff/NinoJS
 /// Generates a unique encryption vector
 public static byte[] GenerateEncryptionVector()
 {
     //Generate a Vector
     RijndaelManaged rm = new RijndaelManaged();
     rm.GenerateIV();
     return rm.IV;
 }
示例#53
0
    static System.Security.Cryptography.SymmetricAlgorithm CreateCam(string key, string IV, bool rij = true)
    {
        System.Security.Cryptography.SymmetricAlgorithm a = null;
        if (rij)
        {
            a = new System.Security.Cryptography.RijndaelManaged();
        }
        else
        {
            a = new System.Security.Cryptography.AesCryptoServiceProvider();
        }

        a.Mode      = System.Security.Cryptography.CipherMode.CBC;
        a.Padding   = System.Security.Cryptography.PaddingMode.Zeros;
        a.BlockSize = 128;
        a.KeySize   = 256;

        if (null != IV)
        {
            a.IV = System.Convert.FromBase64String(IV);
        }
        else
        {
            a.GenerateIV();
        }

        if (null != key)
        {
            a.Key = System.Convert.FromBase64String(key);
        }

        return(a);
    }
示例#54
0
        protected override SymmetricAlgorithm GetCryptProvider(string thePassword)
        {
            //Dim theAlgo As RijndaelManaged = New RijndaelManaged
            SymmetricAlgorithm theAlgo = new System.Security.Cryptography.RijndaelManaged();

            BuildCryptProvider(theAlgo, thePassword);
            return(theAlgo);
        }
示例#55
0
 private System.Security.Cryptography.RijndaelManaged GetCryptographer()
 {
     System.Security.Cryptography.RijndaelManaged rijndaelManaged = new System.Security.Cryptography.RijndaelManaged();
     rijndaelManaged.KeySize = 128;
     rijndaelManaged.GenerateIV();
     rijndaelManaged.GenerateKey();
     return(rijndaelManaged);
 }
示例#56
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;
 }
        // no error???
        public void GetSymmetricAlgorithmWrongSize2()
        {
            AES aes = new AES();

            aes.KeySize = 192;
            aes.GenerateKey();
            Key key = new Key(aes.Key);

            Assert.IsNotNull(key.GetSymmetricAlgorithm(SecurityAlgorithms.Aes256Encryption));
        }
示例#58
0
 public static String generateKey()
 {
     System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
     {
         KeySize = 128,
         Mode    = System.Security.Cryptography.CipherMode.ECB,
         Padding = System.Security.Cryptography.PaddingMode.PKCS7
     };
     rm.GenerateKey();
     return(Convert.ToBase64String(rm.Key));
 }
示例#59
0
 /// <summary>
 /// AES加密 - 16进制
 /// </summary>
 public static String EncryptHex(String content, String key)
 {
     Byte[] keyArray     = UTF8Encoding.UTF8.GetBytes(key);
     Byte[] encryptArray = UTF8Encoding.UTF8.GetBytes(content);
     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(encryptArray, 0, encryptArray.Length);
     return(ByteUtil.BytesToHex(resultArray));
 }
示例#60
0
 public static byte[] AESEncrypt(byte[] input, string Pass)
 {
     System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();
     byte[] hash = new byte[32];
     byte[] temp = new MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.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();
     return(DESEncrypter.TransformFinalBlock(input, 0, input.Length));
 }