示例#1
1
文件: Packers.cs 项目: n017/Confuser
    static byte[] Decrypt(byte[] asm)
    {
        byte[] dat;
        byte[] iv;
        byte[] key;
        using (BinaryReader rdr = new BinaryReader(new MemoryStream(asm)))
        {
            dat = rdr.ReadBytes(rdr.ReadInt32());
            iv = rdr.ReadBytes(rdr.ReadInt32());
            key = rdr.ReadBytes(rdr.ReadInt32());
        }
        int key0 = Mutation.Key0I;
        for (int j = 0; j < key.Length; j += 4)
        {
            key[j + 0] ^= (byte)((key0 & 0x000000ff) >> 0);
            key[j + 1] ^= (byte)((key0 & 0x0000ff00) >> 8);
            key[j + 2] ^= (byte)((key0 & 0x00ff0000) >> 16);
            key[j + 3] ^= (byte)((key0 & 0xff000000) >> 24);
        }
        RijndaelManaged rijn = new RijndaelManaged();
        using (var s = new CryptoStream(new MemoryStream(dat), rijn.CreateDecryptor(key, iv), CryptoStreamMode.Read))
        {
            byte[] l = new byte[4];
            s.Read(l, 0, 4);
            uint len = BitConverter.ToUInt32(l, 0);

            LzmaDecoder decoder = new LzmaDecoder();
            byte[] prop = new byte[5];
            s.Read(prop, 0, 5);
            decoder.SetDecoderProperties(prop);
            long outSize = 0;
            for (int i = 0; i < 8; i++)
            {
                int v = s.ReadByte();
                if (v < 0)
                    throw (new Exception("Can't Read 1"));
                outSize |= ((long)(byte)v) << (8 * i);
            }
            byte[] ret = new byte[outSize];
            long compressedSize = len - 13;
            decoder.Code(s, new MemoryStream(ret, true), compressedSize, outSize);

            return ret;
        }
    }
示例#2
1
    protected string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
    {
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
        byte[] keyBytes = password.GetBytes(keySize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
        CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];
        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
        memoryStream.Close();
        cryptoStream.Close();
        string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);

        StringWriter writer = new StringWriter();
        HttpContext.Current.Server.UrlDecode(plainText, writer);

        return writer.ToString();
    }
示例#3
0
文件: Program.cs 项目: LCruel/LCrypt2
        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;
                                }

                        }
                    }
                }
            }
        }
示例#4
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;
    }
    /// <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;
    }
示例#6
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;
    }
 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);
     }
 }
    public static void Main() {
        string PlainText = "Titan";
        byte[] PlainBytes = new byte[5];
        PlainBytes = Encoding.ASCII.GetBytes(PlainText.ToCharArray());
        PrintByteArray(PlainBytes);
        byte[] CipherBytes = new byte[8];
        PasswordDeriveBytes pdb = new PasswordDeriveBytes("Titan", null);
        byte[] IV = new byte[8];
        byte[] Key = pdb.CryptDeriveKey("RC2", "SHA1", 40, IV);
        PrintByteArray(Key);
        PrintByteArray(IV);

        // Now use the data to encrypt something
        RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
        Console.WriteLine(rc2.Padding);
        Console.WriteLine(rc2.Mode);
        ICryptoTransform sse = rc2.CreateEncryptor(Key, IV);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs1 = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs1.Write(PlainBytes, 0, PlainBytes.Length);
        cs1.FlushFinalBlock();
        CipherBytes = ms.ToArray();
        cs1.Close();
        Console.WriteLine(Encoding.ASCII.GetString(CipherBytes));
        PrintByteArray(CipherBytes);

        ICryptoTransform ssd = rc2.CreateDecryptor(Key, IV);
        CryptoStream cs2 = new CryptoStream(new MemoryStream(CipherBytes), ssd, CryptoStreamMode.Read);
        byte[] InitialText = new byte[5];
        cs2.Read(InitialText, 0, 5);
        Console.WriteLine(Encoding.ASCII.GetString(InitialText));
    	PrintByteArray(InitialText);
    }
	private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
	 {
        FileStream fs = new FileStream(inName, FileMode.Open, FileAccess.Read);
        // Create an instance of the Rijndael cipher
        SymmetricAlgorithm aes = Rijndael.Create();
        // set the key to be the derivedKey computed above
        aes.Key = desKey;
        // set the IV to be all zeros
        aes.IV = desIV;  // arrays are zero-initialized
        // now wrap an encryption transform around the filestream
        CryptoStream stream1 = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Read);
        // The result of reading from stream1 is ciphertext, but we want it
        // base64-encoded, so wrap another transform around it
        CryptoStream stream2 = new CryptoStream(stream1, new ToBase64Transform(), CryptoStreamMode.Read);

        FileStream fsout = new FileStream(outName, FileMode.OpenOrCreate);
        byte[] buffer = new byte[1024];
        int bytesRead;
        do {
            bytesRead = stream2.Read(buffer,0,1024);
            fsout.Write(buffer,0,bytesRead);
        } while (bytesRead > 0);
        fsout.Flush();
        fsout.Close();
    }
 /// <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";
         }
 }
示例#11
0
文件: Program.cs 项目: LCruel/LCrypt2
 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";
                     }
                 }
             }
         }
     }
 }
    static Boolean Test(CipherMode md)
    {

        Byte[]  PlainText = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        Byte[]  Key = {1, 1, 1, 1, 1, 1, 1, 1,2,2,2,2,2,2,2,2};
        Byte[]  IV = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115};
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(PlainText);
        
        RijndaelManaged     des = new RijndaelManaged();
        des.Mode = md;
//        des.FeedbackSize = 0;
//		des.Padding = PaddingMode.PKCS7;

        Console.WriteLine("DES default key size = " + des.KeySize);
        ICryptoTransform sse = des.CreateEncryptor(Key, IV);
        Console.WriteLine("SSE mode = " + des.Mode);
        MemoryStream ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(PlainText,0,PlainText.Length);
        cs.FlushFinalBlock();
        byte[] CipherText = ms.ToArray();
        cs.Close();

        Console.WriteLine("Cyphertext:");
        PrintByteArray(CipherText);
        

        Console.WriteLine("Decrypting...");

//        RijndaelManaged     des = new RijndaelManaged();
//        des.Mode = CipherMode.ECB;
//        des.FeedbackSize = 0;
        ICryptoTransform ssd = des.CreateDecryptor(Key, IV);
        Console.WriteLine("SSD mode = " + des.Mode);
        cs = new CryptoStream(new MemoryStream(CipherText), ssd, CryptoStreamMode.Read);

        byte[] NewPlainText = new byte[PlainText.Length];
        cs.Read(NewPlainText,0,PlainText.Length);

        PrintByteArray(NewPlainText);
        
        if (!Compare(PlainText, NewPlainText)) {
        	Console.WriteLine("ERROR: roundtrip failed");
        	return false;
        }
        
        return true;
    }
    static Boolean Test()
    {

        Byte[]  PlainText = {0, 1, 2, 3, 4, 5, 6, 7}; //, 8, 9, 10, 11, 12, 13, 14, 15};
        Byte[]  Key = {1, 1, 1, 1, 1, 1, 1, 2};
        Byte[]  IV = {1, 1, 1, 1, 1, 1, 1, 1};
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(PlainText);
        
        DESCryptoServiceProvider     des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
//        des.FeedbackSize = 0;
		des.Padding = PaddingMode.None;

        Console.WriteLine("DES default key size = " + des.KeySize);
        ICryptoTransform sse = des.CreateEncryptor(Key, IV);
        Console.WriteLine("SSE mode = " + des.Mode);
        MemoryStream ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(PlainText,0,PlainText.Length);
        cs.FlushFinalBlock();
        byte[] CipherText = ms.ToArray();
        cs.Close();

        Console.WriteLine("Cyphertext:");
        PrintByteArray(CipherText);
        

        Console.WriteLine("Decrypting...");

//        DESCryptoServiceProvider     des = new DESCryptoServiceProvider();
//        des.Mode = CipherMode.ECB;
//        des.FeedbackSize = 0;
        ICryptoTransform ssd = des.CreateDecryptor(Key, IV);
        Console.WriteLine("SSD mode = " + des.Mode);
        cs = new CryptoStream(new MemoryStream(CipherText), ssd, CryptoStreamMode.Read);

        byte[] NewPlainText = new byte[8];
        cs.Read(NewPlainText,0,8);

        PrintByteArray(NewPlainText);
        
        if (!Compare(PlainText, NewPlainText)) {
        	Console.WriteLine("ERROR: roundtrip failed");
        	return false;
        }
        
        return true;
    }
示例#14
0
    public static string Decrypt(string encryptedText)
    {
        byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
        byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

        var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
        var memoryStream = new MemoryStream(cipherTextBytes);
        var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];

        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
        memoryStream.Close();
        cryptoStream.Close();
        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
    }
示例#15
0
 public string Decrypt(string cipherText, string passPhrase)
 {
     byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
     byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
     PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
     byte[] keyBytes = password.GetBytes(keysize / 8);
     RijndaelManaged symmetricKey = new RijndaelManaged();
     symmetricKey.Mode = CipherMode.CBC;
     ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
     MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
     CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
     byte[] plainTextBytes = new byte[cipherTextBytes.Length];
     int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
     memoryStream.Close();
     cryptoStream.Close();
     return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
 }
示例#16
0
文件: AES.cs 项目: ylyking/ABXTool
 /// <summary>
 /// AES解密
 /// </summary>
 /// <param name="cipherText">密文字符串</param>
 /// <returns>返回解密后的明文字符串</returns>
 public static byte[] AESDecrypt(byte[] showText)
 {
     byte[] cipherText = showText;
         SymmetricAlgorithm des = Rijndael.Create();
         des.Key = Encoding.UTF8.GetBytes(Key);
         des.IV = _key1;
         byte[] decryptBytes = new byte[cipherText.Length];
         using (MemoryStream ms = new MemoryStream(cipherText))
         {
             using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
             {
                 cs.Read(decryptBytes, 0, decryptBytes.Length);
                 cs.Close();
                 ms.Close();
             }
         }
         return decryptBytes;  ///将字符串后尾的'\0'去掉
 }
示例#17
0
    /// 
    /// Decrypts a previously encrypted string.
    /// 
    /// The encrypted string to decrypt.
    /// A decrypted string.
    public static string Decrypt(string inputText)
    {
        RijndaelManaged rijndaelCipher = new RijndaelManaged();
        byte[] encryptedData = Convert.FromBase64String(inputText);

        using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(key, iv))
        {
            using (MemoryStream memoryStream = new MemoryStream(encryptedData))
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                {
                    byte[] plainText = new byte[encryptedData.Length];
                    int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                    return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
                }
            }
        }
    }
示例#18
0
文件: Crypto.cs 项目: JJJohan/RTS
    public void DecryptFile(string a_inputFile, string a_outputFile, string a_key)
    {
        ICryptoTransform decryptor = InitDecrypt(a_key);

        FileStream inputFileStream = new FileStream(a_inputFile, FileMode.Open, FileAccess.Read);
        CryptoStream decryptStream = new CryptoStream(inputFileStream, decryptor, CryptoStreamMode.Read);

        byte[] inputFileData = new byte[(int)inputFileStream.Length];
        int decrypt_length = decryptStream.Read(inputFileData, 0, (int)inputFileStream.Length);

        FileStream outputFileStream = new FileStream(a_outputFile, FileMode.Create, FileAccess.Write);
        outputFileStream.Write(inputFileData, 0, decrypt_length);
        outputFileStream.Flush();

        decryptStream.Close();
        inputFileStream.Close();
        outputFileStream.Close();
    }
示例#19
0
文件: Crypto.cs 项目: JJJohan/RTS
    public MemoryStream DecryptFileToStream(string a_inputFile, string a_key)
    {
        ICryptoTransform decryptor = InitDecrypt(a_key);

        FileStream inputFileStream = new FileStream(a_inputFile, FileMode.Open, FileAccess.Read);
        CryptoStream decryptStream = new CryptoStream(inputFileStream, decryptor, CryptoStreamMode.Read);

        byte[] inputFileData = new byte[(int)inputFileStream.Length];
        int decrypt_length = decryptStream.Read(inputFileData, 0, (int)inputFileStream.Length);

        MemoryStream output = new MemoryStream();
        output.Write(inputFileData, 0, decrypt_length);
        output.Seek(0, SeekOrigin.Begin);

        decryptStream.Close();
        inputFileStream.Close();

        return output;
    }
示例#20
0
        private void VerifyICryptoTransformStream(Stream input, string output)
        {
            byte[] expected = ByteUtils.HexToByteArray(output);
            byte[] actual;

            using (HashAlgorithm hash = Create())
            using (CryptoStream cryptoStream = new CryptoStream(input, hash, CryptoStreamMode.Read))
            {
                byte[] buffer = new byte[1024]; // A different default than HashAlgorithm which uses 4K
                int bytesRead;
                while ((bytesRead = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    // CryptoStream will build up the hash
                }

                actual = hash.Hash;
            }

            Assert.Equal(expected, actual);
        }
    static Boolean Test(Aes aes)
    {

        Byte[]  PlainText = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        Byte[]  Key = {1, 1, 1, 1, 1, 1, 1, 1,2,2,2,2,2,2,2,2};
        Byte[]  IV = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115};
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(PlainText);
        
        Console.WriteLine("AES default key size = " + aes.KeySize);
        ICryptoTransform sse = aes.CreateEncryptor(Key, IV);
         MemoryStream ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(PlainText,0,PlainText.Length);
        cs.FlushFinalBlock();
        byte[] CipherText = ms.ToArray();
        cs.Close();

        Console.WriteLine("Cyphertext:");
        PrintByteArray(CipherText);
        

        Console.WriteLine("Decrypting...");

        ICryptoTransform ssd = aes.CreateDecryptor(Key, IV);
        cs = new CryptoStream(new MemoryStream(CipherText), ssd, CryptoStreamMode.Read);

        byte[] NewPlainText = new byte[PlainText.Length];
        cs.Read(NewPlainText,0,PlainText.Length);

        PrintByteArray(NewPlainText);
        
        if (!Compare(PlainText, NewPlainText)) {
        	Console.WriteLine("ERROR: roundtrip failed");
        	return false;
        }
        
        return true;
    }
示例#22
0
	public static byte[] Decrypt(byte[] encryptedBytes, byte[] Key,byte[] IV)  
	{  

		// Create an RijndaelManaged object
		// with the specified key and IV.
		byte[] original = null;

		using (RijndaelManaged rijAlg = new RijndaelManaged())
		{
			rijAlg.Key = Key;
			rijAlg.IV = IV;
			
			// Create a decrytor to perform the stream transform.
			ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
			
			// Create the streams used for decryption.
			using (MemoryStream msDecrypt = new MemoryStream(encryptedBytes))
			{
				using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
				{
					using (MemoryStream originalMemory = new MemoryStream())
					{
						byte[] Buffer = new byte[1024];
						int readBytes = 0;
						while ((readBytes = csDecrypt.Read(Buffer, 0, Buffer.Length)) > 0)
						{
							originalMemory.Write(Buffer, 0, readBytes);
						}
						
						original = originalMemory.ToArray();
					}
				}
			}
			
		}

			return original;

	}  
    public static string DESDecrypt(string Text, string sKey)
    {
        byte[] bufferEncrypted = ASCIIEncoding.ASCII.GetBytes(Text);
        MemoryStream StreamEncrypted = new MemoryStream(bufferEncrypted);

        DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
        ICryptoTransform desdecrypt = DES.CreateDecryptor();

        CryptoStream cryptostreamDecr = new CryptoStream(StreamEncrypted,
            desdecrypt,
            CryptoStreamMode.Read);
        byte[] tors = new byte[StreamEncrypted.Length];
        cryptostreamDecr.Read(tors, 0, tors.Length);
        //			StreamReader sreader = new StreamReader(cryptostreamDecr);
        //			string rs = sreader.ReadToEnd();
        cryptostreamDecr.Close();
        StreamEncrypted.Close();
        //sreader.Close();
        ASCIIEncoding ByteConverter = new ASCIIEncoding();
        return ByteConverter.GetString(tors);
        //return rs;
    }
示例#24
0
	private static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV)
	 {
        FileStream fs = new FileStream(inName, FileMode.Open, FileAccess.Read);
        // Create an instance of the Rijndael cipher
        SymmetricAlgorithm aes = Rijndael.Create();
        // set the key to be the derivedKey computed above
        aes.Key = desKey;
        // set the IV to be all zeros
        aes.IV = desIV;  // arrays are zero-initialized
        // Base64-decode the ciphertext
        CryptoStream stream1 = new CryptoStream(fs, new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces), CryptoStreamMode.Read);
        // now wrap a decryption transform around stream1
        CryptoStream stream2 = new CryptoStream(stream1, aes.CreateDecryptor(), CryptoStreamMode.Read);
        FileStream fsout = new FileStream(outName, FileMode.OpenOrCreate);
        byte[] buffer = new byte[1024];
        int bytesRead;
        UTF8Encoding utf8 = new UTF8Encoding();
        do {
            bytesRead = stream2.Read(buffer,0,1024);
            fsout.Write(buffer,0,bytesRead);
        } while (bytesRead > 0);
        fsout.Flush();
        fsout.Close();
    }
示例#25
0
        public void TestRealDecrytp()
        {
            // YFtS5MGIU/UQ2w2n3RdqMoBcHOzqEQqISOyKD+W9Prk=

            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.BlockSize    = 128;
                rijAlg.Padding      = PaddingMode.None;
                rijAlg.Mode         = CipherMode.CFB;
                rijAlg.FeedbackSize = 8;

                rijAlg.Key = Base64Url.Decode("Tv9JFj4vhftDXgcjpNWNocWZrVKaVpF+icEh51M8MvI=");
                rijAlg.IV  = rijAlg.Key.Take(16).ToArray();

                Assert.AreEqual(rijAlg.Key.Take(16).ToArray(), rijAlg.IV);

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

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream())
                {
                    byte[] buffer1 = SoapHexBinary.Parse("172e0592aba239d86b7ca2384cfad4e4fa5b883ff6db73931ecd").Value;
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        msDecrypt.Write(buffer1, 0, buffer1.Length);
                        msDecrypt.Position = 0;
                        byte[] checksum;
                        byte[] clearBytes;
                        using (var clearBuffer = new MemoryStream())
                        {
                            var buffer = new byte[1024];
                            var read   = csDecrypt.Read(buffer, 0, buffer.Length);
                            while (read > 0)
                            {
                                clearBuffer.Write(buffer, 0, read);
                                read = csDecrypt.Read(buffer, 0, buffer.Length);
                            }
                            csDecrypt.Flush();

                            var fullResult = clearBuffer.ToArray();
                            clearBytes = (byte[])fullResult.Take(fullResult.Length - 8).ToArray();
                            checksum   = fullResult.Skip(fullResult.Length - 8).ToArray();
                        }

                        Assert.AreEqual(6, clearBytes[0]);

                        Package message = PackageFactory.CreatePackage(clearBytes[0], clearBytes, "mcpe");
                        Assert.NotNull(message);
                        Assert.AreEqual(typeof(McpeBatch), message.GetType());

                        List <Package> messages           = HandleBatch((McpeBatch)message);
                        McpeClientToServerHandshake magic = (McpeClientToServerHandshake)messages.FirstOrDefault();
                        Assert.AreEqual(typeof(McpeClientToServerHandshake), magic?.GetType());

                        //Hashing - Checksum - Validation
                        MemoryStream hashStream = new MemoryStream();
                        Assert.True(BitConverter.IsLittleEndian);
                        hashStream.Write(BitConverter.GetBytes(0L), 0, 8);
                        hashStream.Write(clearBytes, 0, clearBytes.Length);
                        hashStream.Write(rijAlg.Key, 0, rijAlg.Key.Length);
                        SHA256Managed crypt              = new SHA256Managed();
                        var           hashBuffer         = hashStream.ToArray();
                        byte[]        validationCheckSum = crypt.ComputeHash(hashBuffer, 0, hashBuffer.Length).Take(8).ToArray();
                        Assert.AreEqual(checksum, validationCheckSum);
                    }
                }
            }
        }
示例#26
0
        /// <summary>
        /// takes an input Stream and decrypts it to the output Stream
        /// </summary>
        /// <param name="fin">the Stream to decrypt</param>
        /// <param name="fout">the Stream to write the decrypted data to</param>
        /// <param name="password">the password used as the key</param>
        /// <param name="callback">the method to call to notify of progress</param>
        public static void DecryptStream(Stream fin, Stream fout, string password, CryptoProgressCallBack callback)
        {
            // NOTE:  The encrypting algo was so much easier...

            // create and open the file streams
            int size = (int)fin.Length;              // the size of the file for progress notification

            byte[] bytes    = new byte[BUFFER_SIZE]; // byte buffer
            int    read     = -1;                    // the amount of bytes read from the stream
            int    value    = 0;
            int    outValue = 0;                     // the amount of bytes written out

            // read off the IV and Salt
            byte[] IV = new byte[16];
            fin.Read(IV, 0, 16);
            byte[] salt = new byte[16];
            fin.Read(salt, 0, 16);

            // create the crypting stream
            SymmetricAlgorithm sma = CreateRijndael(password, salt);

            sma.IV = IV;

            value = 32;      // the value for the progress
            long lSize = -1; // the size stored in the input stream

            // create the hashing object, so that we can verify the file
            HashAlgorithm hasher = SHA256.Create();

            // create the cryptostreams that will process the file
            using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
                   chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write)) {
                // read size from file
                BinaryReader br = new BinaryReader(cin);
                lSize = br.ReadInt64();
                ulong tag = br.ReadUInt64();

                if (FC_TAG != tag)
                {
                    throw new CryptoHelpException("File Corrupted!");
                }

                //determine number of reads to process on the file
                long numReads = lSize / BUFFER_SIZE;

                // determine what is left of the file, after numReads
                long slack = (long)lSize % BUFFER_SIZE;

                // read the buffer_sized chunks
                for (int i = 0; i < numReads; ++i)
                {
                    read = cin.Read(bytes, 0, bytes.Length);
                    fout.Write(bytes, 0, read);
                    chash.Write(bytes, 0, read);
                    value    += read;
                    outValue += read;
                    callback(0, size, value);
                }

                // now read the slack
                if (slack > 0)
                {
                    read = cin.Read(bytes, 0, (int)slack);
                    fout.Write(bytes, 0, read);
                    chash.Write(bytes, 0, read);
                    value    += read;
                    outValue += read;
                    callback(0, size, value);
                }
                // flush and close the hashing stream
                chash.Flush();
                chash.Close();

                // flush and close the output file
                fout.Flush();
                fout.Close();

                // read the current hash value
                byte[] curHash = hasher.Hash;

                // get and compare the current and old hash values
                byte[] oldHash = new byte[hasher.HashSize / 8];
                read = cin.Read(oldHash, 0, oldHash.Length);
                if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash)))
                {
                    throw new CryptoHelpException("File Corrupted!");
                }
            }

            // make sure the written and stored size are equal
            if (outValue != lSize)
            {
                throw new CryptoHelpException("File Sizes don't match!");
            }
        }
示例#27
0
        /// <summary>
        /// AES 解密
        /// </summary>
        /// <param name="data">需要解密的数据</param>
        /// <param name="key">密钥</param>
        /// <param name="vector">向量</param>
        /// <returns></returns>
        public static string AESDecrypt(string data, string key, string vector)
        {
            MemoryStream memoryStream   = null;
            MemoryStream originalMemory = null;
            CryptoStream cryptoStream   = null;
            Rijndael     rijndael       = null;

            try
            {
                Byte[] encryptedBytes = Convert.FromBase64String(data);

                Byte[] byteKeys = new Byte[32];
                Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(byteKeys.Length)), byteKeys, byteKeys.Length);
                Byte[] byteVectors = new Byte[16];
                Array.Copy(Encoding.UTF8.GetBytes(vector.PadRight(byteVectors.Length)), byteVectors, byteVectors.Length);

                Byte[] original = null;

                rijndael = Rijndael.Create();
                using (memoryStream = new MemoryStream(encryptedBytes))
                {
                    using (cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(byteKeys, byteVectors), CryptoStreamMode.Read))
                    {
                        using (originalMemory = new MemoryStream())
                        {
                            Byte[] Buffer    = new Byte[1024];
                            Int32  readBytes = 0;
                            while ((readBytes = cryptoStream.Read(Buffer, 0, Buffer.Length)) > 0)
                            {
                                originalMemory.Write(Buffer, 0, readBytes);
                            }
                            original = originalMemory.ToArray();
                        }
                    }
                }
                return(Encoding.UTF8.GetString(original));
            }
            catch
            {
                throw;
            }
            finally
            {
                if (originalMemory != null)
                {
                    originalMemory.Close();
                }
                if (cryptoStream != null)
                {
                    cryptoStream.Close();
                }
                if (memoryStream != null)
                {
                    memoryStream.Close();
                }
                if (rijndael != null)
                {
                    rijndael.Clear();
                }
            }
        }
示例#28
0
        private static string DecryptFile(string inFile, string password)
        {
            using (FileStream fin = File.OpenRead(inFile))
            {
                MemoryStream content  = new MemoryStream();
                byte[]       bytes    = new byte[BUFFER_SIZE];
                int          read     = -1;
                int          outValue = 0;

                // read off the IV and Salt
                byte[] IV = new byte[16];
                fin.Read(IV, 0, 16);
                byte[] salt = new byte[16];
                fin.Read(salt, 0, 16);

                SymmetricAlgorithm sma = CreateRijndael(password, salt);
                sma.IV = IV;

                long lSize = -1;

                HashAlgorithm hasher = SHA256.Create();

                using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
                       chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
                {
                    BinaryReader br = new BinaryReader(cin);
                    lSize = br.ReadInt64();
                    ulong tag = br.ReadUInt64();

                    if (FC_TAG != tag)
                    {
                        throw new Exception("File Corrupted!");
                    }

                    long numReads = lSize / BUFFER_SIZE;

                    long slack = (long)lSize % BUFFER_SIZE;

                    for (int i = 0; i < numReads; ++i)
                    {
                        read = cin.Read(bytes, 0, bytes.Length);
                        content.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        outValue += read;
                    }

                    if (slack > 0)
                    {
                        read = cin.Read(bytes, 0, (int)slack);
                        content.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        outValue += read;
                    }

                    chash.Flush();
                    chash.Close();
                    content.Flush();

                    byte[] curHash = hasher.Hash;

                    byte[] oldHash = new byte[hasher.HashSize / 8];
                    read = cin.Read(oldHash, 0, oldHash.Length);
                    if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash)))
                    {
                        throw new Exception("File Corrupted!");
                    }
                }

                if (outValue != lSize)
                {
                    throw new Exception("File Sizes don't match!");
                }

                content.Position = 0;
                StreamReader reader = new StreamReader(content);
                return(reader.ReadToEnd());
            }
        }
示例#29
0
        /// <summary>
        /// Decrypt a text using the RijndaelCipher algorithm.
        /// </summary>
        /// <param name="InputText">the plain text</param>
        /// <param name="Password">the encryption key</param>
        /// <returns></returns>
        public static string DecryptString(string inputText, string password)
        {
            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(32), SecretKey.GetBytes(16));



            MemoryStream memoryStream = new MemoryStream(EncryptedData);



            // Create a CryptoStream. (always use Read mode for decryption).

            CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);



            // Since at this point we don't know what the size of decrypted data

            // will be, allocate the buffer long enough to hold EncryptedData;

            // DecryptedData is never longer than EncryptedData.

            byte[] PlainText = new byte[EncryptedData.Length];



            // Start decrypting.

            int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);



            memoryStream.Close();

            cryptoStream.Close();



            // Convert decrypted data into a string.

            string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);



            // Return decrypted string.

            return(DecryptedData);
        }
示例#30
0
        /// <summary>
        /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
        /// </summary>
        /// <param name="cipherText">
        /// Base64-formatted ciphertext value.
        /// </param>
        /// <returns>
        /// Decrypted string value.
        /// </returns>
        /// <remarks>
        /// Most of the logic in this function is similar to the Encrypt
        /// logic. In order for decryption to work, all parameters of this function
        /// - except cipherText value - must match the corresponding parameters of
        /// the Encrypt function which was called to generate the
        /// ciphertext.
        /// </remarks>
        public static string Descriptografar(string cipherText)
        {
            if (ConfigurationManager.AppSettings["CriptografiaEntrePaginas"] == "false" ||
                string.IsNullOrEmpty(cipherText))
            {
                return(cipherText);
            }

            const string PASS_PHRASE         = PHRASE;   // can be any string
            const string SALT_VALUE          = S_TVALUE; // can be any string
            const string HASH_ALGORITHM      = "SHA1";   // can be "MD5"
            const int    PASSWORD_ITERATIONS = 2;        // can be any number
            const int    KEY_SIZE            = 256;      // can be 192 or 128
            const string INIT_VECTOR         = VECTOR;   // must be 16 bytes

            // Convert strings defining encryption key characteristics into byte
            // arrays. Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(INIT_VECTOR);
            byte[] saltValueBytes  = Encoding.ASCII.GetBytes(SALT_VALUE);

            // Convert our ciphertext into a byte array.
            //byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            byte[] cipherTextBytes = DescriptografarDeHexadecimal(cipherText);

            // First, we must create a password, from which the key will be
            // derived. This password will be generated from the specified
            // passphrase and salt value. The password will be created using
            // the specified hash algorithm. Password creation can be done in
            // several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                PASS_PHRASE,
                saltValueBytes,
                HASH_ALGORITHM,
                PASSWORD_ITERATIONS);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(KEY_SIZE / 8);

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

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate decryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                keyBytes,
                initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

            // Define cryptographic stream (always use Read mode for encryption).
            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 ciphertext;
            // plaintext is never longer than ciphertext.
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            // Start decrypting.
            int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                       0,
                                                       plainTextBytes.Length);

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert decrypted data into a string.
            // Let us assume that the original plaintext string was UTF8-encoded.
            string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                       0,
                                                       decryptedByteCount);

            // Return decrypted string.
            return(plainText);
        }
示例#31
0
        public void AES_Decrypt(string originFile, string whereToSave, string logedUser, string aPanDoKogo)
        {
            FileStream fsCrypt = new FileStream(originFile, FileMode.Open);

            //odczytaj rozmiar naglowka
            byte[] stringLenghtAsBytes = new byte[4];
            fsCrypt.Read(stringLenghtAsBytes, 0, stringLenghtAsBytes.Length);
            string result       = System.Text.Encoding.ASCII.GetString(stringLenghtAsBytes);
            int    paresdResult = Int32.Parse(result);

            //odczytaj naglowek
            byte[] stringAsBytes = new byte[paresdResult];
            fsCrypt.Read(stringAsBytes, 0, stringAsBytes.Length);
            string header = System.Text.Encoding.ASCII.GetString(stringAsBytes);

            string[] headerArray;
            //headerArray = header.Split('|');
            headerArray = header.Split(new string[] { "|||" }, StringSplitOptions.None);
            //na podstawie pozycji w nagłówku uzupełnij pola sprawdz HeaderToString() żeby wiedzieć co gdzie leży
            string keySize = headerArray[4];
            string mode    = headerArray[8];

            string IVString = headerArray[10];

            byte[] IV = System.Text.Encoding.ASCII.GetBytes(IVString);
            //11 ApprovedUsers 12User 13username 14SessionKey 15paswd 16 User2 17 username2 18Sessionkey
            string password = "";
            int    i        = 13;

            //sprawdz czy znajduje się na liście odbiorców
            while (!headerArray[i].Equals("Done"))
            {
                if (headerArray[i].Equals(logedUser))
                {
                    string pathToPass = @"..\..\UsersFiles\" + logedUser + @"\paswd.txt";
                    string userpass   = "";
                    using (StreamReader sr = File.OpenText(pathToPass))
                    {
                        userpass = sr.ReadLine();
                    }
                    string dirpathPriv   = @"..\..\UsersFiles\" + logedUser + @"\PRIV\PRIV.txt";
                    string resultPrivRSA = RSAHandle.DecryptPrivate(userpass, dirpathPriv);
                    password = RSAHandle.DecryptMessage(resultPrivRSA, headerArray[i + 2]);
                    break;
                }

                i += 4;
            }
            // sprawdź czy wybraliśmy siebie jako odbiorcę
            if (!logedUser.Equals(aPanDoKogo))
            {
                password = "******";
            }

            //password = UTF8toASCII(password);
            //odczytaj sol
            byte[] salt = new byte[32];
            fsCrypt.Read(salt, 0, salt.Length);
            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            //password bytes form string password
            byte[] passwordBytes = System.Text.Encoding.ASCII.GetBytes(password);

            using (RijndaelManaged AES = new RijndaelManaged())
            {
                if (keySize.Contains("128"))
                {
                    AES.KeySize = 128;
                }
                if (keySize.Contains("192"))
                {
                    AES.KeySize = 192;
                }
                if (keySize.Contains("256"))
                {
                    AES.KeySize = 256;
                }
                AES.BlockSize = 128;
                AES.Padding   = PaddingMode.PKCS7;

                var key = new Rfc2898DeriveBytes(passwordBytes, salt, 10000);
                AES.Key = key.GetBytes(AES.KeySize / 8);
                AES.IV  = IV;
                if (mode.Contains("CBC"))
                {
                    AES.Mode = CipherMode.CBC;
                }
                if (mode.Contains("ECB"))
                {
                    AES.Mode = CipherMode.ECB;
                }
                if (mode.Contains("CFB"))
                {
                    AES.Mode = CipherMode.CFB;
                }
                if (mode.Contains("OFB"))
                {
                    AES.Mode = CipherMode.OFB;
                }


                CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read);

                FileStream fsOut = new FileStream(whereToSave, FileMode.Create);

                int    read;
                byte[] buffer = new byte[1048576];
                try
                {
                    var mainWin = Application.Current.Windows.Cast <Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;

                    mainWin.ProBar.Minimum = 0;
                    mainWin.ProBar.Maximum = new System.IO.FileInfo(originFile).Length;
                    mainWin.ProBar.Dispatcher.Invoke(() => mainWin.ProBar.Value = 0, DispatcherPriority.Background);
                    double proggres = 0;
                    while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fsOut.Write(buffer, 0, read);
                        proggres += read;
                        mainWin.ProBar.Dispatcher.Invoke(() => mainWin.ProBar.Value = proggres, DispatcherPriority.Background);
                    }
                    mainWin.ProBar.Dispatcher.Invoke(() => mainWin.ProBar.Value = mainWin.ProBar.Maximum, DispatcherPriority.Background);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Szyfracja nie wyszła " + ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                }

                finally
                {
                    cs.Close();
                    fsOut.Close();
                    fsCrypt.Close();
                }
            }
        }
        public static byte[] DecryptBytes(
            byte[] value,
            SecureString password,
            SecureString salt,
            SecureString passwordIterations,
            SecureString initialVector,
            SecureString keySize)
        {
            try
            {
                if (value == null || value.Length == 0)
                {
                    return(value);
                }

                byte[] saltBytes          = null;
                byte[] initialVectorBytes = null;
                byte[] derivedBytes       = null;
                byte[] valueBytes         = null;

                try
                {
                    saltBytes          = Encoding.ASCII.GetBytes(salt.ToUnsecureString());
                    initialVectorBytes = Encoding.ASCII.GetBytes(initialVector.ToUnsecureString());
                    valueBytes         = Convert.FromBase64String(Encoding.ASCII.GetString(value));
                    var buffer = new byte[valueBytes.Length];
                    using (var rfcDeriveBytes = new Rfc2898DeriveBytes(password.ToUnsecureString(), saltBytes, Convert.ToInt32(passwordIterations.ToUnsecureString())))
                        using (var rijndaelManaged = new RijndaelManaged {
                            Mode = CipherMode.CBC
                        })
                        {
                            derivedBytes = rfcDeriveBytes.GetBytes(Convert.ToInt32(keySize.ToUnsecureString()) / 8);
                            using (var decryptor = rijndaelManaged.CreateDecryptor(derivedBytes, initialVectorBytes))
                                using (var memoryStream = new MemoryStream(valueBytes))
                                    using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                                    {
                                        var count = cryptoStream.Read(buffer, 0, buffer.Length);
                                        memoryStream.Close();
                                        cryptoStream.Close();
                                        rijndaelManaged.Clear();

                                        Array.Resize(ref buffer, count);
                                        return(buffer);
                                    }
                        }
                }
                finally
                {
                    if (valueBytes != null)
                    {
                        Array.Clear(valueBytes, 0, valueBytes.Length);
                    }
                    if (saltBytes != null)
                    {
                        Array.Clear(saltBytes, 0, saltBytes.Length);
                    }
                    if (initialVectorBytes != null)
                    {
                        Array.Clear(initialVectorBytes, 0, initialVectorBytes.Length);
                    }
                    if (derivedBytes != null)
                    {
                        Array.Clear(derivedBytes, 0, derivedBytes.Length);
                    }
                }
            }
            finally
            {
                SecureStringCleanup(password, salt, passwordIterations, initialVector, keySize);
            }
        }
        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            try
            {
                /////////////////////////////////////////////////////////////////
                // Create a cryptographic provider object used to decrypt data
                //

                SymmetricAlgorithm sa = GetSymmetricAlgorithmProvider();
                // Sets the secret key
                sa.Key = key;
                // Sets the IV
                sa.IV = initVector;
                // Sets the mode
                sa.Mode = cipherMode;
                // Sets the padding mode
                sa.Padding = paddingMode;

                /////////////////////////////////////////////////////////////////
                // Decrypt ciphered data to get plain text
                //

                byte[] plainbytes;
                // Defines a stream object to contain the decrypted data
                using (MemoryStream ms = new MemoryStream(cipherBytes))
                {
                    // Defines a stream for cryptographic transformations
                    using (CryptoStream cs = new CryptoStream(ms, sa.CreateDecryptor(),
                                                              CryptoStreamMode.Read))
                    {
                        // Defines one byte array for recovered plaintext
                        plainbytes = new byte[cipherBytes.Length];
                        // Reads a sequence of bytes for decryption
                        cs.Read(plainbytes, 0, cipherBytes.Length);
                    }
                }

                /////////////////////////////////////////////////////////////////
                // Deserialize data to get message object and display it in UI
                //

                Message recoveredMessage;
                using (MemoryStream stream = new MemoryStream(plainbytes, false))
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    recoveredMessage = (Message)bf.Deserialize(stream);
                }

                // Display the recovered message in textbox control
                this.tbxIntegerPart.Text = recoveredMessage.Num.ToString();
                this.tbxMessagePart.Text = recoveredMessage.MessageBody;

                // Update UI
                comboboxMode.Enabled           = true;
                comboboxPadding.Enabled        = true;
                btnNewRandomInitVector.Enabled = true;
                btnNewRandomKey.Enabled        = true;
                radiobtnDES.Enabled            = true;
                radiobtnTrippleDES.Enabled     = true;
                radiobtnRC2.Enabled            = true;
                radiobtnRijndael.Enabled       = true;
                btnEncrypt.Enabled             = true;
                btnDecrypt.Enabled             = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public string CipherText(string objText, string convertTool)
        {
            string passPhrase = "Rajeev Biswas";
            string saltValue  = "Vipin Gera";
            string initVector = "Infocept Pty Ltd.";
            string cipherText;

            if (convertTool == "E")
            {
                int    keySize            = 256;
                int    passwordIterations = 03;
                string hashAlgorithm      = "MD5";
                byte[] initVectorBytes    = Encoding.ASCII.GetBytes(initVector);
                byte[] saltValueBytes     = Encoding.ASCII.GetBytes(saltValue);
                byte[] plainTextBytes     = Encoding.UTF8.GetBytes(objText);

                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();
                cipherText = Convert.ToBase64String(cipherTextBytes);
                cipherText = HttpUtility.UrlEncode(cipherText);
            }
            else
            {
                int    keySize            = 256;
                int    passwordIterations = 03;
                string hashAlgorithm      = "MD5";
                try
                {
                    cipherText = HttpUtility.UrlDecode(objText);
                    byte[] initVectorBytes       = Encoding.ASCII.GetBytes(initVector);
                    byte[] saltValueBytes        = Encoding.ASCII.GetBytes(saltValue);
                    byte[] cipherTextBytes       = Convert.FromBase64String(cipherText);
                    PasswordDeriveBytes password = new PasswordDeriveBytes
                                                   (
                        passPhrase,
                        saltValueBytes,
                        hashAlgorithm,
                        passwordIterations
                                                   );
                    byte[]          keyBytes     = password.GetBytes(keySize / 8);
                    RijndaelManaged symmetricKey = new RijndaelManaged();
                    symmetricKey.Mode = CipherMode.CBC;
                    ICryptoTransform decryptor = symmetricKey.CreateDecryptor
                                                 (
                        keyBytes,
                        initVectorBytes
                                                 );
                    MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
                    CryptoStream cryptoStream = new CryptoStream
                                                (
                        memoryStream,
                        decryptor,
                        CryptoStreamMode.Read
                                                );
                    byte[] plainTextBytes     = new byte[cipherTextBytes.Length];
                    int    decryptedByteCount = cryptoStream.Read
                                                (
                        plainTextBytes,
                        0,
                        plainTextBytes.Length
                                                );
                    memoryStream.Close();
                    cryptoStream.Close();
                    cipherText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                }
                catch (Exception ex)
                {
                    cipherText = "";
                }
            }
            return(cipherText);
        }
示例#35
0
        private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
            //make sure device is in configured range
            if (eventArgs.RawSignalStrengthInDBm > rssi)
            {
                long secondsFromEpoch = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

                try
                {
                    var advertisementData = new byte[eventArgs.Advertisement.DataSections.ElementAt(2).Data.Length];
                    using (var reader = DataReader.FromBuffer(eventArgs.Advertisement.DataSections.ElementAt(2).Data))
                    {
                        reader.ReadBytes(advertisementData);
                    }


                    int    NumberChars = aesKey.Length;
                    byte[] btkey       = new byte[NumberChars / 2];
                    for (int i = 0; i < NumberChars; i += 2)
                    {
                        btkey[i / 2] = Convert.ToByte(aesKey.Substring(i, 2), 16);
                    }

                    RijndaelManaged aes128 = new RijndaelManaged();
                    aes128.Mode    = CipherMode.ECB;
                    aes128.Padding = PaddingMode.PKCS7;
                    ICryptoTransform decryptor = aes128.CreateDecryptor(btkey, null);



                    Console.WriteLine(BitConverter.ToString(advertisementData));
                    //first two bytes of data should be ignored
                    MemoryStream ms            = new MemoryStream(advertisementData, 2, advertisementData.Length - 2);
                    CryptoStream cs            = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
                    byte[]       decryptedData = new byte[advertisementData.Length - 2];



                    int decryptCount = cs.Read(decryptedData, 0, decryptedData.Length);
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(decryptedData);
                    }

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

                    //return plaintext in String
                    //string timeString = Encoding.UTF8.GetString(decryptedDateTimestamp, 0, decryptCount);

                    long decryptedTimeStamp = BitConverter.ToInt64(decryptedData, 8);
                    long timeDif            = (secondsFromEpoch - decryptedTimeStamp);
                    //Console.WriteLine(secondsFromEpoch);
                    //char[] delimiterChars = { '-', ' ', ':' };

                    //string[] timeValues = (timeString.Split(delimiterChars));
                    //DateTime curDateTime = DateTime.Now;
                    //DateTime authDateTimeStamp = new DateTime(curDateTime.Year, Int32.Parse(timeValues[0]), Int32.Parse(timeValues[1]), Int32.Parse(timeValues[2]), Int32.Parse(timeValues[3]), Int32.Parse(timeValues[4]));

                    //Compare current date and time to decrypted auth message
                    // double secondsFromAuthDateTimeStamp = (curDateTime - authDateTimeStamp).TotalSeconds;
                    //Console.WriteLine(authDateTimeStamp);
                    //Console.WriteLine(curDateTime);

                    if (timeDif >= 0 && timeDif < 60)
                    {
                        MainPage.resetTimer();
                    }
                }
                catch
                {
                }
            }
        }
示例#36
0
    public bool TransformFile(string sInFile, string sOutFile, [System.Runtime.InteropServices.OptionalAttribute, System.Runtime.InteropServices.DefaultParameterValueAttribute(true)]      // ERROR: Optional parameters aren't supported in C#
                              bool encrypt)
    {
        //make sure that all the initialisation has been completed:
        if (!bInitialised)
        {
            if (Finished != null)
            {
                Finished(ReturnType.Badly);
            }
            return(false);
        }
        if (!IO.File.Exists(sInFile))
        {
            if (Finished != null)
            {
                Finished(ReturnType.Badly);
            }
            return(false);
        }

        FileStream   fsIn      = null;
        FileStream   fsOut     = null;
        CryptoStream encStream = null;
        ReturnType   retVal    = ReturnType.Badly;

        try {
            //create the input and output streams:
            fsIn  = new FileStream(sInFile, FileMode.Open, FileAccess.Read);
            fsOut = new FileStream(sOutFile, FileMode.Create, FileAccess.Write);

            //some helper variables
            byte[] bBuffer = new byte[4097];
            //4KB buffer
            long lBytesRead    = 0;
            long lFileSize     = fsIn.Length;
            int  lBytesToWrite = 0;

            if (encrypt)
            {
                encStream = new CryptoStream(fsOut, rijM.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write);
                //write the header to the output file for use when decrypting it
                encStream.Write(headerBytes, 0, headerBytes.Length);
                //this is the main encryption routine. it loops over the input data in blocks of 4KB,
                //and writes the encrypted data to disk
                do
                {
                    if (bCancel)
                    {
                        break;                              // TODO: might not be correct. Was : Exit Try
                    }
                    lBytesToWrite = fsIn.Read(bBuffer, 0, 4096);
                    if (lBytesToWrite == 0)
                    {
                        break;                                         // TODO: might not be correct. Was : Exit Do
                    }
                    encStream.Write(bBuffer, 0, lBytesToWrite);
                    lBytesRead += lBytesToWrite;
                    if (Progress != null)
                    {
                        Progress((int)(lBytesRead / lFileSize) * 100);
                    }
                }while (true);
                if (Progress != null)
                {
                    Progress(100);
                }
                retVal = ReturnType.Well;
            }
            else
            {
                encStream = new CryptoStream(fsIn, rijM.CreateDecryptor(bKey, bIV), CryptoStreamMode.Read);

                //read in the header
                byte[] test = new byte[headerBytes.Length + 1];
                encStream.Read(test, 0, headerBytes.Length);

                //check to see if the file header reads correctly.
                //if it doesn't, then close the stream & jump out
                if (ConvertBytesToString(test) != headerString)
                {
                    encStream.Clear();
                    encStream = null;
                    retVal    = ReturnType.IncorrectPassword;
                    break;                     // TODO: might not be correct. Was : Exit Try
                }

                //this is the main decryption routine. it loops over the input data in blocks of 4KB,
                //and writes the decrypted data to disk
                do
                {
                    if (bCancel)
                    {
                        //if the cancel flag is set,
                        //then jump out
                        encStream.Clear();
                        encStream = null;
                        break;                         // TODO: might not be correct. Was : Exit Try
                    }
                    lBytesToWrite = encStream.Read(bBuffer, 0, 4096);
                    if (lBytesToWrite == 0)
                    {
                        break;                                         // TODO: might not be correct. Was : Exit Do
                    }
                    fsOut.Write(bBuffer, 0, lBytesToWrite);
                    lBytesRead += lBytesToWrite;
                    if (Progress != null)
                    {
                        Progress((int)(lBytesRead / lFileSize) * 100);
                    }
                }while (true);
                if (Progress != null)
                {
                    Progress(100);
                }
                retVal = ReturnType.Well;
            }
        }
        catch (Exception ex) {
            Console.WriteLine("*****************ERROR*****************");
            Console.WriteLine(ex.ToString());
            Console.WriteLine("****************/ERROR*****************");
        }
        finally {
            //close all I/O streams (encStream first)
            if ((encStream != null))
            {
                encStream.Close();
            }
            if ((fsOut != null))
            {
                fsOut.Close();
            }
            if ((fsIn != null))
            {
                fsIn.Close();
            }
        }
        //only delete the file if the password was bad, and
        //therefore its only an empty file
        if (retVal == ReturnType.IncorrectPassword)
        {
            IO.File.Delete(sOutFile);
        }
        //raise the Finished event, and then reset bCancel
        if (Finished != null)
        {
            Finished(retVal);
        }
        bCancel = false;
    }
示例#37
0
        public bool HeaderReader()
        {
            NewFARC();
            if (!File.Exists(FilePath))
            {
                return(false);
            }

            Stream reader = File.OpenReader(FilePath);

            DirectoryPath = Path.GetFullPath(FilePath).Replace(Path.GetExtension(FilePath), "");
            Signature     = (Farc)reader.ReadInt32Endian(true);
            if (Signature != Farc.FArc && Signature != Farc.FArC && Signature != Farc.FARC)
            {
                reader.Close(); return(false);
            }

            int HeaderLength = reader.ReadInt32Endian(true);

            if (Signature == Farc.FARC)
            {
                FARCType = (Type)reader.ReadInt32Endian(true);
                reader.ReadInt32();

                int FARCMode = reader.ReadInt32Endian(true);
                FT  = FARCMode == 0x10;
                CBC = FARCMode != 0x10 && FARCMode != 0x40;

                if (CBC && FARCType.HasFlag(Type.ECB))
                {
                    reader.Close();
                    byte[]          Header = new byte[HeaderLength - 0x08];
                    MSIO.FileStream stream = new MSIO.FileStream(FilePath, MSIO.FileMode.Open,
                                                                 MSIO.FileAccess.ReadWrite, MSIO.FileShare.ReadWrite)
                    {
                        Position = 0x10
                    };

                    using (CryptoStream cryptoStream = new CryptoStream(stream,
                                                                        GetAes(true, null).CreateDecryptor(), CryptoStreamMode.Read))
                        cryptoStream.Read(Header, 0x00, HeaderLength - 0x08);
                    Header = SkipData(Header, 0x10);
                    reader = File.OpenReader(Header);

                    FARCMode = reader.ReadInt32Endian(true);
                    FT       = FARCMode == 0x10;
                }
            }

            if (Signature == Farc.FARC)
            {
                if (reader.ReadInt32Endian(true) == 1)
                {
                    Files = new FARCFile[reader.ReadInt32Endian(true)];
                }
            }
            reader.ReadInt32();

            if (Files == null)
            {
                int  Count    = 0;
                long Position = reader.LongPosition;
                while (reader.LongPosition < HeaderLength)
                {
                    reader.NullTerminated();
                    reader.ReadInt32();
                    if (Signature != Farc.FArc)
                    {
                        reader.ReadInt32();
                    }
                    reader.ReadInt32();
                    if (Signature == Farc.FARC && FT)
                    {
                        reader.ReadInt32();
                    }
                    Count++;
                }
                reader.LongPosition = Position;
                Files = new FARCFile[Count];
            }

            for (int i = 0; i < Files.Length; i++)
            {
                Files[i].Name   = reader.NullTerminatedUTF8();
                Files[i].Offset = reader.ReadInt32Endian(true);
                if (Signature != Farc.FArc)
                {
                    Files[i].SizeComp = reader.ReadInt32Endian(true);
                }
                Files[i].SizeUnc = reader.ReadInt32Endian(true);
                if (Signature == Farc.FARC && FT)
                {
                    Files[i].Type = (Type)reader.ReadInt32Endian(true);
                }
            }

            reader.Close();
            return(true);
        }
示例#38
0
        public byte[] FileReader(int i)
        {
            if (!HasFiles)
            {
                return(null);
            }
            if (i >= Files.Length)
            {
                return(null);
            }
            if (Signature != Farc.FARC)
            {
                if (Signature == Farc.FArC)
                {
                    using (MSIO.MemoryStream memorystream = new MSIO.MemoryStream(
                               File.ReadAllBytes(FilePath, Files[i].SizeComp, Files[i].Offset)))
                    {
                        GZipStream gZipStream = new GZipStream(memorystream, CompressionMode.Decompress);
                        Files[i].Data = new byte[Files[i].SizeUnc];
                        gZipStream.Read(Files[i].Data, 0, Files[i].SizeUnc);
                    }
                }
                else
                {
                    Files[i].Data = File.ReadAllBytes(FilePath, Files[i].SizeUnc, Files[i].Offset);
                }
                return(Files[i].Data);
            }

            int FileSize = FARCType.HasFlag(Type.ECB) || Files[i].Type.HasFlag(Type.ECB) ?
                           Files[i].SizeComp.Align(0x10) : Files[i].SizeComp;

            MSIO.FileStream stream = new MSIO.FileStream(FilePath, MSIO.FileMode.Open,
                                                         MSIO.FileAccess.ReadWrite, MSIO.FileShare.ReadWrite);
            stream.Seek(Files[i].Offset, 0);
            Files[i].Data = new byte[FileSize];

            bool Encrypted = false;

            if (FARCType.HasFlag(Type.ECB))
            {
                if ((FT && Files[i].Type.HasFlag(Type.ECB)) || CBC)
                {
                    using (CryptoStream cryptoStream = new CryptoStream(stream,
                                                                        GetAes(true, null).CreateDecryptor(), CryptoStreamMode.Read))
                        cryptoStream.Read(Files[i].Data, 0, FileSize);
                    Files[i].Data = SkipData(Files[i].Data, 0x10);
                }
                else
                {
                    using (CryptoStream cryptoStream = new CryptoStream(stream,
                                                                        GetAes(false, null).CreateDecryptor(), CryptoStreamMode.Read))
                        cryptoStream.Read(Files[i].Data, 0, FileSize);
                }
                Encrypted = true;
            }

            bool Compressed = false;

            if (((FT && Files[i].Type.HasFlag(Type.GZip)) ||
                 FARCType.HasFlag(Type.GZip)) && Files[i].SizeUnc > 0)
            {
                GZipStream gZipStream;
                if (Encrypted)
                {
                    gZipStream = new GZipStream(new MSIO.MemoryStream(Files[i].Data),
                                                CompressionMode.Decompress); stream.Close();
                }
                else
                {
                    gZipStream = new GZipStream(stream, CompressionMode.Decompress);
                }
                byte[] Temp = new byte[Files[i].SizeUnc];
                gZipStream.Read(Temp, 0, Files[i].SizeUnc);
                Files[i].Data = Temp;

                Compressed = true;
            }

            if (!Encrypted && !Compressed)
            {
                Files[i].Data = new byte[Files[i].SizeUnc];
                stream.Read(Files[i].Data, 0, Files[i].SizeUnc);
                stream.Close();
            }
            return(Files[i].Data);
        }
示例#39
0
        public AES3DESStream(Stream sbaseStream, bool bWriting, byte[] AESKey, byte[] AESIV, CompositeKey Level2Key) :
            base(sbaseStream, bWriting)
        {
            m_RandomStream  = new MemoryStream();
            m_ContentLength = 0;
            m_hash          = new SHA256Managed();
            m_2Key          = Level2Key;

            ICryptoTransform AESTransformer;

            RijndaelManaged r = new RijndaelManaged();

            r.BlockSize = 128;
            r.IV        = AESIV;
            r.KeySize   = 256;
            r.Key       = AESKey;
            r.Mode      = CipherMode.CBC;
            r.Padding   = PaddingMode.None; // We are taking care of the padding to make sure it is within 32 byte boundary


            if (bWriting)
            {
                CryptoRandom cr = CryptoRandom.Instance;
                m_MasterSeed    = cr.GetRandomBytes(32);
                m_TransformSeed = cr.GetRandomBytes(32);
                m_3DESIV        = cr.GetRandomBytes(8);
                m_NumRounds     = 10000;

                m_sBaseStream.WriteByte(0);
                m_sBaseStream.Write(m_MasterSeed, 0, 32);
                m_sBaseStream.Write(m_TransformSeed, 0, 32);
                m_sBaseStream.Write(m_3DESIV, 0, 8);
                m_sBaseStream.Write(Extensions.GetLittleEndianBytes(m_NumRounds), 0, 8);


                m_AESStream = new MemoryStream();

                AESTransformer    = r.CreateEncryptor();
                m_CryptoStreamAES = new CryptoStream(m_AESStream, AESTransformer, CryptoStreamMode.Write);
            }
            else
            {
                // File format version and algorithm has been read
                m_MasterSeed = new byte[32];
                sbaseStream.Read(m_MasterSeed, 0, 32);

                m_TransformSeed = new byte[32];
                sbaseStream.Read(m_TransformSeed, 0, 32);

                m_3DESIV = new byte[8];
                sbaseStream.Read(m_3DESIV, 0, 8);

                byte[] buffer = new byte[8];
                sbaseStream.Read(buffer, 0, 8);
                m_NumRounds = Extensions.ToLittleEndianUInt64(buffer);

                byte[] len = new byte[4];
                m_sBaseStream.Read(len, 0, 4);

                m_ContentLength = Extensions.ToLittleEndianInt32(len);
                int remainder = m_ContentLength % 32;

                int buflen = m_ContentLength + 32;

                if (remainder > 0)
                {
                    buflen -= remainder;
                }
                else
                {
                    buflen -= 32;
                }

                byte[] AESBuffer = new byte[buflen];

                AESTransformer    = r.CreateDecryptor();
                m_CryptoStreamAES = new CryptoStream(m_sBaseStream, AESTransformer, CryptoStreamMode.Read);

                int read = m_CryptoStreamAES.Read(AESBuffer, 0, buflen);

                if (read != buflen)
                {
                    throw new InvalidDataException("Invalid Data length");
                }

                byte[] DES3Buffer = new byte[buflen];

                m_hash.TransformFinalBlock(AESBuffer, 0, buflen);

                CryptoStream Stream3DES = new CryptoStream(m_sBaseStream, Get3DES().CreateDecryptor(), CryptoStreamMode.Read);
                read = Stream3DES.Read(DES3Buffer, 0, buflen);

                if (read != buflen)
                {
                    throw new InvalidDataException("Invalid Data length 2");
                }

                for (int i = 0; i < m_ContentLength; i++)
                {
                    AESBuffer[i] ^= DES3Buffer[i];
                }

                m_AESStream = new MemoryStream(AESBuffer, 0, m_ContentLength);
            }
        }
        public MemoryStream DecryptFileToMemoryStream(string filePath, string passwordString, CryptoProgress progress)
        {
            var        ms = new MemoryStream();
            FileStream fs = null;

            try
            {
                CryptoProgressHandler progressHandler = null;
                if (string.IsNullOrEmpty(passwordString))
                {
                    throw new Exception("Password can not be null or empty");
                }

                fs          = File.OpenRead(filePath);
                fs.Position = 0;


                if (progress != null)
                {
                    progressHandler = new CryptoProgressHandler {
                        EncodedBytes = 0, TotalBytes = fs.Length, Text = "Starting decryption"
                    };
                    progress.Report(progressHandler);
                }

                // Create an AesCryptoServiceProvider object
                using (Aes aesAlg = Aes.Create())
                {
                    var rfc2898DeriveBytes = new Rfc2898DeriveBytes(passwordString, SALT, 1000);
                    aesAlg.BlockSize = 128;
                    aesAlg.KeySize   = 256;
                    aesAlg.Padding   = PaddingMode.PKCS7;
                    aesAlg.Mode      = CipherMode.CBC;

                    aesAlg.Key = rfc2898DeriveBytes.GetBytes(32);
                    aesAlg.IV  = rfc2898DeriveBytes.GetBytes(16);

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

                    // Create the streams used for decryption.
                    int bufferSize     = Math.Min(MaxBufferSize, (int)fs.Length);
                    var plainTextBytes = new byte[bufferSize];

                    using (var csDecrypt = new CryptoStream(fs, decryptor, CryptoStreamMode.Read))
                    {
                        int decryptedByteCount;
                        while ((decryptedByteCount = csDecrypt.Read(plainTextBytes, 0, plainTextBytes.Length)) > 0)
                        {
                            ms.Write(plainTextBytes, 0, decryptedByteCount);
                            if (progressHandler == null)
                            {
                                continue;
                            }
                            progressHandler.EncodedBytes += decryptedByteCount;
                            progress.Report(progressHandler);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error in EncryptionManager.EncryptAndSaveFile");
                return(null);
            }
            finally
            {
                fs?.Close();

                progress?.Report(new CryptoProgressHandler {
                    EncodedBytes = ms.Length, TotalBytes = ms.Length, Text = "Decryption completed"
                });
            }

            return(ms);
        }
 public static byte[] decryptBytes(byte[] Value, byte[] Key, byte[] IV)
 {
     try
     {
         Monitor.Enter(_lock);
 #if __DotNet35Plus
         thisCSP = new AesCryptoServiceProvider();
 #else
         thisCSP = new RijndaelManaged();
 #endif
         thisCSP.KeySize = KeySize;
         Int32 bitLength = Key.Length * 8;
         if (bitLength != thisCSP.KeySize)
         {
             throw new ArgumentException("The supplied key's length [" + bitLength.ToString() + " bits] is not a valid key size for the AES-256 algorithm.", "Key");
         }
         bitLength = IV.Length * 8;
         if (bitLength != thisCSP.BlockSize)
         {
             throw new ArgumentException("The supplied IV's length [" + bitLength.ToString() + " bits] is not a valid IV size for the AES-256 algorithm.", "IV");
         }
         try
         {
             byte[]           Decrypted;
             ICryptoTransform Decryptor = thisCSP.CreateDecryptor(Key, IV);
             msDecrypt = new MemoryStream(Value);
             csDecrypt = new CryptoStream(msDecrypt, Decryptor, CryptoStreamMode.Read);
             Decrypted = (byte[])Array.CreateInstance(typeof(byte), msDecrypt.Length);
             csDecrypt.Read(Decrypted, 0, Decrypted.Length);
             Decryptor.Dispose();
             Decryptor = null;
             msDecrypt.Close();
             Int32 trimCount = 0;
             // Remove any block padding left over from encryption algorithm before returning
             for (Int32 i = Decrypted.Length - 1; i >= 0; i--)
             {
                 if (Decrypted[i] == 0)
                 {
                     trimCount++;
                 }
                 else
                 {
                     break;
                 }
             }
             if (trimCount > 0)
             {
                 byte[] buffer = (byte[])Array.CreateInstance(typeof(byte), Decrypted.Length - trimCount);
                 Array.ConstrainedCopy(Decrypted, 0, buffer, 0, buffer.Length);
                 Array.Clear(Decrypted, 0, Decrypted.Length);
                 Array.Resize <byte>(ref Decrypted, buffer.Length);
                 Array.Copy(buffer, Decrypted, buffer.Length);
                 buffer = null;
             }
             return(Decrypted);
         }
         finally
         {
             thisCSP = null;
         }
     }
     finally
     {
         Monitor.Exit(_lock);
     }
 }
        /// <summary>
        /// decrypt the stream data asymmetrically using the security profile
        /// information stored in the configuration file
        /// </summary>
        /// <param name="data">encrypted stream data</param>
        /// <param name="profile">security profile name</param>
        /// <param name="key">generated key</param>
        /// <param name="iv">generated iv</param>
        /// <param name="signature">generated signature</param>
        /// <returns>decrypted stream</returns>
        public static Stream Decrypt(Stream data, string profile, byte[] key, byte[] iv, byte[] signature)
        {
            var helper = new EncryptionConfigHelper();
            var cm     = helper[profile];


            if (cm.SymmetricAlgorithm)
            {
                throw new Exception("This method id not intended for symmetric  encryption");
            }


            //retireve the sneder and receiver's certification information for encryption
            var    senderCert            = cm.ExtentProperty["SenderCertificate"];
            string sendCertStore         = null;
            string sendCertStoreName     = null;
            string password              = null;
            var    receiverCert          = cm.ExtentProperty["ReceiverCertificate"];
            string receiverCertStore     = null;
            string receiverCertStoreName = null;

            var fromFile = cm.ExtentProperty["CertificateFile"] == "true";

            if (!fromFile)
            {
                if (cm.ExtentProperty.ContainsKey("SenderCertificateStore"))
                {
                    sendCertStore = cm.ExtentProperty["SenderCertificateStore"];
                }
                if (cm.ExtentProperty.ContainsKey("SenderCertificateStoreName"))
                {
                    sendCertStoreName = cm.ExtentProperty["SenderCertificateStoreName"];
                }

                if (cm.ExtentProperty.ContainsKey("ReceiverCertificateStore"))
                {
                    receiverCertStore = cm.ExtentProperty["ReceiverCertificateStore"];
                }

                if (cm.ExtentProperty.ContainsKey("ReceiverCertificateStoreName"))
                {
                    receiverCertStoreName = cm.ExtentProperty["ReceiverCertificateStoreName"];
                }
            }
            else
            {
                password = cm.ExtentProperty["SenderCertificatePassword"];
            }
            //obtain the X509 certificate object for the sender and receiver
            var senderCertificate   = fromFile ? Certificate.LoadCertificateByFile(senderCert, password) : Certificate.SearchCertificateBySubjectName(senderCert, sendCertStore, sendCertStoreName);
            var receiverCertificate = fromFile ? Certificate.LoadCertificateByFile(receiverCert, null) : Certificate.SearchCertificateBySubjectName(receiverCert, receiverCertStore, receiverCertStoreName);

            string senderPrivateKey  = senderCertificate.GetKeyAlgorithmParametersString();
            string receiverPublicKey = receiverCertificate.GetPublicKeyString();

            if (string.IsNullOrEmpty(senderPrivateKey) || string.IsNullOrEmpty(receiverPublicKey))
            {
                throw new Exception("用于签名的私有Key或公有Key为空。");
            }

            //import the public key information to verify the data
            var provider = (RSACryptoServiceProvider)receiverCertificate.PublicKey.Key;

            var ms     = new MemoryStream();
            var buffer = new Byte[1024];
            int count;

            while ((count = data.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, count);
            }

            var encryptedData = ms.ToArray();
            //data.Position = 0 ;
            //data.Read(encryptedData,0,encryptedData.Length);
            //verify if the data has been tempered with
            var v = provider.VerifyData(encryptedData, new SHA1CryptoServiceProvider(), signature);

            if (v == false)
            {
                throw new CryptographicException();
            }
            //import the private key information to decrypt data
            var provider2 = (RSACryptoServiceProvider)senderCertificate.PrivateKey;
            //decrypt the secret key and iv
            var decryptedkey = provider2.Decrypt(key, false);
            var decryptediv  = provider2.Decrypt(iv, false);

            var symmProvider = SymmetricAlgorithm.Create(cm.AlgorithmProvider);

            symmProvider.Key = decryptedkey;
            symmProvider.IV  = decryptediv;
            var decryptor = symmProvider.CreateDecryptor();

            ms.Position = 0;
            //decrypt the stream
            var decStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
            var decrypted = new MemoryStream();

            while ((count = decStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                decrypted.Write(buffer, 0, count);
            }
            decrypted.Position = 0;
            return(decrypted);
        }
示例#43
0
文件: FARC.cs 项目: nastys/PD_Tool
        public void UnPack(string file, bool SaveToDisk = true)
        {
            Files         = null;
            Signature     = Farc.FArC;
            FT            = false;
            Console.Title = "FARC Extractor - Archive: " + Path.GetFileName(file);
            if (!File.Exists(file))
            {
                Console.WriteLine("File {0} doesn't exist.", Path.GetFileName(file));
                Console.Clear();
                return;
            }

            Stream reader    = File.OpenReader(file);
            string directory = Path.GetFullPath(file).Replace(Path.GetExtension(file), "");

            Signature = (Farc)reader.ReadInt32Endian(true);
            if (Signature != Farc.FArc && Signature != Farc.FArC && Signature != Farc.FARC)
            {
                Console.WriteLine("Unknown signature"); reader.Close();
                Console.Clear();
                return;
            }

            MSIO.Directory.CreateDirectory(directory);
            int HeaderLength = reader.ReadInt32Endian(true);

            if (Signature != Farc.FARC)
            {
                reader.ReadUInt32();
                HeaderReader(HeaderLength, ref Files, ref reader);
                reader.Close();

                for (int i = 0; i < Files.Length; i++)
                {
                    if (Signature == Farc.FArC)
                    {
                        using (MSIO.MemoryStream memorystream = new MSIO.MemoryStream(
                                   File.ReadAllBytes(file, Files[i].SizeComp, Files[i].Offset)))
                        {
                            GZipStream gZipStream = new GZipStream(memorystream, CompressionMode.Decompress);
                            Files[i].Data = new byte[Files[i].SizeUnc];
                            gZipStream.Read(Files[i].Data, 0, Files[i].SizeUnc);
                        }
                    }
                    else
                    {
                        Files[i].Data = File.ReadAllBytes(file, Files[i].SizeUnc, Files[i].Offset);
                    }

                    if (SaveToDisk)
                    {
                        File.WriteAllBytes(Path.Combine(directory, Files[i].Name), Files[i].Data);
                        Files[i].Data = null;
                    }
                }
                Console.Clear();
                return;
            }

            int Mode = reader.ReadInt32Endian(true);

            reader.ReadUInt32();
            bool GZip = (Mode & 2) == 2;
            bool ECB  = (Mode & 4) == 4;

            int FARCType = reader.ReadInt32Endian(true);

            FT = FARCType == 0x10;
            bool CBC = !FT && FARCType != 0x40;

            if (ECB && CBC)
            {
                byte[] Header = new byte[HeaderLength - 0x08];
                FT = true;
                reader.Close();
                MSIO.FileStream stream = new MSIO.FileStream(file, MSIO.FileMode.Open,
                                                             MSIO.FileAccess.ReadWrite, MSIO.FileShare.ReadWrite);
                stream.Seek(0x10, 0);

                using (CryptoStream cryptoStream = new CryptoStream(stream,
                                                                    GetAes(true, null).CreateDecryptor(), CryptoStreamMode.Read))
                    cryptoStream.Read(Header, 0x00, HeaderLength - 0x08);
                Header = SkipData(Header, 0x10);
                Stream CBCreader = new Stream(new MSIO.MemoryStream(Header));
                CBCreader.BaseStream.Seek(0, 0);

                FARCType = CBCreader.ReadInt32Endian(true);
                FT       = FARCType == 0x10;
                if (CBCreader.ReadInt32Endian(true) == 1)
                {
                    Files = new FARCFile[CBCreader.ReadInt32Endian(true)];
                }
                CBCreader.ReadUInt32();
                HeaderReader(HeaderLength, ref Files, ref CBCreader);
                CBCreader.Close();
            }
            else
            {
                if (reader.ReadInt32Endian(true) == 1)
                {
                    Files = new FARCFile[reader.ReadInt32Endian(true)];
                }
                reader.ReadUInt32();
                HeaderReader(HeaderLength, ref Files, ref reader);
                reader.Close();
            }

            for (int i = 0; i < Files.Length; i++)
            {
                int             FileSize = ECB || Files[i].ECB ? Files[i].SizeComp.Align(0x10) : Files[i].SizeComp;
                MSIO.FileStream stream   = new MSIO.FileStream(file, MSIO.FileMode.Open,
                                                               MSIO.FileAccess.ReadWrite, MSIO.FileShare.ReadWrite);
                stream.Seek(Files[i].Offset, 0);
                Files[i].Data = new byte[FileSize];

                bool Encrypted = false;
                if (ECB)
                {
                    if ((FT && Files[i].ECB) || CBC)
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(stream,
                                                                            GetAes(true, null).CreateDecryptor(), CryptoStreamMode.Read))
                            cryptoStream.Read(Files[i].Data, 0, FileSize);
                        Files[i].Data = SkipData(Files[i].Data, 0x10);
                    }
                    else
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(stream,
                                                                            GetAes(false, null).CreateDecryptor(), CryptoStreamMode.Read))
                            cryptoStream.Read(Files[i].Data, 0, FileSize);
                    }
                    Encrypted = true;
                }

                bool Compressed = false;
                bool LocalGZip  = (FT && Files[i].GZip) || GZip && Files[i].SizeUnc != 0;
                if (LocalGZip)
                {
                    GZipStream gZipStream;
                    if (Encrypted)
                    {
                        gZipStream = new GZipStream(new MSIO.MemoryStream(
                                                        Files[i].Data), CompressionMode.Decompress);
                        stream.Close();
                    }
                    else
                    {
                        gZipStream = new GZipStream(stream, CompressionMode.Decompress);
                    }
                    Files[i].Data = new byte[Files[i].SizeUnc];
                    gZipStream.Read(Files[i].Data, 0, Files[i].SizeUnc);

                    Compressed = true;
                }

                if (!Encrypted && !Compressed)
                {
                    Files[i].Data = new byte[Files[i].SizeUnc];
                    stream.Read(Files[i].Data, 0, Files[i].SizeUnc);
                    stream.Close();
                }

                if (SaveToDisk)
                {
                    File.WriteAllBytes(Path.Combine(directory, Files[i].Name), Files[i].Data);
                    Files[i].Data = null;
                }
            }
            Console.Clear();
        }
        /// <summary>
        /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
        /// </summary>
        /// <param name="cipherText">
        /// Base64-formatted ciphertext value.
        /// </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>
        /// Decrypted string value.
        /// </returns>
        /// <remarks>
        /// Most of the logic in this function is similar to the Encrypt
        /// logic. In order for decryption to work, all parameters of this function
        /// - except cipherText value - must match the corresponding parameters of
        /// the Encrypt function which was called to generate the
        /// ciphertext.
        /// </remarks>
        public static string Decrypt(string cipherText,
                                     string passPhrase,
                                     string saltValue,
                                     string hashAlgorithm,
                                     int passwordIterations,
                                     string initVector,
                                     int keySize)
        {
            // Convert strings defining encryption key characteristics into byte
            // arrays. Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);

            // Convert our ciphertext into a byte array.
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            // First, we must create a password, from which the key will be
            // derived. This password will be generated from the specified
            // passphrase and salt value. The password will be created using
            // the specified hash algorithm. Password creation can be done in
            // several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                passPhrase,
                saltValueBytes,
                hashAlgorithm,
                passwordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(keySize / 8);

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

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate decryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                keyBytes,
                initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

            // Define cryptographic stream (always use Read mode for encryption).
            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 ciphertext;
            // plaintext is never longer than ciphertext.
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            // Start decrypting.
            int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                       0,
                                                       plainTextBytes.Length);

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert decrypted data into a string.
            // Let us assume that the original plaintext string was UTF8-encoded.
            string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                       0,
                                                       decryptedByteCount);

            // Return decrypted string.
            return(plainText);
        }
示例#45
0
        public static string DecryptString(string strToDecrypt, ref bool result, bool WriteErrorsToLog = true)
        {
            try
            {
                //Convert strings defining encryption key characteristics into byte arrays
                byte[] _initVectorBytes = Encoding.UTF8.GetBytes(INIT_VECTOR);
                byte[] _saltValueBytes  = Encoding.UTF8.GetBytes(SALT_VALUE);

                // Create a password, from which the key will be derived
                PasswordDeriveBytes _password = new PasswordDeriveBytes(PASS_PHRASE, _saltValueBytes, HASH_ALGORITHM, PASSWORD_ITERATIONS);

                // Use the password to generate pseudo-random bytes for the encryption key
                byte[] _keyBytes = _password.GetBytes(KEY_SIZE / 8);

                // Create uninitialized Rijndael Object
                RijndaelManaged _rijndaelObject = new RijndaelManaged();

                //check strToEncrypt is not empty
                if ((strToDecrypt == null) || (strToDecrypt == string.Empty))
                {
                    return(strToDecrypt);
                }
                else
                {
                    // Convert strToEncrypt into a byte array.
                    byte[] strToDecryptBytes = Convert.FromBase64String(strToDecrypt);

                    // Set encryption mode to Cipher Block Chaining(CBC)
                    _rijndaelObject.Mode = CipherMode.CBC;

                    // Generate encryptor from the existing key bytes and initializationvector
                    ICryptoTransform decryptor = _rijndaelObject.CreateDecryptor(_keyBytes, _initVectorBytes);

                    // Define memory stream which will be used to hold encrypted data.
                    MemoryStream memoryStream = new MemoryStream(strToDecryptBytes);

                    // Define cryptographic stream
                    CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

                    // allocate the buffer long enough to hold ciphertext;
                    byte[] plainTextBytes = new byte[strToDecryptBytes.Length];

                    // Start decrypting
                    int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);

                    // Close both streams
                    memoryStream.Close();
                    cryptoStream.Close();

                    // Convert decrypted data into a string.
                    string decryptedStr = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);

                    // Return decrypted string.
                    result = true;
                    return(decryptedStr);
                }
            }
            catch (Exception ex)
            {
                if (WriteErrorsToLog)
                {
                    Reporter.ToLog(eLogLevel.ERROR, string.Format("Failed to Decrypt the value: '{0}'", strToDecrypt), ex);
                }
                result = false;
                return(string.Empty);
            }
        }
        /// <summary>
        /// 异步加密算法
        /// of specific security profile in the configuration file
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="profile">配置名</param>
        /// <param name="key">output parameter for generated secret key</param>
        /// <param name="iv">output parameter for generated iv</param>
        /// <param name="signature">out parameters for the digital signature</param>
        /// <returns>stream data</returns>
        public static Stream Encrypt(Stream data, string profile, out byte[] key, out byte[] iv, out byte[] signature)
        {
            var helper = new EncryptionConfigHelper();
            var cm     = helper[profile];


            if (cm.SymmetricAlgorithm)
            {
                throw new Exception("This method id not intended for symmetric  encryption");
            }

            //retireve the sneder and receiver's certification information for encryption
            var    senderCert        = cm.ExtentProperty["SenderCertificate"];
            string sendCertStore     = null;
            string sendCertStoreName = null;
            string password          = null;

            var    receiverCert          = cm.ExtentProperty["ReceiverCertificate"];
            string receiverCertStore     = null;
            string receiverCertStoreName = null;

            var fromFile = cm.ExtentProperty["CertificateFile"] == "true";

            if (!fromFile)
            {
                if (cm.ExtentProperty.ContainsKey("SenderCertificateStore"))
                {
                    sendCertStore = cm.ExtentProperty["SenderCertificateStore"];
                }
                if (cm.ExtentProperty.ContainsKey("SenderCertificateStoreName"))
                {
                    sendCertStoreName = cm.ExtentProperty["SenderCertificateStoreName"];
                }

                if (cm.ExtentProperty.ContainsKey("ReceiverCertificateStore"))
                {
                    receiverCertStore = cm.ExtentProperty["ReceiverCertificateStore"];
                }

                if (cm.ExtentProperty.ContainsKey("ReceiverCertificateStoreName"))
                {
                    receiverCertStoreName = cm.ExtentProperty["ReceiverCertificateStoreName"];
                }
            }
            else
            {
                password = cm.ExtentProperty["SenderCertificatePassword"];
            }

            //obtain the X509 certificate object for the sender and receiver
            var senderCertificate   = fromFile ? Certificate.LoadCertificateByFile(senderCert, password) : Certificate.SearchCertificateBySubjectName(senderCert, sendCertStore, sendCertStoreName);
            var receiverCertificate = fromFile ? Certificate.LoadCertificateByFile(receiverCert, null) : Certificate.SearchCertificateBySubjectName(receiverCert, receiverCertStore, receiverCertStoreName);


            var symmProvider = cm.AlgorithmProvider.CreateInstance <SymmetricAlgorithm>();

            ICryptoTransform encryptor = symmProvider.CreateEncryptor();

            var encStream = new CryptoStream(data, encryptor, CryptoStreamMode.Read);
            var encrypted = new MemoryStream();
            var buffer    = new byte[1024];
            int count;

            while ((count = encStream.Read(buffer, 0, 1024)) > 0)
            {
                encrypted.Write(buffer, 0, count);
            }
            //encrypt the screte key, iv key using receiver's public key
            //that are used to decrypt the data
            var provider = (RSACryptoServiceProvider)receiverCertificate.PublicKey.Key;

            key = provider.Encrypt(symmProvider.Key, false);
            iv  = provider.Encrypt(symmProvider.IV, false);

            //sign the data with sender's private key
            var provider2 = (RSACryptoServiceProvider)senderCertificate.PrivateKey;

            signature          = provider2.SignData(encrypted.ToArray(), new SHA1CryptoServiceProvider());
            encrypted.Position = 0;
            return(encrypted);
        }
示例#47
0
        public static void ValidateWhitespace(string expected, string data)
        {
            byte[] inputBytes = Text.Encoding.ASCII.GetBytes(data);
            byte[] outputBytes = new byte[100];

            // Verify default of FromBase64TransformMode.IgnoreWhiteSpaces
            using (var base64Transform = new FromBase64Transform()) 
            using (var ms = new MemoryStream(inputBytes))
            using (var cs = new CryptoStream(ms, base64Transform, CryptoStreamMode.Read))
            {
                int bytesRead = cs.Read(outputBytes, 0, outputBytes.Length);
                string outputString = Text.Encoding.ASCII.GetString(outputBytes, 0, bytesRead);
                Assert.Equal(expected, outputString);
            }

            // Verify explicit FromBase64TransformMode.IgnoreWhiteSpaces
            using (var base64Transform = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces))
            using (var ms = new MemoryStream(inputBytes))
            using (var cs = new CryptoStream(ms, base64Transform, CryptoStreamMode.Read))
            {
                int bytesRead = cs.Read(outputBytes, 0, outputBytes.Length);
                string outputString = Text.Encoding.ASCII.GetString(outputBytes, 0, bytesRead);
                Assert.Equal(expected, outputString);
            }

            // Verify FromBase64TransformMode.DoNotIgnoreWhiteSpaces
            using (var base64Transform = new FromBase64Transform(FromBase64TransformMode.DoNotIgnoreWhiteSpaces))
            using (var ms = new MemoryStream(inputBytes))
            using (var cs = new CryptoStream(ms, base64Transform, CryptoStreamMode.Read))
            {
                Assert.Throws<FormatException>(() => cs.Read(outputBytes, 0, outputBytes.Length));
            }
        }
示例#48
0
        public static void Roundtrip(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks)
        {
            ICryptoTransform encryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks);
            ICryptoTransform decryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks);

            var stream = new MemoryStream();
            using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
            {
                Assert.True(encryptStream.CanWrite);
                Assert.False(encryptStream.CanRead);
                Assert.False(encryptStream.CanSeek);
                Assert.False(encryptStream.HasFlushedFinalBlock);
                Assert.Throws<NotSupportedException>(() => encryptStream.SetLength(1));
                Assert.Throws<NotSupportedException>(() => encryptStream.Length);
                Assert.Throws<NotSupportedException>(() => encryptStream.Position);
                Assert.Throws<NotSupportedException>(() => encryptStream.Position = 0);
                Assert.Throws<NotSupportedException>(() => encryptStream.Seek(0, SeekOrigin.Begin));
                Assert.Throws<NotSupportedException>(() => encryptStream.Read(new byte[0], 0, 0));
                Assert.Throws<NullReferenceException>(() => encryptStream.Write(null, 0, 0)); // No arg validation on buffer?
                Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], -1, 0));
                Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1));
                Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1));
                Assert.Throws<ArgumentException>(() => encryptStream.Write(new byte[3], 1, 4));

                byte[] toWrite = Encoding.UTF8.GetBytes(LoremText);

                // Write it all at once
                encryptStream.Write(toWrite, 0, toWrite.Length);
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Write in chunks
                encryptStream.Write(toWrite, 0, toWrite.Length / 2);
                encryptStream.Write(toWrite, toWrite.Length / 2, toWrite.Length - (toWrite.Length / 2));
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Write one byte at a time
                for (int i = 0; i < toWrite.Length; i++)
                {
                    encryptStream.WriteByte(toWrite[i]);
                }
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Write async
                encryptStream.WriteAsync(toWrite, 0, toWrite.Length).GetAwaiter().GetResult();
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Flush (nops)
                encryptStream.Flush();
                encryptStream.FlushAsync().GetAwaiter().GetResult();

                encryptStream.FlushFinalBlock();
                Assert.Throws<NotSupportedException>(() => encryptStream.FlushFinalBlock());
                Assert.True(encryptStream.HasFlushedFinalBlock);

                Assert.True(stream.Length > 0);
            }

            // Read/decrypt using Read
            stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
            using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
            {
                Assert.False(decryptStream.CanWrite);
                Assert.True(decryptStream.CanRead);
                Assert.False(decryptStream.CanSeek);
                Assert.False(decryptStream.HasFlushedFinalBlock);
                Assert.Throws<NotSupportedException>(() => decryptStream.SetLength(1));
                Assert.Throws<NotSupportedException>(() => decryptStream.Length);
                Assert.Throws<NotSupportedException>(() => decryptStream.Position);
                Assert.Throws<NotSupportedException>(() => decryptStream.Position = 0);
                Assert.Throws<NotSupportedException>(() => decryptStream.Seek(0, SeekOrigin.Begin));
                Assert.Throws<NotSupportedException>(() => decryptStream.Write(new byte[0], 0, 0));
                Assert.Throws<NullReferenceException>(() => decryptStream.Read(null, 0, 0)); // No arg validation on buffer?
                Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], -1, 0));
                Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1));
                Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1));
                Assert.Throws<ArgumentException>(() => decryptStream.Read(new byte[3], 1, 4));

                using (StreamReader reader = new StreamReader(decryptStream))
                {
                    Assert.Equal(
                        LoremText + LoremText + LoremText + LoremText,
                        reader.ReadToEnd());
                }
            }

            // Read/decrypt using ReadToEnd
            stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
            using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
            using (StreamReader reader = new StreamReader(decryptStream))
            {
                Assert.Equal(
                    LoremText + LoremText + LoremText + LoremText,
                    reader.ReadToEndAsync().GetAwaiter().GetResult());
            }

            // Read/decrypt using a small buffer to force multiple calls to Read
            stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
            using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
            using (StreamReader reader = new StreamReader(decryptStream, Encoding.UTF8, true, bufferSize: 10))
            {
                Assert.Equal(
                    LoremText + LoremText + LoremText + LoremText,
                    reader.ReadToEndAsync().GetAwaiter().GetResult());
            }            
            
            // Read/decrypt one byte at a time with ReadByte
            stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
            using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
            {
                string expectedStr = LoremText + LoremText + LoremText + LoremText;
                foreach (char c in expectedStr)
                {
                    Assert.Equal(c, decryptStream.ReadByte()); // relies on LoremText being ASCII
                }
                Assert.Equal(-1, decryptStream.ReadByte());
            }
        }
    /// <summary>
    /// Decrypts source
    /// </summary>
    /// <param name="source"></param>
    /// <param name="key">the key to build with</param>
    /// <param name="keyStr">the key string to build with</param>
    public static byte[] DecryptWithRijndael(this byte[] source, string keyStr, byte[] key)
    {
        // exit if null
        if (source.IsNullOrEmpty())
            return null;

        try
        {
            using (RijndaelManaged RCrypto = new RijndaelManaged())
            {
                BuildRijndaelKeys(RCrypto, keyStr, key);

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

                // decrypt with a crypto stream
                // read from
                using (MemoryStream SourceMemStream = new MemoryStream(source))
                {
                    // run through decryptor
                    using (CryptoStream cryptoStream = new CryptoStream(SourceMemStream, RDecryptor, CryptoStreamMode.Read))
                    {
                        // save to memory stream so we can get decrypted bytes
                        using (MemoryStream decMemStream = new MemoryStream())
                        {
                            byte[] buffer = new byte[512];
                            int bytesRead;

                            while ((bytesRead = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
                                decMemStream.Write(buffer, 0, bytesRead);

                            // get the decrypted data (still in byte form)
                            return decMemStream.ToArray();
                        }
                    }
                }
            }
        }

        catch (Exception excep)
        {
            ExceptionLogger.SaveException(excep, source);
        }

        return null;
    }
示例#50
0
        public static string Decrypt(string cipherText, string uphash)
        {
            try
            {
                // Allocate a byte array to copy the string into
                byte[] bytes = Encoding.ASCII.GetBytes(gethash(uphash));

                // 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(256 / 8).ToArray();
                // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
                var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(256 / 8).Take(256 / 8).ToArray();
                // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
                var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((256 / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((256 / 8) * 2)).ToArray();

                for (int i = 0; i < cipherTextBytesWithSaltAndIv.Length; i++)
                {
                    cipherTextBytesWithSaltAndIv[i] = 0;
                }

                using (var password = new Rfc2898DeriveBytes(bytes, saltStringBytes, 10000))
                {
                    for (int i = 0; i < bytes.Count(); i++)
                    {
                        bytes[i] = 0;
                    }
                    for (int i = 0; i < saltStringBytes.Length; i++)
                    {
                        saltStringBytes[i] = 0;
                    }

                    var keyBytes = password.GetBytes(256 / 8);
                    using (var symmetricKey = new RijndaelManaged())
                    {
                        symmetricKey.BlockSize = 256;
                        symmetricKey.Mode      = CipherMode.CBC;
                        symmetricKey.Padding   = PaddingMode.PKCS7;
                        using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                        {
                            for (int i = 0; i < keyBytes.Length; i++)
                            {
                                keyBytes[i] = 0;
                            }
                            for (int i = 0; i < ivStringBytes.Length; i++)
                            {
                                ivStringBytes[i] = 0;
                            }

                            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();

                                    for (int i = 0; i < cipherTextBytes.Length; i++)
                                    {
                                        cipherTextBytes[i] = 0;
                                    }

                                    return(Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount));
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                return(null);
            }
            finally
            {
            }
        }
示例#51
0
    /// <summary>
    /// Decrypts a base64-encoded cipher text value and generates a byte array
    /// of plain text data.
    /// </summary>
    /// <param name="cipherTextBytes">
    /// Byte array containing encrypted data.
    /// </param>
    /// <returns>
    /// Byte array containing decrypted value.
    /// </returns>
    public byte[] DecryptToBytes(byte[] cipherTextBytes)
    {
        byte[] decryptedBytes = null;
        byte[] plainTextBytes = null;
        int decryptedByteCount = 0;
        int saltLen = 0;

        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

        // Since we do not know how big decrypted value will be, use the same
        // size as cipher text. Cipher text is always longer than plain text
        // (in block cipher encryption), so we will just use the number of
        // decrypted data byte after we know how big it is.
        decryptedBytes = new byte[cipherTextBytes.Length];

        // Let's make cryptographic operations thread-safe.
        lock (this)
        {
            // To perform decryption, we must use the Read mode.
            CryptoStream cryptoStream = new CryptoStream(
                                               memoryStream,
                                               decryptor,
                                               CryptoStreamMode.Read);

            // Decrypting data and get the count of plain text bytes.
            decryptedByteCount = cryptoStream.Read(decryptedBytes,
                                                    0,
                                                    decryptedBytes.Length);
            // Release memory.
            memoryStream.Close();
            cryptoStream.Close();
        }

        // If we are using salt, get its length from the first 4 bytes of plain
        // text data.
        if (maxSaltLen > 0 && maxSaltLen >= minSaltLen)
        {
            saltLen = (decryptedBytes[0] & 0x03) |
                        (decryptedBytes[1] & 0x0c) |
                        (decryptedBytes[2] & 0x30) |
                        (decryptedBytes[3] & 0xc0);
        }

        // Allocate the byte array to hold the original plain text (without salt).
        plainTextBytes = new byte[decryptedByteCount - saltLen];

        // Copy original plain text discarding the salt value if needed.
        Array.Copy(decryptedBytes, saltLen, plainTextBytes,
                    0, decryptedByteCount - saltLen);

        // Return original plain text value.
        return plainTextBytes;
    }
示例#52
0
        public bool HeaderReader()
        {
            NewFARC();
            if (!File.Exists(FilePath))
            {
                return(false);
            }

            Stream reader = File.OpenReader(FilePath);

            DirectoryPath = Path.GetFullPath(FilePath).Replace(Path.GetExtension(FilePath), "");
            Signature     = (Farc)reader.RI32E(true);
            if (Signature != Farc.FArc && Signature != Farc.FArC && Signature != Farc.FARC)
            {
                reader.Dispose(); return(false);
            }

            int headerLength = reader.RI32E(true);

            if (Signature == Farc.FARC)
            {
                FARCType = (Type)reader.RI32E(true);
                reader.RI32();

                int farcMode = reader.RI32E(true);
                ft  = farcMode == 0x10;
                cbc = farcMode != 0x10 && farcMode != 0x40;

                if (cbc && (FARCType & Type.ECB) != 0)
                {
                    reader.Dispose();
                    byte[]          header = new byte[headerLength - 0x08];
                    MSIO.FileStream stream = new MSIO.FileStream(FilePath, MSIO.FileMode.Open,
                                                                 MSIO.FileAccess.ReadWrite, MSIO.FileShare.ReadWrite)
                    {
                        Position = 0x10
                    };

                    using (AesManaged aes = GetAes(true, null))
                        using (CryptoStream cryptoStream = new CryptoStream(stream,
                                                                            aes.CreateDecryptor(), CryptoStreamMode.Read))
                            cryptoStream.Read(header, 0x00, headerLength - 0x08);
                    header = SkipData(header, 0x10);
                    reader = File.OpenReader(header);

                    farcMode = reader.RI32E(true);
                    ft       = farcMode == 0x10;
                }
            }

            if (Signature == Farc.FARC)
            {
                if (reader.RI32E(true) == 1)
                {
                    Files.Capacity = reader.RI32E(true);
                }
            }
            reader.RI32();

            if (Files.Capacity == 0)
            {
                int  Count    = 0;
                long Position = reader.PI64;
                while (reader.PI64 < headerLength)
                {
                    reader.NT();
                    reader.RI32();
                    if (Signature != Farc.FArc)
                    {
                        reader.RI32();
                    }
                    reader.RI32();
                    if (Signature == Farc.FARC && ft)
                    {
                        reader.RI32();
                    }
                    Count++;
                }
                reader.PI64    = Position;
                Files.Capacity = Count;
            }

            for (int i = 0; i < Files.Capacity; i++)
            {
                FARCFile file = default;
                file.Name   = reader.NTUTF8();
                file.Offset = reader.RI32E(true);
                if (Signature != Farc.FArc)
                {
                    file.SizeComp = reader.RI32E(true);
                }
                file.SizeUnc = reader.RI32E(true);
                if (Signature == Farc.FARC && ft)
                {
                    file.Type = (Type)reader.RI32E(true);
                }
                Files.Add(file);
            }

            reader.Dispose();
            return(true);
        }
示例#53
0
        /// <summary>
        /// Decrypts a string
        /// </summary>
        /// <param name="CipherTextBytes">Bytes 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 bytes</returns>
        public static byte[] Decrypt(
            byte[] CipherTextBytes,
            string Password,
            string Salt,
            string HashAlgorithm,
            int PasswordIterations,
            string InitialVector,
            int KeySize)
        {
            if ((Salt == null) || (Salt == ""))
            {
                Salt = "Nextcom123";
            }
            if ((HashAlgorithm == null) || (HashAlgorithm == ""))
            {
                HashAlgorithm = "SHA1";
            }
            if (PasswordIterations == 0)
            {
                PasswordIterations = 2;
            }
            if ((InitialVector == null) || (InitialVector == "") || (InitialVector.Length != 16))
            {
                InitialVector = "ANGh9M&op-*UL$W%";
            }
            if ((KeySize != 128) && (KeySize != 192) && (KeySize != 256))
            {
                PasswordIterations = 256;
            }

            if (CipherTextBytes == null)
            {
                return(null);
            }

            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);

            byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);

            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(PlainTextBytes);
        }
示例#54
0
        /// <summary>
        /// 解密文件
        /// </summary>
        /// <param name="inFile">待解密文件</param>
        /// <param name="outFile">解密后输出文件</param>
        /// <param name="password">解密密码</param>
        public static void DecryptFile(string inFile, string outFile, string password)
        {
            // 创建打开文件流
            using (FileStream fin = File.OpenRead(inFile),
                   fout = File.OpenWrite(outFile))
            {
                int    size     = (int)fin.Length;
                byte[] bytes    = new byte[BUFFER_SIZE];
                int    read     = -1;
                int    value    = 0;
                int    outValue = 0;

                byte[] IV = new byte[16];
                fin.Read(IV, 0, 16);
                byte[] salt = new byte[16];
                fin.Read(salt, 0, 16);

                SymmetricAlgorithm sma = DESFile.CreateRijndael(password, salt);
                sma.IV = IV;

                value = 32;
                long lSize = -1;

                // 创建散列对象, 校验文件
                HashAlgorithm hasher = SHA256.Create();

                using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
                       chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
                {
                    // 读取文件长度
                    BinaryReader br = new BinaryReader(cin);
                    lSize = br.ReadInt64();
                    ulong tag = br.ReadUInt64();

                    if (FC_TAG != tag)
                    {
                        throw new CryptoHelpException("文件被破坏");
                    }


                    long numReads = lSize / BUFFER_SIZE;

                    long slack = (long)lSize % BUFFER_SIZE;

                    for (int i = 0; i < numReads; ++i)
                    {
                        read = cin.Read(bytes, 0, bytes.Length);
                        fout.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        value    += read;
                        outValue += read;
                    }

                    if (slack > 0)
                    {
                        read = cin.Read(bytes, 0, (int)slack);
                        fout.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        value    += read;
                        outValue += read;
                    }

                    chash.Flush();
                    chash.Close();

                    fout.Flush();
                    fout.Close();

                    byte[] curHash = hasher.Hash;

                    // 获取比较和旧的散列对象
                    byte[] oldHash = new byte[hasher.HashSize / 8];
                    read = cin.Read(oldHash, 0, oldHash.Length);
                    if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash)))
                    {
                        throw new CryptoHelpException("文件被破坏");
                    }
                }

                if (outValue != lSize)
                {
                    throw new CryptoHelpException("文件大小不匹配");
                }
            }
        }
示例#55
0
    public static string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
    {
        // Convert strings defining encryption key characteristics into byte
        // arrays. Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

        // Convert our ciphertext into a byte array.
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

        // First, we must create a password, from which the key will be
        // derived. This password will be generated from the specified
        // passphrase and salt value. The password will be created using
        // the specified hash algorithm. Password creation can be done in
        // several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                        passPhrase,
                                                        saltValueBytes,
                                                        hashAlgorithm,
                                                        passwordIterations);

        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);

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

        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;

        // Generate decryptor from the existing key bytes and initialization
        // vector. Key size will be defined based on the number of the key
        // bytes.
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                         keyBytes,
                                                         initVectorBytes);

        // Define memory stream which will be used to hold encrypted data.
        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

        // Define cryptographic stream (always use Read mode for encryption).
        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 ciphertext;
        // plaintext is never longer than ciphertext.
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];

        // Start decrypting.
        int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                   0,
                                                   plainTextBytes.Length);

        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();

        // Convert decrypted data into a string.
        // Let us assume that the original plaintext string was UTF8-encoded.
        string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                   0,
                                                   decryptedByteCount);

        // Return decrypted string.
        return plainText;
    }
示例#56
0
 public override int Read(byte[] buffer, int offset, int count)
 {
     return(dec.Read(buffer, offset, count));
 }
示例#57
0
    string RJ256(byte[] key, byte[] IV, string data, bool flag)
    {
        RijndaelManaged myRijndael = new RijndaelManaged();

        // --
        myRijndael.Padding   = PaddingMode.Zeros;
        myRijndael.Mode      = CipherMode.ECB;
        myRijndael.KeySize   = 256;
        myRijndael.BlockSize = 256;
        // --

        string r;

        if(flag){ //Encrypt

            // data
            byte[] toEncryptData = System.Text.Encoding.UTF8.GetBytes(data);

            // key
            ICryptoTransform h = myRijndael.CreateEncryptor(key, IV);

            // create enc stream
            MemoryStream outp = new MemoryStream();
            CryptoStream inp  = new CryptoStream(outp, h, CryptoStreamMode.Write);

            // streaming
            inp.Write(toEncryptData, 0, toEncryptData.Length);
            inp.FlushFinalBlock();

            // get enc data with base64
            r = Convert.ToBase64String(outp.ToArray());

        }else{ // Decrypt

            // data with base64 decoding
            byte[] toDecryptData = Convert.FromBase64String(data);
            byte[] PlainData = new byte[toDecryptData.Length];

            // key
            ICryptoTransform h = myRijndael.CreateDecryptor(key, IV);

            // create dec stream
            MemoryStream inp  = new MemoryStream(toDecryptData);
            CryptoStream outp = new CryptoStream(inp, h, CryptoStreamMode.Read);

            // streaming
            outp.Read(PlainData, 0, PlainData.Length);

            // get dec data
            r = System.Text.Encoding.UTF8.GetString(PlainData);
        }

        return r;
    }
示例#58
0
        //Расшифровать файл
        private bool DecryptFileByte(string filepath, ProgressBar ProBar)
        {
            string[] temp     = filepath.Split('\\');                                     //Сплитим путь файла
            string   tempname = temp[temp.Length - 1];                                    //Берем имя фалй
            string   temppath = filepath.Substring(0, filepath.Length - tempname.Length); //Берем путь до директории файла

            FileStream fileOut = new FileStream(filepath, FileMode.Open);

            ProBar.Maximum = (int)fileOut.Length;

            //Проверяем ключи на сущестоввание
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            using (AesManaged aesAlg = new AesManaged())
            {
                //Задаем ключи
                aesAlg.KeySize = 256;
                aesAlg.Key     = key;
                aesAlg.IV      = IV;
                aesAlg.Padding = PaddingMode.ISO10126;

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                CryptoStream     csDecrypt = new CryptoStream(fileOut, decryptor, CryptoStreamMode.Read);

                byte[] userbyte = new byte[username.Length];
                csDecrypt.Read(userbyte, 0, userbyte.Length); //Расшифровываем имя пользователя
                string name = Encoding.Default.GetString(userbyte);
                if (name != username)                         //Если имя пользоватея из файла и текущее не совпадает
                {
                    MessageBox.Show("Файл зашифрован другим пользователем");
                    return(false);
                }
                else
                {
                    byte[] nameLen = new byte[1];
                    csDecrypt.Read(nameLen, 0, 1);           //Расшифровываем длинну имени файла
                    byte[] bytename = new byte[nameLen[0]];
                    csDecrypt.Read(bytename, 0, nameLen[0]); //Расшифровываем имя файла
                    string dename = Encoding.Default.GetString(bytename);

                    FileStream fileIn = new FileStream(temppath + "\\" + dename, FileMode.CreateNew);


                    int    readIn;
                    byte[] bufferin = new byte[1048576]; //Буфер по 1МБ

                    //Пока файл не кончится расшифровываем
                    while ((readIn = csDecrypt.Read(bufferin, 0, bufferin.Length)) > 0)
                    {
                        Application.DoEvents();
                        fileIn.Write(bufferin, 0, readIn);
                        ProBar.Value += readIn;
                    }
                    csDecrypt.Close();

                    fileOut.Close();
                    fileIn.Close();

                    return(true);
                }
            }
        }
        public static string Decrypt <T>(string value) where T : SymmetricAlgorithm, new()
        {
            if (!File.Exists(value))
            {
                byte[] vectorBytes = Encoding.ASCII.GetBytes(_vector);
                byte[] saltBytes   = Encoding.ASCII.GetBytes(_salt);
                byte[] valueBytes  = Convert.FromBase64String(value);

                byte[] decrypted;
                int    decryptedByteCount;

                using (var cipher = new T())
                {
                    var    passwordBytes = new PasswordDeriveBytes(_password, saltBytes, Hash, Iterations);
                    byte[] keyBytes      = passwordBytes.GetBytes(KeySize / 8);

                    cipher.Mode = CipherMode.CBC;

                    try
                    {
                        using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes))
                        {
                            using (var from = new MemoryStream(valueBytes))
                            {
                                using (var reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read))
                                {
                                    decrypted          = new byte[valueBytes.Length];
                                    decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        return(null);
                    }

                    cipher.Clear();
                }
                return(Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount));
            }
            else
            {
                byte[] vectorBytes = Encoding.ASCII.GetBytes(_vector);
                byte[] saltBytes   = Encoding.ASCII.GetBytes(_salt);

                using (var cipher = new T())
                {
                    var    passwordBytes = new PasswordDeriveBytes(_password, saltBytes, Hash, Iterations);
                    byte[] keyBytes      = passwordBytes.GetBytes(KeySize / 8);

                    var fsread = new FileStream(value, FileMode.Open, FileAccess.Read);

                    ICryptoTransform decrypt = cipher.CreateDecryptor(keyBytes, vectorBytes);

                    var cryptostreamDecr = new CryptoStream(fsread,
                                                            decrypt,
                                                            CryptoStreamMode.Read);

                    var fsDecrypted = new StreamWriter(value + "_d");
                    fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
                    fsDecrypted.Flush();
                    fsDecrypted.Close();

                    return(null);
                }
            }
        }
示例#60
0
        public byte[] FileReader(int i)
        {
            if (!HasFiles)
            {
                return(null);
            }
            if (i >= Files.Count)
            {
                return(null);
            }

            FARCFile file = Files[i];

            if (Signature != Farc.FARC)
            {
                if (Signature == Farc.FArC)
                {
                    using (MSIO.MemoryStream memorystream = new MSIO.MemoryStream(
                               File.ReadAllBytes(FilePath, file.SizeComp, file.Offset)))
                        using (GZipStream gZipStream = new GZipStream(memorystream, CompressionMode.Decompress))
                        {
                            file.Data = new byte[file.SizeUnc];
                            gZipStream.Read(file.Data, 0, file.SizeUnc);
                        }
                }
                else
                {
                    file.Data = File.ReadAllBytes(FilePath, file.SizeUnc, file.Offset);
                }
                Files[i] = file;
                return(file.Data);
            }

            int FileSize = (FARCType & Type.ECB) != 0 || (file.Type & Type.ECB) != 0 ?
                           file.SizeComp.A(0x10) : file.SizeComp;

            using (MSIO.FileStream stream = new MSIO.FileStream(FilePath, MSIO.FileMode.Open,
                                                                MSIO.FileAccess.ReadWrite, MSIO.FileShare.ReadWrite))
            {
                stream.Seek(file.Offset, 0);
                file.Data = new byte[FileSize];

                bool encrypted = false;
                if ((FARCType & Type.ECB) != 0)
                {
                    if ((ft && (file.Type & Type.ECB) != 0) || cbc)
                    {
                        using (AesManaged aes = GetAes(true, null))
                            using (CryptoStream cryptoStream = new CryptoStream(stream,
                                                                                aes.CreateDecryptor(), CryptoStreamMode.Read))
                                cryptoStream.Read(file.Data, 0, FileSize);
                        file.Data = SkipData(file.Data, 0x10);
                    }
                    else
                    {
                        using (AesManaged aes = GetAes(false, null))
                            using (CryptoStream cryptoStream = new CryptoStream(stream,
                                                                                aes.CreateDecryptor(), CryptoStreamMode.Read))
                                cryptoStream.Read(file.Data, 0, FileSize);
                    }
                    encrypted = true;
                }

                bool compressed = false;
                if (((ft && (file.Type & Type.GZip) != 0) ||
                     (FARCType & Type.GZip) != 0) && file.SizeUnc > 0)
                {
                    GZipStream gZipStream = new GZipStream(encrypted ? new MSIO.MemoryStream(file.Data) :
                                                           (MSIO.Stream)stream, CompressionMode.Decompress);
                    byte[] Temp = new byte[file.SizeUnc];
                    gZipStream.Read(Temp, 0, file.SizeUnc);
                    file.Data = Temp;
                    gZipStream.Dispose();
                    compressed = true;
                }

                if (!encrypted && !compressed)
                {
                    file.Data = new byte[file.SizeUnc];
                    stream.Read(file.Data, 0, file.SizeUnc);
                }
            }
            Files[i] = file;
            return(file.Data);
        }