Esempio n. 1
0
    internal static bool DecryptFile(string inputPath, string outputPath, string password)
    {
        var input = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
        var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write);

        // Essentially, if you want to use RijndaelManaged as AES you need to make sure that:
        // 1.The block size is set to 128 bits
        // 2.You are not using CFB mode, or if you are the feedback size is also 128 bits
        RijndaelManaged algorithm = new RijndaelManaged {KeySize = 256, BlockSize = 128};

        algorithm.Mode = CipherMode.CBC;

        var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(Salt));

        algorithm.Key = key.GetBytes(algorithm.KeySize/8);
        algorithm.IV = key.GetBytes(algorithm.BlockSize/8);

        try
        {
        using (var decryptedStream = new CryptoStream(output, algorithm.CreateDecryptor(), CryptoStreamMode.Write))
        {
        CopyStream(input, decryptedStream);
        return true;
        }
        }
        catch (CryptographicException)
        {
        throw new InvalidDataException("Please supply a correct password");
        }
        catch (Exception ex)
        {
        throw new Exception(ex.Message);
        }
    }
    //Encrypts the save file to prevent modification
    public static void EncryptFile(string path)
    {
        if(!File.Exists(path))
        {
            Debug.Log("File Not Found At: " + path);
            return;
        }

        XDocument xmlFile = XDocument.Load(path);
        XmlReader reader = xmlFile.CreateReader();
        reader.MoveToContent();
        if(xmlFile.Root.HasElements)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes ("86759426197648123460789546213421");
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes (reader.ReadInnerXml());
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length);
            xmlFile.Root.ReplaceNodes(Convert.ToBase64String (resultArray, 0, resultArray.Length));
        }

        xmlFile.Save(path);
    }
 protected 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);
     }
 }
Esempio n. 4
0
    /// <summary>
    /// Decrypts a previously encrypted string.
    /// </summary>
    /// <param name="inputText">The encrypted string to decrypt.</param>
    /// <returns>A decrypted string.</returns>
    public static string Decrypt(string inputText)
    {
        string decrypted = null;
        try
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            byte[] encryptedData = Convert.FromBase64String(inputText);
            PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

            using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
            {
                using (MemoryStream memoryStream = new MemoryStream(encryptedData))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        byte[] plainText = new byte[encryptedData.Length];
                        int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                        decrypted = Encoding.Unicode.GetString(plainText, 0, decryptedCount);
                    }
                }
            }
        }
        catch (Exception)
        {
        }
        return decrypted;
    }
Esempio n. 5
0
 /// Generates a unique encryption vector
 public static byte[] GenerateEncryptionVector()
 {
     //Generate a Vector
     RijndaelManaged rm = new RijndaelManaged();
     rm.GenerateIV();
     return rm.IV;
 }
Esempio n. 6
0
 /// -------------- 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;
 }
Esempio n. 7
0
	public AES()
	{
		RijndaelManaged rm = new RijndaelManaged();
		_encryptor = rm.CreateEncryptor(_key, _vector);
		_decryptor = rm.CreateDecryptor(_key, _vector);
		encoder = new UTF8Encoding();
	}
Esempio n. 8
0
    public static 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;
        //end public byte[] AES_Encrypt
    }
 /// <summary>
 /// Decrypts a Base64 encoded string previously generated with a specific crypt class, returns a string
 /// </summary>
 /// <param name="cipherText">A base64 encoded string containing encryption information</param>
 /// <param name="passPhrase">The passphrase used to encrypt the inputed text</param>
 /// <returns></returns>
 public string Decrypt(string cipherText, string passPhrase)
 {
     try
         {
             var ciphertextS = DecodeFrom64(cipherText);
             var ciphersplit = Regex.Split(ciphertextS, "-");
             var passsalt = Convert.FromBase64String(ciphersplit[1]);
             var initVectorBytes = Convert.FromBase64String(ciphersplit[0]);
             var cipherTextBytes = Convert.FromBase64String(ciphersplit[2]);
             var password = new PasswordDeriveBytes(passPhrase, passsalt, "SHA512", 100);
             var keyBytes = password.GetBytes(256/8);
             var symmetricKey = new RijndaelManaged();
             symmetricKey.Mode = CipherMode.CBC;
             var decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
             var memoryStream = new MemoryStream(cipherTextBytes);
             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);
         }
         catch (Exception m)
         {
             return "error";
         }
 }
    //Decrypts the save file for loading purposes
    public static void DecryptFile(string path)
    {
        if(!File.Exists(path))
        {
            Debug.Log("File Not Found At: " + path);
            return;
        }

        XDocument xmlFile = XDocument.Load (path);
        XmlReader reader = xmlFile.CreateReader ();

        reader.MoveToContent ();
        if(xmlFile.Root.Elements() != null)
        {
            Debug.Log("decrypting");
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes ("86759426197648123460789546213421");
            byte[] toEncryptArray = Convert.FromBase64String (reader.ReadInnerXml());
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length);
            string data = (UTF8Encoding.UTF8.GetString (resultArray));
            data = "<Root>" + data + "</Root>";
            xmlFile = (XDocument.Parse(data));

        }

        xmlFile.Save(path);
    }
    /// <summary>
    /// Decrypt byte array
    /// </summary>
    /// <param name="dataStream">encrypted data array</param>
    /// <param name="password">password</param>
    /// <returns>unencrypted data array</returns>
    private static byte[] DecryptStream(byte[] dataStream, string password)
    {
        SqlPipe pipe = SqlContext.Pipe;
        //the decrypter
        RijndaelManaged cryptic = new RijndaelManaged
        {
            Key = Encoding.ASCII.GetBytes(password),
            IV = Encoding.ASCII.GetBytes("1qazxsw23edcvfr4"),
            Padding = PaddingMode.ISO10126,
        };

        //Get a decryptor that uses the same key and IV as the encryptor used.
        ICryptoTransform decryptor = cryptic.CreateDecryptor();

        //Now decrypt encrypted data stream
        MemoryStream msDecrypt = new MemoryStream(dataStream);
        CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

        byte[] fromEncrypt = new byte[dataStream.Length];

        //Read the data out of the crypto stream.
        try
        {
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
        }
        catch (Exception e)
        {
            pipe.Send("Failed to decrypt data");
            pipe.Send(e.Message);
            throw;
        }

        return fromEncrypt;
    }
Esempio n. 12
0
    private static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
    {
        byte[] decryptedBytes = null;

        using (MemoryStream ms = new MemoryStream())
        {
            using (RijndaelManaged AES = new RijndaelManaged())
            {
                try
                {
                    AES.KeySize = AESKeySize_256;
                    AES.Key = passwordBytes;
                    AES.Mode = AESCipherMode_ECB;
                    AES.Padding = AESPadding_PKCS7;

                    using (CryptoStream cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                        cs.Close();
                    }
                    decryptedBytes = ms.ToArray();
                }
                catch (CryptographicException e)
                {
                    throw e;
                }
            }
        }

        return decryptedBytes;
    }
Esempio n. 13
0
    public static byte[] Encrypt(byte[] data, string password)
    {
        byte[] result = null;
            byte[] passwordBytes = Encoding.Default.GetBytes(password);

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = keySize;
                    AES.BlockSize = 128;
                    var key = new Rfc2898DeriveBytes(passwordBytes, salt, 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(data, 0, data.Length);
                        cs.Close();
                    }
                    result = ms.ToArray();
                }

            }
            return result;
    }
 // Token: 0x06000EF7 RID: 3831 RVA: 0x00045348 File Offset: 0x00043548
 public static string Encrypt(string unencrypted)
 {
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(SimpleAES.key, SimpleAES.vector);
     UTF8Encoding uTF8Encoding = new UTF8Encoding();
     return Convert.ToBase64String(SimpleAES.Encrypt(uTF8Encoding.GetBytes(unencrypted), encryptor));
 }
 // Token: 0x06000EF8 RID: 3832 RVA: 0x00045384 File Offset: 0x00043584
 public static string Decrypt(string encrypted)
 {
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(SimpleAES.key, SimpleAES.vector);
     UTF8Encoding uTF8Encoding = new UTF8Encoding();
     return uTF8Encoding.GetString(SimpleAES.Decrypt(Convert.FromBase64String(encrypted), decryptor));
 }
Esempio n. 16
0
 public static string Decrypt(string cipherText, string passPhrase)
 {
     byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                 {
                     try
                     {
                         using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                         {
                             byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                             int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                             return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                         }
                     }
                     catch
                     {
                         return "ERROR";
                     }
                 }
             }
         }
     }
 }
Esempio n. 17
0
 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);
                     }
                 }
             }
         }
     }
 }
Esempio n. 18
0
        public static byte[] Decrypt(byte[] cipherText, string passPhrase,bool padding)
        {
            byte[] cipherTextBytes = cipherText;
            using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
            {
                byte[] keyBytes = password.GetBytes(keysize / 8);
                using (RijndaelManaged symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.Mode = CipherMode.CBC;
                    if(!padding)
                        symmetricKey.Padding = PaddingMode.None;
                    using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                    {
                        using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                        {

                                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                                {
                                    byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                                    cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                    return plainTextBytes;
                                }

                        }
                    }
                }
            }
        }
Esempio n. 19
0
    /// <summary>
    /// Encrypt string using AES 128
    /// </summary>
    /// <param name="plaintext"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string Encrypt(string plaintext, string key)
    {
        byte[] keybytes = Encoding.UTF8.GetBytes(key);

        RijndaelManaged aes = new RijndaelManaged();
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.None;
        byte[] IVbytes = Encoding.ASCII.GetBytes("dongbinhuiasxiny");

        ICryptoTransform encryptor = aes.CreateEncryptor(keybytes, IVbytes);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);

        byte[] plainBytes = Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(plaintext)));

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

        cs.FlushFinalBlock();

        byte[] cipherBytes = ms.ToArray();

        ms.Close();
        cs.Close();

        return Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
    }
Esempio n. 20
0
    public static void EncryptFile(string path)
    {
        if (!File.Exists(path))
        {
            Debug.Log("File Not Found At: " + path);
            return;
        }

        XmlDocument xmlFile = new XmlDocument();
        xmlFile.Load(path);
        XmlElement xmlRoot = xmlFile.DocumentElement;

        if (xmlRoot.ChildNodes.Count > 1)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes ("86759426197648123460789546213421");
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes (xmlRoot.InnerXml);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length);
            xmlRoot.InnerXml = Convert.ToBase64String (resultArray, 0, resultArray.Length);
        }

        xmlFile.Save(path);
    }
Esempio n. 21
0
	public static byte[] Encrypt(byte[] PlainBytes, byte[] Key,byte[] IV )  
	{  
		byte[] encrypted;
		// Create an RijndaelManaged object
		// with the specified key and IV.
		using (RijndaelManaged rijAlg = new RijndaelManaged())
		{
			rijAlg.Key = Key;
			rijAlg.IV = IV;
			
			// Create a decrytor to perform the stream transform.
			ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
			
			// Create the streams used for encryption.
			using (MemoryStream msEncrypt = new MemoryStream())
			{
				using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
				{
					csEncrypt.Write(PlainBytes,0,PlainBytes.Length);
					csEncrypt.FlushFinalBlock();
					encrypted = msEncrypt.ToArray();
				}
			}
		}

		// Return the encrypted bytes from the memory stream.
		return encrypted;
	}  
Esempio n. 22
0
    public static string DecryptRijndael(string encryptedString)
    {
        byte[] encrypted;

        byte[] fromEncrypted;

        UTF8Encoding utf8Converter = new UTF8Encoding();

        encrypted = Convert.FromBase64String(encryptedString);

        RijndaelManaged myRijndael = new RijndaelManaged();

        ICryptoTransform decryptor = myRijndael.CreateDecryptor(Key, IV);

        MemoryStream ms = new MemoryStream(encrypted);

        CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);

        fromEncrypted = new byte[encrypted.Length];

        cs.Read(fromEncrypted, 0, fromEncrypted.Length);

        string decryptedString = utf8Converter.GetString(fromEncrypted);
        int indexNull = decryptedString.IndexOf("\0");
        if (indexNull > 0)
        {
            decryptedString = decryptedString.Substring(0, indexNull);
        }
        return decryptedString;
    }
Esempio n. 23
0
 static AesEncryptor()
 {
     encoder = new UTF8Encoding();
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     rijndaelManaged.Key = encoder.GetBytes(keyString).Take(keySize).ToArray();
     rijndael = rijndaelManaged;
     rijndael.BlockSize = 128;
 }
Esempio n. 24
0
    /// <summary>
    /// ถอดรหัสข้อมูล
    /// </summary>
    /// <param name="Value">ข้อมูลที่ต้องการให้ถอดรหัส</param>
    /// <returns>ข้อมูลหลังจากถอดรหัส</returns>
    /// <example>
    /// clsSecurity.Decrypt("e0NDKIlUhHF3qcIdkmGpZw==");
    /// </example>
    public string Decrypt(string Value)
    {
        #region Variable
        SymmetricAlgorithm mCSP;
        ICryptoTransform ct = null;
        MemoryStream ms = null;
        CryptoStream cs = null;
        byte[] byt;
        byte[] result;
        #endregion
        #region Procedure
        mCSP = new RijndaelManaged();

        try
        {
            mCSP.Key = _key;
            mCSP.IV = _initVector;
            ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);

            byt = Convert.FromBase64String(Value);

            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();

            cs.Close();
            result = ms.ToArray();
        }
        catch
        {
            result = null;
        }
        finally
        {
            if (ct != null)
                ct.Dispose();
            if (ms != null)
                if (ms.CanRead)
                {
                    ms.Dispose();
                }
            if (cs != null)
                if (cs.CanRead)
                {
                    cs.Dispose();
                }
        }
        try
        {
            return ASCIIEncoding.UTF8.GetString(result);
        }
        catch (Exception)
        {
            return "";
        }
        #endregion
    }
Esempio n. 25
0
 /// <summary>
 /// Initialize the cipher.
 /// </summary>
 /// <param name="key"></param>
 public Cipher(String key)
 {
     using (SHA256Managed SHA = new SHA256Managed())
     {
         AES = new RijndaelManaged();
         AES.Key = SHA.ComputeHash(Encoding.ASCII.GetBytes(key));
         AES.IV = new Byte[16];
     }
 }
Esempio n. 26
0
    public static RijndaelManaged DataEncryptAlgorithm()
    {
        _encryptAlgorithm = new RijndaelManaged ();
        _encryptAlgorithm.Key = Encoding.UTF8.GetBytes (DATA_ENCRYPT_KEY);
        _encryptAlgorithm.Mode = CipherMode.ECB;
        _encryptAlgorithm.Padding = PaddingMode.PKCS7;

        return _encryptAlgorithm;
    }
Esempio n. 27
0
	private RijndaelManaged configAES256() {
		byte[] keyBytes = Encoding.UTF8.GetBytes(this.key);
		
		RijndaelManaged rjnd = new RijndaelManaged();
		rjnd.Key = keyBytes;
		rjnd.Mode = CipherMode.ECB;
		rjnd.Padding = PaddingMode.PKCS7;
		
		return rjnd;
	}
Esempio n. 28
0
    public List<string> GetAllData()
    {
        string line = "";
        string input_file = "./Saved Data/characters.xml";
        List<string> keyList = new List<string>();
        List<string> elemList = new List<string>();
        UnicodeEncoding encoding = new UnicodeEncoding();
        byte[] key = null;
        RijndaelManaged RMCrypto = new RijndaelManaged();
        string tagID;
        string tagIDend;
        int indexStart = 0;
        int indexEnd = 0;

        key = encoding.GetBytes(Data_Handler_Key.keyvalue);
        FileStream decrypted_file = new FileStream(input_file, FileMode.Open);
        CryptoStream cryptography_stream = new CryptoStream(decrypted_file, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read);
        using (MemoryStream msDecrypt = new MemoryStream())
        {
            using (BufferedStream readBuffer = new BufferedStream(cryptography_stream))
            using (StreamReader srDecrypt = new StreamReader(readBuffer))
            {
                    while ((line = srDecrypt.ReadLine()) != null)
                    {
                        elemList.Add(line);
                    }
            }
        }
        cryptography_stream.Close();
        decrypted_file.Close();
        tagID = "<id>" + Character_Info.id + "</id>";
        tagIDend = "<idend>" + Character_Info.id + "</idend>";
        int i = 0;
        foreach(var content in elemList)
        {
            if(content == tagID)
            {
                indexStart = i;
            }

            if(content == tagIDend)
            {
                indexEnd = i;
            }
            i++;
        }
        if (indexStart != indexEnd)
        {
            elemList.RemoveRange(indexStart, indexEnd - indexStart);
        }
        elemList.Remove("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        elemList.Remove("<savedcharacters>");
        elemList.Remove("</savedcharacters>");
        return elemList;
    }
Esempio n. 29
0
    public SimpleAES()
    {
        //This is our encryption method
        RijndaelManaged rm = new RijndaelManaged();

        //Create an encryptor and a decryptor using our encryption method, key, and vector.
        EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
        DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);

        //Used to translate bytes to text and vice versa
        UTFEncoder = new System.Text.UTF8Encoding();
    }
Esempio n. 30
0
        /// <summary>
        /// 복호화 Function (AES256 암호화 알고리즘 적용)
        /// </summary>
        /// <param name="pEncrptStr">암호화 문자열</param>
        /// <returns>원문</returns>
        public static String FN_DECRPT(String pEncrptStr)
        {
            String tmpEncrptStr = pEncrptStr.ToString();

            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            byte[] EncryptedData = Convert.FromBase64String(tmpEncrptStr);
            byte[] Salt          = Encoding.ASCII.GetBytes(ConstValue.ServerInfoMonitor_General.ENCRPT_KEY.Length.ToString());

            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ConstValue.ServerInfoMonitor_General.ENCRPT_KEY, Salt);

            // Decryptor 객체를 만든다.
            ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

            MemoryStream memoryStream = new MemoryStream(EncryptedData);

            // 데이터 읽기(복호화이므로) 용도로 cryptoStream객체를 선언, 초기화
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

            // 복호화된 데이터를 담을 바이트 배열을 선언한다.
            // 길이는 알 수 없지만, 일단 복호화되기 전의 데이터의 길이보다는
            // 길지 않을 것이기 때문에 그 길이로 선언한다.
            byte[] PlainText = new byte[EncryptedData.Length];

            // 복호화 시작
            int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);

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

            // 복호화된 데이터를 문자열로 바꾼다.
            string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);

            // 최종 결과 리턴
            return(DecryptedData);
        }
Esempio n. 31
0
        public static string EncryptRijndaelManaged(string value)
        {
            if (value == string.Empty)
            {
                return(string.Empty);
            }

            RijndaelManaged crypto       = new RijndaelManaged();
            MemoryStream    memoryStream = new MemoryStream();

            CryptoStream cryptoStream = new CryptoStream(
                memoryStream,
                crypto.CreateEncryptor(key_192, iv_128),
                CryptoStreamMode.Write);

            StreamWriter streamWriter = new StreamWriter(cryptoStream);

            streamWriter.Write(value);
            streamWriter.Flush();
            cryptoStream.FlushFinalBlock();
            memoryStream.Flush();

            return(Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
        }
Esempio n. 32
0
        public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes, byte[] salt)
        {
            byte[] decryptedBytes = null;

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

            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.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                        cs.Close();
                    }
                    decryptedBytes = ms.ToArray();
                }
            }

            return(decryptedBytes);
        }
Esempio n. 33
0
        private static String AES_encrypt(byte[] Input, byte[] Iv, byte[] Key)
        {
            var aes = new RijndaelManaged();

            //秘钥的大小,以位为单位
            aes.KeySize = 256;
            //支持的块大小
            aes.BlockSize = 128;
            //填充模式
            //aes.Padding = PaddingMode.PKCS7;
            aes.Padding = PaddingMode.None;
            aes.Mode    = CipherMode.CBC;
            aes.Key     = Key;
            aes.IV      = Iv;
            var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);

            byte[] xBuff = null;

            #region 自己进行PKCS7补位,用系统自己带的不行
            var msg = new byte[Input.Length + 32 - Input.Length % 32];
            Array.Copy(Input, msg, Input.Length);
            var pad = KCS7Encoder(Input.Length);
            Array.Copy(pad, 0, msg, Input.Length, pad.Length);
            #endregion

            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                {
                    cs.Write(msg, 0, msg.Length);
                }
                xBuff = ms.ToArray();
            }
            var Output = Convert.ToBase64String(xBuff);
            return(Output);
        }
Esempio n. 34
0
        public string Decrypt(string textToDecrypt, string key)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            rijndaelCipher.Mode    = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;

            rijndaelCipher.KeySize   = 0x80;
            rijndaelCipher.BlockSize = 0x80;
            byte[] encryptedData = Convert.FromBase64String(textToDecrypt);
            byte[] pwdBytes      = Encoding.UTF8.GetBytes(key);
            byte[] keyBytes      = new byte[0x10];
            int    len           = pwdBytes.Length;

            if (len > keyBytes.Length)
            {
                len = keyBytes.Length;
            }
            Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            rijndaelCipher.IV  = keyBytes;
            byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
            return(Encoding.UTF8.GetString(plainText));
        }
Esempio n. 35
0
    /// <summary>
    /// Encrypts specified plaintext using Rijndael symmetric key algorithm
    /// and returns a base64-encoded result.
    /// </summary>
    /// <param name="plainText">
    /// Plaintext value to be encrypted.
    /// </param>
    /// <param name="passPhrase">
    /// Passphrase from which a pseudo-random password will be derived. The
    /// derived password will be used to generate the encryption key.
    /// Passphrase can be any string. In this example we assume that this
    /// passphrase is an ASCII string.
    /// </param>
    /// <param name="saltValue">
    /// Salt value used along with passphrase to generate password. Salt can
    /// be any string. In this example we assume that salt is an ASCII string.
    /// </param>
    /// <param name="hashAlgorithm">
    /// Hash algorithm used to generate password. Allowed values are: "MD5" and
    /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
    /// </param>
    /// <param name="passwordIterations">
    /// Number of iterations used to generate password. One or two iterations
    /// should be enough.
    /// </param>
    /// <param name="initVector">
    /// Initialization vector (or IV). This value is required to encrypt the
    /// first block of plaintext data. For RijndaelManaged class IV must be
    /// exactly 16 ASCII characters long.
    /// </param>
    /// <param name="keySize">
    /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
    /// Longer keys are more secure than shorter keys.
    /// </param>
    /// <returns>
    /// Encrypted value formatted as a base64-encoded string.
    /// </returns>
    public static byte[] Encrypt(byte[] buffer, string passPhrase, string saltValue, Cryptos hash, int passwordIterations, string initVector, int keySize)
    {
        string hashAlgorithm = hash.ToString();

        byte[] initVectorBytes       = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes        = Encoding.ASCII.GetBytes(saltValue);
        byte[] plainTextBytes        = buffer;
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);

        byte[]          keyBytes     = password.GetBytes(keySize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();

        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform encryptor    = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
        MemoryStream     memoryStream = new MemoryStream();
        CryptoStream     cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
        cryptoStream.FlushFinalBlock();
        byte[] cipherTextBytes = memoryStream.ToArray();
        memoryStream.Close();
        cryptoStream.Close();
        return(cipherTextBytes);
    }
Esempio n. 36
0
        public string Encrypt(string Original)
        {
            byte[]          ToEncrypt;
            RijndaelManaged MyRijndael    = new RijndaelManaged();
            ASCIIEncoding   TextConverter = new ASCIIEncoding();

            MyRijndael.Key = this.m_Key;
            MyRijndael.IV  = this.m_IV;

            ICryptoTransform Encryptor = MyRijndael.CreateEncryptor();
            MemoryStream     MsEncrypt = new MemoryStream();
            CryptoStream     CsEncrypt = new CryptoStream(MsEncrypt, Encryptor, CryptoStreamMode.Write);

            //Convert the data to a byte array.
            ToEncrypt = TextConverter.GetBytes(Original);

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

            //Get encrypted array of bytes.

            return(Convert.ToBase64String(MsEncrypt.ToArray()));
        }
Esempio n. 37
0
        public string DeEncrypt(string Encrypted)
        {
            byte[]          FromEncrypt;
            RijndaelManaged MyRijndael    = new RijndaelManaged();
            ASCIIEncoding   TextConverter = new ASCIIEncoding();

            MyRijndael.Key = this.m_Key;
            MyRijndael.IV  = this.m_IV;

            ICryptoTransform DeCryptor = MyRijndael.CreateDecryptor();

            MemoryStream MsDecrypt = new MemoryStream(Convert.FromBase64String(Encrypted));
            CryptoStream CsDecrypt = new CryptoStream(MsDecrypt, DeCryptor, CryptoStreamMode.Read);

            FromEncrypt = new byte[Convert.FromBase64String(Encrypted).Length];

            //Read the data out of the crypto stream.
            //CsDecrypt.Read(FromEncrypt, 0, FromEncrypt.Length);

            //Convert the byte array back into a string.
            StreamReader sr = new StreamReader(CsDecrypt);

            return(sr.ReadToEnd());
        }
Esempio n. 38
0
        public static string Encrypt(string plainText, string PasswordHash)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] keyBytes       = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var    symmetricKey   = new RijndaelManaged()
            {
                Mode = CipherMode.CBC, Padding = PaddingMode.Zeros
            };
            var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

            byte[] cipherTextBytes;
            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                    cryptoStream.Close();
                }
                memoryStream.Close();
            }
            return(Convert.ToBase64String(cipherTextBytes));
        }
        public static string desencriptar(string cadena)
        {
            byte[]          cadenaBytes = Convert.FromBase64String(cadena);
            byte[]          claveBytes  = Encoding.UTF8.GetBytes(clave);
            RijndaelManaged rij         = new RijndaelManaged();

            rij.Mode      = CipherMode.ECB;
            rij.BlockSize = 256;
            rij.Padding   = PaddingMode.Zeros;
            ICryptoTransform desencriptador;

            desencriptador = rij.CreateDecryptor(claveBytes, rij.IV);
            MemoryStream memStream = new MemoryStream(cadenaBytes);
            CryptoStream cifradoStream;

            cifradoStream = new CryptoStream(memStream, desencriptador,
                                             CryptoStreamMode.Read);
            StreamReader lectorStream = new StreamReader(cifradoStream);
            string       resultado    = lectorStream.ReadToEnd();

            memStream.Close();
            cifradoStream.Close();
            return(resultado);
        }
Esempio n. 40
0
        public static byte[] AesDecrypt(byte[] origin, string password)
        {
            RijndaelManaged    aes    = new RijndaelManaged();
            Rfc2898DeriveBytes key    = CreateKey(password);
            Rfc2898DeriveBytes vector = CreateKey(password);

            aes.BlockSize = 128;
            aes.KeySize   = 256;
            aes.Mode      = CipherMode.CBC;
            aes.Padding   = PaddingMode.PKCS7;
            aes.Key       = key.GetBytes(32);
            aes.IV        = vector.GetBytes(16);

            ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
                {
                    cs.Write(origin, 0, origin.Length);
                }
                return(ms.ToArray());
            }
        }
Esempio n. 41
0
        public static string DecryptRJ256(string prm_text_to_decrypt)
        {
            byte[]          array           = Convert.FromBase64String(prm_text_to_decrypt);
            RijndaelManaged rijndaelManaged = new RijndaelManaged();

            rijndaelManaged.Padding   = PaddingMode.Zeros;
            rijndaelManaged.Mode      = CipherMode.CBC;
            rijndaelManaged.KeySize   = 256;
            rijndaelManaged.BlockSize = 256;
            byte[] array2 = new byte[32];
            byte[] rgbIV  = new byte[32];
            byte[] array3 = new byte[array.Length - array2.Length];
            Array.Copy(array, 0, array3, 0, array3.Length);
            Array.Copy(array, array.Length - array2.Length, array2, 0, array2.Length);
            rgbIV = Encoding.UTF8.GetBytes(RJ256Key);
            ICryptoTransform transform = rijndaelManaged.CreateDecryptor(array2, rgbIV);

            byte[]       array4       = new byte[array3.Length];
            MemoryStream stream       = new MemoryStream(array3);
            CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Read);

            cryptoStream.Read(array4, 0, array4.Length);
            return(Encoding.UTF8.GetString(array4).TrimEnd(new char[1]));
        }
Esempio n. 42
0
        private static dynamic ChechAlg()
        {
            dynamic Alg = null;

            switch (Encryption.currentAlg)
            {
            case 1:
                Alg = new DESCryptoServiceProvider();
                break;

            case 2:
                Alg = new TripleDESCryptoServiceProvider();
                break;

            case 3:
                Alg = new RijndaelManaged();
                break;

            case 4:
                Alg = new RC2CryptoServiceProvider();
                break;
            }
            return(Alg);
        }
Esempio n. 43
0
    public static string EncryptRJ128Byte(string prm_key, string prm_iv, byte[] toEncrypt)
    {
        var myRijndael = new RijndaelManaged()
        {
            Padding   = PaddingMode.PKCS7,
            Mode      = CipherMode.CBC,
            KeySize   = 256,
            BlockSize = 128
        };

        var key = Encoding.UTF8.GetBytes(prm_key);
        var IV  = Encoding.UTF8.GetBytes(prm_iv);

        var encryptor = myRijndael.CreateEncryptor(key, IV);
        var msEncrypt = new MemoryStream();
        var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

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

        var encrypted = msEncrypt.ToArray();

        return(Convert.ToBase64String(encrypted));
    }
Esempio n. 44
0
        public static string Encrypt(string text)
        {
            var rijndaelCipher = new RijndaelManaged();

            byte[] plainText = Encoding.Unicode.GetBytes(text);
            byte[] salt      = Encoding.ASCII.GetBytes(Password.Length.ToString());
            var    secretKey = new PasswordDeriveBytes(Password, salt);

            //Creates a symmetric encryptor object.
            ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
            var memoryStream           = new MemoryStream();
            //Defines a stream that links data streams to cryptographic transformations
            var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

            cryptoStream.Write(plainText, 0, plainText.Length);
            //Writes the final state and clears the buffer
            cryptoStream.FlushFinalBlock();
            byte[] cipherBytes = memoryStream.ToArray();
            memoryStream.Close();
            cryptoStream.Close();
            string encryptedData = Convert.ToBase64String(cipherBytes);

            return(encryptedData);
        }
Esempio n. 45
0
        /// <summary>
        /// Encrypts the file.
        /// </summary>
        /// <param name="inputFile">The input file.</param>
        /// <param name="outputFile">The output file.</param>
        /// <param name="skey">The skey.</param>
        static void EncryptFile(string inputFile, string outputFile, string skey)
        {
            try
            {
                using (var aes = new RijndaelManaged {
                    BlockSize = 256
                })
                {
                    byte[] key = Encoding.UTF8.GetBytes(skey);

                    var IV = new byte[256 / 8];

                    using (FileStream fsCrypt = new FileStream(outputFile, FileMode.CreateNew))
                    {
                        using (ICryptoTransform encryptor = aes.CreateEncryptor(key, IV))
                        {
                            using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
                            {
                                using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
                                {
                                    int data;
                                    while ((data = fsIn.ReadByte()) != -1)
                                    {
                                        cs.WriteByte((byte)data);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 46
0
 public static string Decrypt(string cipherText, string passPhrase)
 {
     byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                 {
                     using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                     {
                         byte[] plainTextBytes     = new byte[cipherTextBytes.Length];
                         int    decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                         return(Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount));
                     }
                 }
             }
         }
     }
 }
Esempio n. 47
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));
            }
Esempio n. 48
0
        public static string Decrypt(string text, string password)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return(text);
            }
            var heap = Convert.FromBase64String(text);
            var salt = heap
                       .Take(PROTECTION_KEY_SIZE / 8)
                       .ToArray();
            var iv = heap.Skip(PROTECTION_KEY_SIZE / 8)
                     .Take(PROTECTION_KEY_SIZE / 8)
                     .ToArray();
            var cipher = heap
                         .Skip((PROTECTION_KEY_SIZE / 8) * 2)
                         .Take(heap.Length - ((PROTECTION_KEY_SIZE / 8) * 2))
                         .ToArray();

            using (var protection = new Rfc2898DeriveBytes(password, salt, DERIVATION_ITERATIONS)) {
                using (var symmetricKey = new RijndaelManaged()) {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode      = CipherMode.CBC;
                    symmetricKey.Padding   = PaddingMode.PKCS7;
                    var bytes = protection.GetBytes(PROTECTION_KEY_SIZE / 8);
                    using (var decryptor = symmetricKey.CreateDecryptor(bytes, iv)) {
                        using (var memory = new MemoryStream(cipher)) {
                            using (var crypto = new CryptoStream(memory, decryptor, CryptoStreamMode.Read)) {
                                var data  = new byte[cipher.Length];
                                var count = crypto.Read(data, 0, data.Length);
                                return(Encoding.UTF8.GetString(data, 0, count));
                            }
                        }
                    }
                }
            }
        }
Esempio n. 49
0
            ///<summary>
            ///Encrypts a string
            ///</summary>
            ///<param name="PlainText">Text to be encrypted</param>
            ///<param name="Password">Password to encrypt with</param>
            ///<param name="Salt">Salt to encrypt with</param>
            ///<param name="HashAlgorithm">Can be either SHA1 or MD5</param>
            ///<param name="PasswordIterations">Number of iterations to do</param>
            ///<param name="InitialVector">Needs to be 16 ASCII characters long</param>
            ///<param name="KeySize">Can be 128, 192, or 256</param>
            ///<returns>An encrypted string</returns>
            public static string Encrypt(string PlainText, string Password,
                                         string Salt            = "Kosher", string HashAlgorithm = "SHA1",
                                         int PasswordIterations = 2, string InitialVector        = "OFRna73m*aze01xY",
                                         int KeySize            = 256)
            {
                if (string.IsNullOrEmpty(PlainText))
                {
                    return("");
                }
                byte[] InitialVectorBytes           = Encoding.ASCII.GetBytes(InitialVector);
                byte[] SaltValueBytes               = Encoding.ASCII.GetBytes(Salt);
                byte[] PlainTextBytes               = Encoding.UTF8.GetBytes(PlainText);
                PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);

                byte[]          KeyBytes     = DerivedPassword.GetBytes(KeySize / 8);
                RijndaelManaged SymmetricKey = new RijndaelManaged();

                SymmetricKey.Mode = CipherMode.CBC;
                byte[] CipherTextBytes = null;
                using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
                {
                    using (MemoryStream MemStream = new MemoryStream())
                    {
                        using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                        {
                            CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                            CryptoStream.FlushFinalBlock();
                            CipherTextBytes = MemStream.ToArray();
                            MemStream.Close();
                            CryptoStream.Close();
                        }
                    }
                }
                SymmetricKey.Clear();
                return(Convert.ToBase64String(CipherTextBytes));
            }
Esempio n. 50
0
        internal void EncryptFile(DirectoryItem fileItem)
        {
            var oldName = fileItem.ItemName + fileItem.ItemExtension;

            if (fileItem.ItemPath != _path + "\\" + _appName && !HasExtension(fileItem.ItemPath, "DC"))
            {
                var fileBytes = File.ReadAllBytes(fileItem.ItemPath);
                var RM        = new RijndaelManaged();
                RM.Mode = CipherMode.CBC;
                var salt      = Encoding.ASCII.GetBytes(saltValue);
                var password  = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
                var encryptor = RM.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));
                using (var ms = new MemoryStream())
                {
                    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        cs.Write(fileBytes, 0, fileBytes.Length);
                        cs.FlushFinalBlock();
                    }
                    File.WriteAllBytes(fileItem.ItemPath + ".DC", ms.ToArray());
                    File.Delete(fileItem.ItemPath);
                }
            }
        }
        /// <summary>
        /// Decrypts the file.
        /// </summary>
        /// <param name="inputFile">The input file.</param>
        /// <returns></returns>
        public static string DecryptFile(string inputFile)
        {
            try
            {
                const string password = @"zxcvbnma";
                var          UE       = new UnicodeEncoding();
                byte[]       key      = UE.GetBytes(password);
                var          fsCrypt  = new FileStream(inputFile, FileMode.Open);
                var          RMCrypto = new RijndaelManaged();
                var          cs       = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read);
                var          reader   = new StreamReader(cs);
                var          read     = reader.ReadToEnd();

                cs.Close();
                fsCrypt.Close();
                return(read);
            }
            catch (Exception)
            {
                MessageBox.Show("Thông tin bản quyền không đúng, vui lòng kiểm tra lại!", "Cảnh báo",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return("");
            }
        }
Esempio n. 52
0
        public static int RijndaelDecryptInplace(ArraySegment <byte> data, byte[] key, byte[] iv)
        {
            using (var rijn = new RijndaelManaged()
            {
                Mode = CipherMode.CBC,
                IV = iv,
                Key = key,
                Padding = PaddingMode.None
            })
            {
                using (var crypt = rijn.CreateDecryptor(rijn.Key, rijn.IV))
                {
                    if (data.Count % crypt.InputBlockSize != 0)
                    {
                        throw new Exception(string.Format("Input data is not a multiple of block size, {0}/{1}", data.Count, crypt.InputBlockSize));
                    }

                    crypt.TransformBlock(data.Array, data.Offset, data.Count, data.Array, data.Offset);

                    int numBlocks = (data.Count + crypt.InputBlockSize - 1) / crypt.InputBlockSize;
                    return(numBlocks * crypt.InputBlockSize);
                }
            }
        }
Esempio n. 53
0
        /// <summary>
        /// Encryption
        /// </summary>
        /// <param name="plainText">The plaintext to encrypt</param>
        /// <returns>The ciphertext</returns>
        public string Encrypt(string plainText)
        {
            byte[] initVectorBytes       = Encoding.ASCII.GetBytes(initVector);
            byte[] saltValueBytes        = Encoding.ASCII.GetBytes(saltValue);
            byte[] plainTextBytes        = Encoding.UTF8.GetBytes(plainText);
            PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, "MD5", 1);

            byte[]          keyBytes     = password.GetBytes(16);
            RijndaelManaged symmetricKey = new RijndaelManaged();

            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform encryptor    = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            MemoryStream     memoryStream = new MemoryStream();
            CryptoStream     cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();
            byte[] cipherTextBytes = memoryStream.ToArray();
            memoryStream.Close();
            cryptoStream.Close();
            string cipherText = Convert.ToBase64String(cipherTextBytes);

            return(cipherText);
        }
Esempio n. 54
0
        /// <summary>
        /// 带Salt解密
        /// </summary>
        /// <param name="strCrypto">带Salt的密文</param>
        /// <param name="strKey">解密密钥</param>
        /// <returns>明文</returns>
        public static string DecryptSalt(string strCrypto, string strKey)
        {
            // 解密
            byte[] byKey          = null;
            byte[] IV             = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
            byte[] inputByteArray = new Byte[strCrypto.Length];

            byKey = System.Text.Encoding.UTF8.GetBytes(strKey.Substring(0, 16));
            RijndaelManaged RMCrypto = new RijndaelManaged();

            inputByteArray = Convert.FromBase64String(strCrypto);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, RMCrypto.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);

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

            byte[] storedSaltCrypto = ms.ToArray();


            // 去除开头Salt
            if (storedSaltCrypto.Length <= SALT_LENGTH)
            {
                return(String.Empty);
            }
            byte[] storedCrypto = new byte[storedSaltCrypto.Length - SALT_LENGTH];
            for (int i = 0; i < storedCrypto.Length; i++)
            {
                storedCrypto[i] = storedSaltCrypto[i + SALT_LENGTH];
            }

            // 返回原文

            System.Text.Encoding encoding = new System.Text.UTF8Encoding();
            return(encoding.GetString(storedCrypto));
        }
Esempio n. 55
0
        /// <summary>
        /// AES decrypt data with a password and salt
        /// </summary>
        /// <param name="input">Data to decrypt</param>
        /// <param name="password">Password</param>
        /// <param name="salt">Salt</param>
        /// <returns>Decrypted data</returns>
        public static byte[] AesDecryption(byte[] input, byte[] password, byte[] salt)
        {
            if (input == null || input.Length == 0 || password == null || password.Length == 0 || salt == null || salt.Length == 0)
            {
                return(null);
            }
            MemoryStream decrypted = new MemoryStream();
            var          AES       = new RijndaelManaged()
            {
                KeySize   = 256,
                BlockSize = 128,
                Padding   = PaddingMode.PKCS7,
            };
            var key = new Rfc2898DeriveBytes(password, salt, 1024);

            AES.Key  = key.GetBytes(AES.KeySize / 8);
            AES.IV   = key.GetBytes(AES.BlockSize / 8);
            AES.Mode = CipherMode.CBC;
            MemoryStream encrypted = new MemoryStream(input);

            byte[] saltMatch = new byte[salt.Length];
            if (encrypted.Read(saltMatch, 0, saltMatch.Length) != salt.Length || !salt.SequenceEqual(saltMatch))
            {
                throw new InvalidOperationException("Invalid salt");
            }
            var cs = new CryptoStream(encrypted, AES.CreateDecryptor(), CryptoStreamMode.Read);

            byte[] buffer = new byte[8192];
            int    count;

            while ((count = cs.Read(buffer, 0, buffer.Length)) > 0)
            {
                decrypted.Write(buffer, 0, count);
            }
            return(decrypted.ToArray());
        }
Esempio n. 56
0
        public RijndaelCryptograph(int keySize, byte[] key, byte[] iv)
        {
            this.CheckKeySize(keySize);
            this.CheckIV(iv);
            this.CheckKey(keySize, key);


            if (key == DEFAULT_KEY || iv == DEFAULT_IV)
            {
                if (log.IsWarnEnabled)
                {
                    log.Warn("Note:Do not use the default Key and IV in the production environment.");
                }
            }

            this.key = key;
            this.iv  = iv;

#if NETFX_CORE
            SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            cryptographicKey = provider.CreateSymmetricKey(this.key.AsBuffer());

            this.algorithmName = string.Format("AES{0}_{1}_{2}", keySize, "CBC", "PKCS7");
#else
            this.rijndael = new RijndaelManaged()
            {
                Mode         = CipherMode.CBC,    //use CBC
                Padding      = PaddingMode.PKCS7, //default PKCS7
                KeySize      = keySize,           //default 256
                BlockSize    = 128,               //default 128
                FeedbackSize = 128                //default 128
            };

            this.algorithmName = string.Format("AES{0}_{1}_{2}", rijndael.KeySize, rijndael.Mode, rijndael.Padding);
#endif
        }
        public string AES_Decrypt(string encrypted, string passkey)
        {
            RijndaelManaged          AES     = new RijndaelManaged();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();

            decryptedString = "";

            try
            {
                byte[] hash = new byte[32];
                byte[] temp = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(passkey));
                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);
                AES.Key  = hash;
                AES.Mode = CipherMode.ECB;
                ICryptoTransform DESdecrypter = AES.CreateDecryptor();
                byte[]           buffer       = Convert.FromBase64String(encrypted);
                decryptedString = ASCIIEncoding.ASCII.GetString
                                      (DESdecrypter.TransformFinalBlock(buffer, 0, buffer.Length));
            }
            catch (Exception e)
            { return(""); }
            return(decryptedString);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="plainText"></param>
        /// <param name="passPhrase"></param>
        /// <param name="salt">The salt is appended to the password as a measure to make dictionary attacks harder. The salt must remain the same for encryption and decryption and be ASCII-encoded.</param>
        /// <param name="initVector">This size of the IV (in bytes) must be (keysize / 8). Default keysize is 256, so the IV must be 32 bytes long. This parameter can be left null in order to use a default IV.</param>
        /// <returns></returns>
        public static string Encrypt(string plainText, string passPhrase, string salt = null, byte[] initVector = null)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                return("");
            }

            if (initVector == null)
            {
                initVector = INIT_VECTOR;
            }

            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] saltValueBytes = string.IsNullOrEmpty(salt) ? null : Encoding.ASCII.GetBytes(salt);
            using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes))
            {
                byte[] keyBytes = password.GetBytes(KEYSIZE / 8);
                using (RijndaelManaged symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.Mode = CipherMode.CBC;
                    using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVector))
                    {
                        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));
                            }
                        }
                    }
                }
            }
        }
Esempio n. 59
0
    /// <summary>
    /// 暗号化処理
    /// </summary>
    public static string Encrypt(string text)
    {
        RijndaelManaged aes = new RijndaelManaged();

        aes.BlockSize = 128;
        aes.KeySize   = 128;
        aes.Padding   = PaddingMode.Zeros;
        aes.Mode      = CipherMode.CBC;
        aes.Key       = System.Text.Encoding.UTF8.GetBytes(sharedKey);
        aes.IV        = System.Text.Encoding.UTF8.GetBytes(initializationVector);

        ICryptoTransform encrypt      = aes.CreateEncryptor();
        MemoryStream     memoryStream = new MemoryStream();
        CryptoStream     cryptStream  = new CryptoStream(memoryStream, encrypt, CryptoStreamMode.Write);

        byte[] text_bytes = System.Text.Encoding.UTF8.GetBytes(text);

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

        byte[] encrypted = memoryStream.ToArray();

        return(System.Convert.ToBase64String(encrypted));
    }
Esempio n. 60
-1
    public static string EncryptRijndael(string original)
    {
        byte[] encrypted;

        byte[] toEncrypt;

        UTF8Encoding utf8Converter = new UTF8Encoding();

        toEncrypt = utf8Converter.GetBytes(original);

        RijndaelManaged myRijndael = new RijndaelManaged();

        MemoryStream ms = new MemoryStream();

        ICryptoTransform encryptor = myRijndael.CreateEncryptor(Key, IV);

        CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);

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

        cs.FlushFinalBlock();

        encrypted = ms.ToArray();

        string encryptedString = Convert.ToBase64String(encrypted);

        return encryptedString;
    }