Пример #1
2
    static Boolean TestKnownEnc(Aes aes, Byte[] Key, Byte[] IV, Byte[] Plain, Byte[] Cipher)
    {

        Byte[]  CipherCalculated;
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(Plain);
        Console.WriteLine("With the following Key:");
        PrintByteArray(Key);
        Console.WriteLine("and IV:");
        PrintByteArray(IV);
 		Console.WriteLine("Expecting this ciphertext:");
		PrintByteArray(Cipher);        
        
        ICryptoTransform sse = aes.CreateEncryptor(Key, IV);
        MemoryStream 	ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(Plain,0,Plain.Length);
        cs.FlushFinalBlock();
        CipherCalculated = ms.ToArray();
        cs.Close();

		Console.WriteLine("Computed this cyphertext:");
        PrintByteArray(CipherCalculated);
        

        if (!Compare(Cipher, CipherCalculated)) {
        	Console.WriteLine("ERROR: result is different from the expected");
        	return false;
        }
        
        Console.WriteLine("OK");
        return true;
    }
Пример #2
0
    /// <summary>
    /// Encrypt string using AES 128
    /// </summary>
    /// <param name="plaintext"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string Encrypt(string plaintext, string key)
    {
        byte[] keybytes = Encoding.UTF8.GetBytes(key);

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

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

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

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

        cs.FlushFinalBlock();

        byte[] cipherBytes = ms.ToArray();

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

        return Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
    }
Пример #3
0
    public static string Encrypt(this string text, string lKey)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey));
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV = aes.Key;
                using (MemoryStream encryptionStream = new MemoryStream())
                {
                    using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] cleanText = Encoding.UTF8.GetBytes(text);
                        encrypt.Write(cleanText, 0, cleanText.Length);
                        encrypt.FlushFinalBlock();
                    }

                    byte[] encryptedData = encryptionStream.ToArray();
                    string encryptedText = Convert.ToBase64String(encryptedData);


                    return encryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
    }
Пример #4
0
    public static string Decrypt(this string text, string lKey)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey));
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV = aes.Key;

                using (MemoryStream decryptionStream = new MemoryStream())
                {
                    using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] encryptedData = Convert.FromBase64String(text);


                        decrypt.Write(encryptedData, 0, encryptedData.Length);
                        decrypt.Flush();
                    }

                    byte[] decryptedData = decryptionStream.ToArray();
                    string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);


                    return decryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
    }
Пример #5
0
 /// <summary>
 /// Return stream to read encrypted file.
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 public static CryptoStream Decrypt(string path)
 {
     FileStream encryptReader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Delete);
     var returnStream = new CryptoStream(encryptReader, RMCrypto.CreateDecryptor(Key, IV), CryptoStreamMode.Read);
     Debug.Log("Return encrypt stream");
     return returnStream;
 }
Пример #6
0
 /// <summary>
 /// Return stream to write file in encrypted way.
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 public static CryptoStream Encrypt(string path)
 {
     FileStream encryptWriter = new FileStream(path, FileMode.Append,FileAccess.Write,FileShare.Delete);
     var returnStream = new CryptoStream(encryptWriter, RMCrypto.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
     Debug.Log("Return encrypt stream");
     return returnStream;
 }
    //This method is to encrypt the password given by user.
    public static string Encrypt(string data, string password)
    {
        if (String.IsNullOrEmpty(data))
            throw new ArgumentException("No data given");
        if (String.IsNullOrEmpty(password))
            throw new ArgumentException("No password given");

        // setup the encryption algorithm
        Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, 8);
        TripleDES tdes = TripleDES.Create();
        //Rijndael aes = Rijndael.Create();

        tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8);
        tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8);

        // encrypt the data
        byte[] rawData = Encoding.Unicode.GetBytes(data);
        using (MemoryStream memoryStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateEncryptor(), CryptoStreamMode.Write))
        {
            memoryStream.Write(keyGenerator.Salt, 0, keyGenerator.Salt.Length);
            cryptoStream.Write(rawData, 0, rawData.Length);
            cryptoStream.Close();

            byte[] encrypted = memoryStream.ToArray();
            return Convert.ToBase64String(encrypted);
        }
    }
Пример #8
0
    public static Boolean Test() {
    	String Text = "This is some test text";
    	
    	Console.WriteLine("Original text : "  + Text);
    	
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, new ToBase64Transform(), CryptoStreamMode.Write);
		cs.Write(Encoding.ASCII.GetBytes(Text), 0, Text.Length);
		cs.Close();
		
    	Console.WriteLine("Encoded : " + Encoding.ASCII.GetString(ms.ToArray()));

        MemoryStream ms1 = new MemoryStream();
        CryptoStream cs1 = new CryptoStream(ms1, new FromBase64Transform(), CryptoStreamMode.Write);
		cs1.Write(ms.ToArray(), 0, (int)ms.ToArray().Length);
		cs1.Close();
    		
    	Console.WriteLine("Decoded : " + Encoding.ASCII.GetString(ms1.ToArray()));

    	String mod = Encoding.ASCII.GetString((Byte[])ms.ToArray().Clone());
    	mod = mod.Insert(17, "\n").Insert(4, "  ").Insert(8,"\t");
    	Byte[] modified = Encoding.ASCII.GetBytes(mod);
    	
        MemoryStream ms2 = new MemoryStream();
        CryptoStream cs2 = new CryptoStream(ms2, new FromBase64Transform(), CryptoStreamMode.Write);
		cs2.Write(modified, 0, (int)modified.Length);
		cs2.Close();

    	Console.WriteLine("Decoded (with whitespaces) : " + Encoding.ASCII.GetString(ms2.ToArray()));
    	
    	if (!Compare(ms1.ToArray(), ms2.ToArray())) return false;
 
        return true;
    }
Пример #9
0
    //cmThe function used to decrypt the text
    private static string Decrypt(string strText, string SaltKey)
    {
        byte[] byKey = { };
        byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
        byte[] inputByteArray = new byte[strText.Length + 1];

        try
        {
            byKey = System.Text.Encoding.UTF8.GetBytes(SaltKey.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(strText);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;

            return encoding.GetString(ms.ToArray());

        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
Пример #10
0
    public static bool ForCodeCoverage()
    {
        AesManaged aes = new AesManaged();
        using (ICryptoTransform cte = aes.CreateEncryptor(), ctd = aes.CreateDecryptor())
        {
            byte[] plain1 = new byte[64];
            for (int i = 0; i < plain1.Length; i++)
                plain1[i] = (byte)i;

            byte[] encr1 = cte.TransformFinalBlock(plain1, 0, plain1.Length);
            using(MemoryStream ms = new MemoryStream())
            using(CryptoStream cs = new CryptoStream(ms, ctd, CryptoStreamMode.Write))
            {
                cs.Write(encr1, 0, 16);
                cs.Write(encr1, 16, 16);
                cs.Write(encr1, 32, 16);
                cs.Write(encr1, 48, encr1.Length-48);
                cs.FlushFinalBlock();
                byte[] plain2 = ms.ToArray();

                if (!Compare(plain1, plain2))
                {
                    Console.WriteLine("CodeCoverage case failed");
                    return false;
                }
                return true;
            }
        }
    }
Пример #11
0
        public static byte[] Decrypt(byte[] cipherText, string passPhrase,bool padding)
        {
            byte[] cipherTextBytes = cipherText;
            using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
            {
                byte[] keyBytes = password.GetBytes(keysize / 8);
                using (RijndaelManaged symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.Mode = CipherMode.CBC;
                    if(!padding)
                        symmetricKey.Padding = PaddingMode.None;
                    using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                    {
                        using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                        {

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

                        }
                    }
                }
            }
        }
Пример #12
0
	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();
    }
Пример #13
0
    // Decrypt a byte array into a byte array using a key and an IV
    public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
    {
        // Create a MemoryStream that is going to accept the decrypted bytes

        MemoryStream ms = new MemoryStream();

        // Create a symmetric algorithm.

        // We are going to use Rijndael because it is strong and available on all platforms.

        // You can use other algorithms, to do so substitute the next line with something like

        //                      TripleDES alg = TripleDES.Create();

        Rijndael alg = Rijndael.Create();

        // Now set the key and the IV.

        // We need the IV (Initialization Vector) because the algorithm is operating in its default

        // mode called CBC (Cipher Block Chaining). The IV is XORed with the first block (8 byte)

        // of the data after it is decrypted, and then each decrypted block is XORed with the previous

        // cipher block. This is done to make encryption more secure.

        // There is also a mode called ECB which does not need an IV, but it is much less secure.

        alg.Key = Key;

        alg.IV = IV;

        // Create a CryptoStream through which we are going to be pumping our data.

        // CryptoStreamMode.Write means that we are going to be writing data to the stream

        // and the output will be written in the MemoryStream we have provided.

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

        // Write the data and make it do the decryption

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

        // Close the crypto stream (or do FlushFinalBlock).

        // This will tell it that we have done our decryption and there is no more data coming in,

        // and it is now a good time to remove the padding and finalize the decryption process.

        cs.Close();

        // Now get the decrypted data from the MemoryStream.

        // Some people make a mistake of using GetBuffer() here, which is not the right way.

        byte[] decryptedData = ms.ToArray();

        return decryptedData;
    }
Пример #14
0
    public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
    {
        byte[] encryptedBytes = null;

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

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

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

        AES.Mode = CipherMode.CBC;

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

        return encryptedBytes;
        //end public byte[] AES_Encrypt
    }
Пример #15
0
    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);
    }
Пример #16
0
	public static string DecryptString(string input, string cryptographicProvider_PublicKey, string cryptographicProvider_IV)
	{
		try
		{
			input = input.Replace(CryptographicProviderKey, String.Empty);

			using (var dataString = new MemoryStream())
			{
				var service = new TripleDESCryptoServiceProvider().CreateDecryptor(Encoding.UTF8.GetBytes(cryptographicProvider_PublicKey),
				 Encoding.UTF8.GetBytes(cryptographicProvider_IV));
				using (var cryptoStream = new CryptoStream(dataString, service, CryptoStreamMode.Write))
				{
					var inputData = Convert.FromBase64String(input);
					cryptoStream.Write(inputData, 0, inputData.Length);
					cryptoStream.FlushFinalBlock();

					var dataResult = dataString.ToArray();
					var resultString = Encoding.UTF8.GetString(Convert.FromBase64String(Convert.ToBase64String(dataResult)));
					cryptoStream.Close();

					return resultString;

				}
			}

		}
		catch (Exception e)
		{
			return e.ToString();
		}

	}
    //This method is to decrypt the password given by user.
    public static string Decrypt(string data, string password)
    {
        if (String.IsNullOrEmpty(data))
            throw new ArgumentException("No data given");
        if (String.IsNullOrEmpty(password))
            throw new ArgumentException("No password given");

        byte[] rawData = Convert.FromBase64String(data.Replace(" ", "+"));
        if (rawData.Length < 8)
            throw new ArgumentException("Invalid input data");

        // setup the decryption algorithm
        byte[] salt = new byte[8];
        for (int i = 0; i < salt.Length; i++)
            salt[i] = rawData[i];

        Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, salt);

        TripleDES tdes = TripleDES.Create();
        //Rijndael aes = Rijndael.Create();

        tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8);
        tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8);
        // decrypt the data
        using (MemoryStream memoryStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateDecryptor(), CryptoStreamMode.Write))
        {
            cryptoStream.Write(rawData, 8, rawData.Length - 8);
            cryptoStream.Close();

            byte[] decrypted = memoryStream.ToArray();
            return Encoding.Unicode.GetString(decrypted);
        }
    }
Пример #18
0
    public static string Decrypt(byte[] key, byte[] iv, byte[] input)
    {
        if (key == null || iv == null || input == null)
        {
            return null;
        }

        // Create a memory stream to the passed buffer.
        MemoryStream ms = new MemoryStream(input);

        // Create a CryptoStream using the memory stream and the
        // CSP DES key.
        CryptoStream encStream = new CryptoStream(ms, m_desKey.CreateDecryptor(key, iv), CryptoStreamMode.Read);

        // Create a StreamReader for reading the stream.
        StreamReader sr = new StreamReader(encStream);

        // Read the stream as a string.
        string val = sr.ReadToEnd();

        // Close the streams.
        sr.Close();
        encStream.Close();
        ms.Close();

        return val;
    }
Пример #19
0
 /// <summary>
 /// 对文件内容进行DES解密
 /// </summary>
 /// <param name="sourceFile">待解密的文件绝对路径</param>
 /// <param name="destFile">解密后的文件保存的绝对路径</param>
 public static void DecryptFile(string sourceFile, string destFile)
 {
     if (!File.Exists(sourceFile)) throw new FileNotFoundException("指定的文件路径不存在!", sourceFile);
     byte[] btKey = Encoding.Default.GetBytes(key);
     byte[] btIV = Encoding.Default.GetBytes(iv);
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     byte[] btFile = File.ReadAllBytes(sourceFile);
     using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write))
     {
         try
         {
             using (CryptoStream cs = new CryptoStream(fs, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
             {
                 cs.Write(btFile, 0, btFile.Length);
                 cs.FlushFinalBlock();
             }
         }
         catch
         {
             throw;
         }
         finally
         {
             fs.Close();
         }
     }
 }
 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);
     }
 }
    /// <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;
    }
Пример #22
0
    public static string DecryptRijndael(string encryptedString)
    {
        byte[] encrypted;

        byte[] fromEncrypted;

        UTF8Encoding utf8Converter = new UTF8Encoding();

        encrypted = Convert.FromBase64String(encryptedString);

        RijndaelManaged myRijndael = new RijndaelManaged();

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

        MemoryStream ms = new MemoryStream(encrypted);

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

        fromEncrypted = new byte[encrypted.Length];

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

        string decryptedString = utf8Converter.GetString(fromEncrypted);
        int indexNull = decryptedString.IndexOf("\0");
        if (indexNull > 0)
        {
            decryptedString = decryptedString.Substring(0, indexNull);
        }
        return decryptedString;
    }
Пример #23
0
    internal static bool DecryptFile(string inputPath, string outputPath, string password)
    {
        var input = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
        var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write);

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

        algorithm.Mode = CipherMode.CBC;

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

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

        try
        {
        using (var decryptedStream = new CryptoStream(output, algorithm.CreateDecryptor(), CryptoStreamMode.Write))
        {
        CopyStream(input, decryptedStream);
        return true;
        }
        }
        catch (CryptographicException)
        {
        throw new InvalidDataException("Please supply a correct password");
        }
        catch (Exception ex)
        {
        throw new Exception(ex.Message);
        }
    }
Пример #24
0
        /// <summary>
        /// 对数据进行解密
        /// </summary>
        /// <param name="decryptstring">需要解密的数据</param>
        /// <returns></returns>
        public static string Decode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            try
            {
                DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
                MemoryStream ms = new MemoryStream(byEnc);
                CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
                StreamReader sr = new StreamReader(cst);
                return sr.ReadToEnd();
            }
            catch
            {
                return null;
            }

        }
Пример #25
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;
    }
Пример #26
0
	private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
	 {
	     //Create the file streams to handle the input and output files.
	     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
	     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
	     fout.SetLength(0);

	     //Create variables to help with read and write.
	     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
	     long rdlen = 0;              //This is the total number of bytes written.
	     long totlen = fin.Length;    //This is the total length of the input file.
	     int len;                     //This is the number of bytes to be written at a time.

	     SymmetricAlgorithm des = new DESCryptoServiceProvider();
         des.Padding = PaddingMode.PKCS7;
	     CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

	     Console.WriteLine("Encrypting...");

	     //Read from the input file, then encrypt and write to the output file.
	     while(rdlen < totlen)
	     {
	         len = fin.Read(bin, 0, 100);
	         encStream.Write(bin, 0, len);
	         rdlen = rdlen + len;
             Console.WriteLine("{0} bytes processed", rdlen);
         }
	     encStream.Close();
    }
Пример #27
0
    private string DeCryption(string content, string sKey, string sIV)
    {
        try
        {
            byte[] inputByteArray = Convert.FromBase64String(content);
            using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
            {
                //byte[] inputByteArray = Convert.FromBase64String(content);
                desProvider.Key = System.Text.Encoding.ASCII.GetBytes(sKey);
                desProvider.IV = System.Text.Encoding.ASCII.GetBytes(sIV);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms,desProvider.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    //cs.Clear();
                    cs.Write(inputByteArray,0,inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }

                string str = System.Text.Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }
        catch
        {
            return "String Not Base64 Encode!!!";
        }
    }
Пример #28
0
Файл: test.cs Проект: mono/gert
	static int Main ()
	{
		string filename = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
			"encrypt.tmp");
		string data = "this is sensitive data";

		DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
		des.GenerateIV ();
		des.GenerateKey ();

		// -----------  WRITING ENCRYPTED SERIALIZED DATA ------------------
		Stream stream = new FileStream (filename, FileMode.Create, FileAccess.Write);
		stream = new CryptoStream (stream, des.CreateEncryptor (), CryptoStreamMode.Write);
		BinaryFormatter bformatter = new BinaryFormatter ();
		bformatter.Serialize (stream, data);
		stream.Close ();

		stream = null;
		bformatter = null;
		data = string.Empty;

		// -----------  READING ENCRYPTED SERIALIZED DATA ------------------
		stream = new FileStream (filename, FileMode.Open, FileAccess.Read);
		stream = new CryptoStream (stream, des.CreateDecryptor (), CryptoStreamMode.Read);
		bformatter = new BinaryFormatter ();
		data = (string) bformatter.Deserialize (stream);
		stream.Close ();

		//----------- CHECK RESULTS ----------------
		if (data != "this is sensitive data")
			return 1;

		return 0;
	}
Пример #29
0
        private static byte[] encryptStringToBytes_AES(String plainText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Name");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("Name");
            }
            // Declare the streams used
            // to encrypt to an in memory
            // array of bytes.
            MemoryStream msEncrypt = null;
            CryptoStream csEncrypt = null;
            StreamWriter swEncrypt = null;
            // Declare the RijndaelManaged object
            // used to encrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the bytes used to hold the
            // encrypted data.
            //byte[] encrypted = null;
            try
            {
                // Create a RijndaelManaged object
                // with the specified SessionID and IV.
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = Key;
                aesAlg.IV  = IV;
                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for encryption.
                msEncrypt = new MemoryStream();
                csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
                swEncrypt = new StreamWriter(csEncrypt);
                //Write all data to the stream.
                swEncrypt.Write(plainText);
            }
            finally
            {
                // Clean things up.
                // Close the streams.
                if (swEncrypt != null)
                {
                    swEncrypt.Close();
                }
                if (csEncrypt != null)
                {
                    csEncrypt.Close();
                }
                if (msEncrypt != null)
                {
                    msEncrypt.Close();
                }
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }
            // Return the encrypted bytes from the memory stream.
            return(msEncrypt.ToArray());
        }
Пример #30
0
        private static String decryptStringFromBytes_AES_tostring(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Name");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("Name");
            }
            // TDeclare the streams used
            // to decrypt to an in memory
            // array of bytes.
            MemoryStream msDecrypt = null;
            CryptoStream csDecrypt = null;
            StreamReader srDecrypt = null;
            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;
            // Declare the String used to hold
            // the decrypted text.
            String plaintext = null;

            try
            {
                // Create a RijndaelManaged object
                // with the specified SessionID and IV.
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = Key;
                aesAlg.IV  = IV;
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.
                msDecrypt = new MemoryStream(cipherText);
                csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
                srDecrypt = new StreamReader(csDecrypt);
                // Read the decrypted bytes from the decrypting stream
                // and place them in a String.
                plaintext = srDecrypt.ReadToEnd();
            }
            finally
            {
                // Clean things up.
                // Close the streams.
                if (srDecrypt != null)
                {
                    srDecrypt.Close();
                }
                if (csDecrypt != null)
                {
                    csDecrypt.Close();
                }
                if (msDecrypt != null)
                {
                    msDecrypt.Close();
                }
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }
            return(plaintext);
        }
Пример #31
0
        private static byte[] decrypt_AES(byte[] data, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (Key.Length != 32)
            {
                throw new ArgumentNullException("Key");
            }
            if (data.Length < 1)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (IV.Length != 16)
            {
                throw new ArgumentNullException("IV");
            }
            // TDeclare the streams used
            // to decrypt to an in memory
            // array of bytes.
            MemoryStream msDecrypt = null;
            CryptoStream csDecrypt = null;
            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // the decrypted data.
            byte[] clear = null;
            try
            {
                // Create a RijndaelManaged object
                // with the specified SessionID and IV.
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = Key;
                aesAlg.IV  = IV;
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.
                msDecrypt = new MemoryStream(data);
                csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
                // Read the decrypted bytes from the decrypting stream
                clear = new byte[data.Length];
                csDecrypt.Read(clear, 0, data.Length);
            }
            finally
            {
                // Clean things up.
                // Close the streams.
                if (csDecrypt != null)
                {
                    csDecrypt.Close();
                }
                if (msDecrypt != null)
                {
                    msDecrypt.Close();
                }
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }
            return(clear);
        }
Пример #32
0
        private static byte[] encrypt_AES(byte[] data, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (Key.Length != 32)
            {
                throw new ArgumentNullException("Key");
            }
            if (data.Length < 1)
            {
                throw new ArgumentNullException("data");
            }
            if (IV.Length != 16)
            {
                throw new ArgumentNullException("IV");
            }
            // Declare the streams used
            // to encrypt to an in memory
            // array of bytes.
            MemoryStream msEncrypt = null;
            CryptoStream csEncrypt = null;
            // Declare the RijndaelManaged object
            // used to encrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the bytes used to hold the
            // encrypted data.
            //byte[] encrypted = null;
            try
            {
                // Create a RijndaelManaged object
                // with the specified SessionID and IV.
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = Key;
                aesAlg.IV  = IV;
                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for encryption.
                msEncrypt = new MemoryStream();
                csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
                //Write all data to the stream.
                csEncrypt.Write(data, 0, data.Length);
                csEncrypt.FlushFinalBlock();
            }
            finally
            {
                // Clean things up.
                // Close the streams.
                if (csEncrypt != null)
                {
                    csEncrypt.Close();
                }
                if (msEncrypt != null)
                {
                    msEncrypt.Close();
                }
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }
            // Return the encrypted bytes from the memory stream.
            return(msEncrypt.ToArray());
        }
Пример #33
0
 /// <summary>
 /// DES 加密
 /// </summary>
 /// <param name="Values">要加密的字符串</param>
 /// <returns>加密后的字符串</returns>
 public string DESEncrypt(string Values)
 {
     try
     {
         DESCryptoServiceProvider DesHash = new DESCryptoServiceProvider();
         DesHash.Mode = CipherMode.CBC;
         byte[] byt;
         if (null == this._Key)
         {
             DesHash.GenerateKey();
             _Key = Encoding.ASCII.GetString(DesHash.Key);
         }
         else
         {
             if (_Key.Length > 8)
             {
                 _Key = _Key.Substring(0, 8);
             }
             else
             {
                 for (int i = 8; i < _Key.Length; i--)
                 {
                     _Key += "0";
                 }
             }
         }
         if (null == this._IV)
         {
             DesHash.GenerateIV();
             _IV = Encoding.ASCII.GetString(DesHash.IV);
         }
         else
         {
             if (_IV.Length > 8)
             {
                 _IV = _IV.Substring(0, 8);
             }
             else
             {
                 for (int i = 8; i < _IV.Length; i--)
                 {
                     _IV += "0";
                 }
             }
         }
         //return _Key + ":" + Encoding.ASCII.GetBytes(_Key).Length.ToString() + "<br>"+ _IV + ":" + Encoding.ASCII.GetBytes(this._IV).Length.ToString();
         byt = Encoding.UTF8.GetBytes(Values);
         ICryptoTransform ct = DesHash.CreateEncryptor(Encoding.ASCII.GetBytes(this._Key), Encoding.ASCII.GetBytes(this._IV));
         DesHash.Clear();
         System.IO.MemoryStream ms = new System.IO.MemoryStream();
         CryptoStream           cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
         cs.Write(byt, 0, byt.Length);
         cs.FlushFinalBlock();
         cs.Close();
         return(Convert.ToBase64String(ms.ToArray()));
     }
     catch (System.Exception e)
     {
         throw new System.Exception("加密数据出错,详细原因:" + e.Message);
     }
 }
Пример #34
0
            private static Stream Decrypt(Stream stream, ExchangePrivateKey privateKey)
            {
                if (stream == null)
                {
                    throw new ArgumentNullException(nameof(stream));
                }
                if (privateKey == null)
                {
                    throw new ArgumentNullException(nameof(privateKey));
                }

                try
                {
                    int type = (int)Varint.GetUInt64(stream);

                    if (type == (int)ConvertCryptoAlgorithm.Aes256)
                    {
                        byte[] cryptoKey;

                        {
                            int length = (int)Varint.GetUInt64(stream);

                            var encryptedBuffer = new byte[length];
                            if (stream.Read(encryptedBuffer, 0, encryptedBuffer.Length) != encryptedBuffer.Length)
                            {
                                throw new ArgumentException();
                            }

                            cryptoKey = Exchange.Decrypt(privateKey, encryptedBuffer);
                        }

                        var iv = new byte[32];
                        stream.Read(iv, 0, iv.Length);

                        RecyclableMemoryStream outStream = null;

                        try
                        {
                            outStream = new RecyclableMemoryStream(_bufferManager);

                            using (var aes = Aes.Create())
                            {
                                aes.KeySize = 256;
                                aes.Mode    = CipherMode.CBC;
                                aes.Padding = PaddingMode.PKCS7;

                                using (var inStream = new RangeStream(stream, stream.Position, stream.Length - stream.Position, true))
                                    using (var cs = new CryptoStream(inStream, aes.CreateDecryptor(cryptoKey, iv), CryptoStreamMode.Read))
                                        using (var safeBuffer = _bufferManager.CreateSafeBuffer(1024 * 4))
                                        {
                                            int length;

                                            while ((length = cs.Read(safeBuffer.Value, 0, safeBuffer.Value.Length)) > 0)
                                            {
                                                outStream.Write(safeBuffer.Value, 0, length);
                                            }
                                        }
                            }

                            outStream.Seek(0, SeekOrigin.Begin);
                        }
                        catch (Exception)
                        {
                            if (outStream != null)
                            {
                                outStream.Dispose();
                            }

                            throw;
                        }

                        return(outStream);
                    }
                    else
                    {
                        throw new NotSupportedException();
                    }
                }
                catch (Exception e)
                {
                    throw new ArgumentException(e.Message, e);
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }
        public ActionResult Edit(Password password)
        {
            if (password.PasswordId == -1)
            {
                password.CreatedByUserId      = User.UserID;
                password.CreatedOnDate        = DateTime.UtcNow;
                password.LastModifiedByUserId = User.UserID;
                password.LastModifiedOnDate   = DateTime.UtcNow;
                string pwd1 = ModuleContext.Configuration.ModuleSettings["JTM2_PasswordManager_MasterPassword"].ToString();
                // Create a byte array to hold the random value.
                byte[] salt1 = new byte[SALT_LEN];
                using (RNGCryptoServiceProvider rngCsp = new
                                                         RNGCryptoServiceProvider())
                {
                    // Fill the array with a random value.
                    rngCsp.GetBytes(salt1);
                }

                //data1 can be a string or contents of a file.
                string data1 = password.PasswordPlainText;
                //The default iteration count is 1000 so the two methods use the same iteration count.
                try
                {
                    Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes(pwd1, salt1,
                                                                   NUM_PBKDF2_ITERS);
                    // Encrypt the data.
                    Aes encAlg = Aes.Create();
                    password.PasswordIV = encAlg.IV;

                    encAlg.Key = k1.GetBytes(KEY_LEN);
                    MemoryStream encryptionStream = new MemoryStream();
                    CryptoStream encrypt          = new CryptoStream(encryptionStream,
                                                                     encAlg.CreateEncryptor(), CryptoStreamMode.Write);
                    byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(
                        data1);

                    encrypt.Write(utfD1, 0, utfD1.Length);
                    encrypt.FlushFinalBlock();
                    encrypt.Close();
                    byte[] edata1 = encryptionStream.ToArray();
                    password.PasswordText = edata1;
                    k1.Reset();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: ", e);
                }

                password.PasswordSalt = salt1;

                password.PasswordPlainText = "";

                PasswordManager.Instance.CreatePassword(password);
            }
            else
            {
                var existingPassword = PasswordManager.Instance.GetPassword(password.PasswordId, password.ModuleId);
                existingPassword.LastModifiedByUserId = User.UserID;
                existingPassword.LastModifiedOnDate   = DateTime.UtcNow;
                existingPassword.PasswordSite         = password.PasswordSite;
                existingPassword.PasswordText         = password.PasswordText;
                existingPassword.PasswordUrl          = password.PasswordUrl;
                existingPassword.PasswordNotes        = password.PasswordNotes;
                existingPassword.PasswordPlainText    = "";
                existingPassword.PasswordIV           = password.PasswordIV;
                existingPassword.PasswordSalt         = password.PasswordSalt;

                existingPassword.AssignedUserId = password.AssignedUserId;

                PasswordManager.Instance.UpdatePassword(existingPassword);
            }

            return(RedirectToDefaultRoute());
        }
Пример #36
0
 public byte[] PublicFinalizeHashing(
     CryptoStream hashStream,
     byte[] salt) => base.FinalizeHashing(hashStream, salt);
Пример #37
0
 public byte[] PublicWriteSalt(
     CryptoStream hashStream,
     byte[] salt) => base.WriteSalt(hashStream, salt);
Пример #38
0
        public static String encryption(string plainText)
        {
            //Initial Setup:
            //------------------------------------------------------------------------------------------------------------------
            String ciphertext = "";

            //------------------------------------------------------------------------------------------------------------------


            //Do Initial Error Checking before encryption:
            //------------------------------------------------------------------------------------------------------------------
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentException("plaintext");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentException("key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentException("iv");
            }
            //------------------------------------------------------------------------------------------------------------------


            //Declare encrypted Byte Array:
            //------------------------------------------------------------------------------------------------------------------
            byte[] encrypted;
            //------------------------------------------------------------------------------------------------------------------


            //Encrypt plaintext:
            //------------------------------------------------------------------------------------------------------------------
            using (Rijndael rij = Rijndael.Create())
            {
                rij.Key = key;
                rij.IV  = iv;

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

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter westream = new StreamWriter(csEncrypt))
                        {
                            westream.Write(plainText);
                        } //END OF STREAM-WRITER.
                        encrypted = msEncrypt.ToArray();
                    }     //END OF CRYPTO_STREAM.
                }         //END OF MEMORY-STREAM.
            }             //END OF RIJNDAEL.
             //------------------------------------------------------------------------------------------------------------------


            //Convert Byte array to string:
            //------------------------------------------------------------------------------------------------------------------
            ciphertext = System.Text.Encoding.Default.GetString(encrypted);
            //------------------------------------------------------------------------------------------------------------------


            //Return Encrypted String:
            //------------------------------------------------------------------------------------------------------------------
            return(ciphertext);
            //------------------------------------------------------------------------------------------------------------------
        }//END OF ENCRYPTION FUNCTION.
Пример #39
0
        public async Task LocalOrchestrator_Interceptor_ShouldSerialize()
        {
            var dbNameSrv = HelperDatabase.GetRandomName("tcp_lo_srv");
            await HelperDatabase.CreateDatabaseAsync(ProviderType.Sql, dbNameSrv, true);

            var dbNameCli = HelperDatabase.GetRandomName("tcp_lo_cli");
            await HelperDatabase.CreateDatabaseAsync(ProviderType.Sql, dbNameCli, true);

            var csServer       = HelperDatabase.GetConnectionString(ProviderType.Sql, dbNameSrv);
            var serverProvider = new SqlSyncProvider(csServer);

            var csClient       = HelperDatabase.GetConnectionString(ProviderType.Sql, dbNameCli);
            var clientProvider = new SqlSyncProvider(csClient);

            await new AdventureWorksContext((dbNameSrv, ProviderType.Sql, serverProvider), true, false).Database.EnsureCreatedAsync();
            await new AdventureWorksContext((dbNameCli, ProviderType.Sql, clientProvider), true, false).Database.EnsureCreatedAsync();

            var scopeName = "scopesnap1";

            // Make a first sync to be sure everything is in place
            var agent = new SyncAgent(clientProvider, serverProvider, this.Tables, scopeName);

            // Making a first sync, will initialize everything we need
            var r = await agent.SynchronizeAsync();

            // Get the orchestrators
            var localOrchestrator  = agent.LocalOrchestrator;
            var remoteOrchestrator = agent.RemoteOrchestrator;

            // Server side : Create a product category and a product
            // Create a productcategory item
            // Create a new product on server
            var productId     = Guid.NewGuid();
            var productName   = HelperDatabase.GetRandomName();
            var productNumber = productName.ToUpperInvariant().Substring(0, 10);

            var productCategoryName = HelperDatabase.GetRandomName();
            var productCategoryId   = productCategoryName.ToUpperInvariant().Substring(0, 6);

            using (var ctx = new AdventureWorksContext((dbNameCli, ProviderType.Sql, clientProvider)))
            {
                var pc = new ProductCategory {
                    ProductCategoryId = productCategoryId, Name = productCategoryName
                };
                ctx.Add(pc);

                var product = new Product {
                    ProductId = productId, Name = productName, ProductNumber = productNumber
                };
                ctx.Add(product);

                await ctx.SaveChangesAsync();
            }


            // Defining options with Batchsize to enable serialization on disk
            agent.Options.BatchSize = 2000;

            var myRijndael = new RijndaelManaged();

            myRijndael.GenerateKey();
            myRijndael.GenerateIV();

            // Encrypting data on disk
            localOrchestrator.OnSerializingSet(ssa =>
            {
                // Create an encryptor to perform the stream transform.
                var encryptor = myRijndael.CreateEncryptor(myRijndael.Key, myRijndael.IV);

                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            var strSet = JsonConvert.SerializeObject(ssa.Set);
                            swEncrypt.Write(strSet);
                        }
                        ssa.Result = msEncrypt.ToArray();
                    }
                }
            });

            // Get changes to be populated to the server.
            // Should intercept the OnSerializing interceptor
            var changes = await localOrchestrator.GetChangesAsync();
        }
Пример #40
0
        public string Decrypt(string EncryptedValue)
        {
            Byte[] encryptedPasswordBytes = Convert.FromBase64String(EncryptedValue);

            Byte[] textBytes;

            String plainTextValue;

            UTF8Encoding encoder = new UTF8Encoding();


            // Perform Decryption

            //-------------------

            // Create an instances of the decryption algorithm (Rinjdael AES) for the encryption to perform,

            // a memory stream used to store the decrypted data temporarily, and

            // a crypto stream that performs the decryption algorithm.

            RijndaelManaged rmEncryption = new RijndaelManaged();

            MemoryStream myMemoryStream = new MemoryStream();

            CryptoStream myDecryptionStream = new CryptoStream(myMemoryStream, rmEncryption.CreateDecryptor(key, vector), CryptoStreamMode.Write);



            // Use the crypto stream to perform the decryption on the encrypted data in the byte array.

            myDecryptionStream.Write(encryptedPasswordBytes, 0, encryptedPasswordBytes.Length);

            myDecryptionStream.FlushFinalBlock();



            // Retrieve the decrypted data from the memory stream, and write it to a separate byte array.

            myMemoryStream.Position = 0;

            textBytes = new Byte[myMemoryStream.Length];

            myMemoryStream.Read(textBytes, 0, textBytes.Length);



            // Close all the streams.

            myDecryptionStream.Close();

            myMemoryStream.Close();



            // Convert the bytes to a string and display it.

            plainTextValue = encoder.GetString(textBytes);

            return(plainTextValue);
        }
Пример #41
0
 public async Task <byte[]> PublicWriteSaltAsync(
     CryptoStream hashStream,
     byte[] salt) => await base.WriteSaltAsync(hashStream, salt);
Пример #42
0
        /// <summary>
        /// Decrypt the given string.  Assumes the string was encrypted using
        /// EncryptStringAES(), using an identical sharedSecret.
        /// </summary>
        /// <param name="cipherText">The text to decrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
        public string DecryptStringAES(string cipherText, string sharedSecret, string inpSalt = null, int FromFETPIP = 0)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                throw new ArgumentNullException("cipherText");
            }
            if (string.IsNullOrEmpty(sharedSecret))
            {
                throw new ArgumentNullException("sharedSecret");
            }
            if (!string.IsNullOrEmpty(inpSalt))
            {
                //System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                //salt = encoding.GetBytes(inpSalt);

                // UNCOMMENT ME (below)
                salt = Encoding.ASCII.GetBytes(inpSalt + pepperEnc);
                //salt = Encoding.ASCII.GetBytes(inpSalt);
            }

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, salt);

                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg           = new RijndaelManaged();
                aesAlg.Padding   = PaddingMode.Zeros;
                aesAlg.BlockSize = 256;
                aesAlg.KeySize   = 256;
                aesAlg.Key       = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV        = key.GetBytes(aesAlg.BlockSize / 8);

                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.
                if (FromFETPIP == 1)
                {
                    byte[] bytes = Convert.FromBase64String(cipherText);
                    using (MemoryStream msDecrypt = new MemoryStream(bytes))
                    {
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                                // Read the decrypted bytes from the decrypting stream
                                // and place them in a string.
                                plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
                else
                {
                    SoapHexBinary shb   = SoapHexBinary.Parse(cipherText);
                    byte[]        bytes = shb.Value;

                    using (MemoryStream msDecrypt = new MemoryStream(bytes))
                    {
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                                // Read the decrypted bytes from the decrypting stream
                                // and place them in a string.
                                plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            return(plaintext.TrimEnd('\0'));  //  TrimEnd shouldn't be necessary but sometimes they're still there (it also gets stripped when inserted into dictionary in LogggedInMaster)
        }
Пример #43
0
        public static void DecryptFile(string inFile, string destinationFile)
        {
            Aes aes = Aes.Create();

            byte[] LenK  = new byte[4];
            byte[] LenIV = new byte[4];

            inFile = Path.ChangeExtension(inFile, extension);

            using (FileStream inFs = new FileStream(inFile, FileMode.Open))
            {
                inFs.Seek(0, SeekOrigin.Begin);
                inFs.Seek(0, SeekOrigin.Begin);
                inFs.Read(LenK, 0, 3);
                inFs.Seek(4, SeekOrigin.Begin);
                inFs.Read(LenIV, 0, 3);

                int lenK  = BitConverter.ToInt32(LenK, 0);
                int lenIV = BitConverter.ToInt32(LenIV, 0);

                int startC = lenK + lenIV + 8;
                int lenC   = (int)inFs.Length - startC;

                byte[] KeyEncrypted = new byte[lenK];
                byte[] IV           = new byte[lenIV];

                inFs.Seek(8, SeekOrigin.Begin);
                inFs.Read(KeyEncrypted, 0, lenK);
                inFs.Seek(8 + lenK, SeekOrigin.Begin);
                inFs.Read(IV, 0, lenIV);

                byte[] KeyDecrypted = rsa.Decrypt(KeyEncrypted, false);

                ICryptoTransform transform = aes.CreateDecryptor(KeyDecrypted, IV);

                using (FileStream outFs = new FileStream(destinationFile, FileMode.Create))
                {
                    int count  = 0;
                    int offset = 0;

                    int    blockSizeBytes = aes.BlockSize / 8;
                    byte[] data           = new byte[blockSizeBytes];

                    inFs.Seek(startC, SeekOrigin.Begin);
                    using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                    {
                        do
                        {
                            count   = inFs.Read(data, 0, blockSizeBytes);
                            offset += count;
                            outStreamDecrypted.Write(data, 0, count);
                        }while (count > 0);

                        outStreamDecrypted.FlushFinalBlock();
                        outStreamDecrypted.Close();
                    }
                    outFs.Close();
                }

                inFs.Close();
            }
        }
Пример #44
0
        /// <summary>
        /// DES 解密
        /// </summary>
        /// <param name="Values">加密后的字符串</param>
        /// <returns>解密后的字符串</returns>
        public string DeDESEncrypt(string Values)
        {
            try
            {
                byte[] buffer = Convert.FromBase64String(Values);
                DESCryptoServiceProvider DesHash = new DESCryptoServiceProvider();
                DesHash.Mode = CipherMode.CBC;

                #region 处理key ,iv
                if (null == this._Key)
                {
                    DesHash.GenerateKey();
                    _Key = Encoding.ASCII.GetString(DesHash.Key);
                }
                else
                {
                    if (_Key.Length > 8)
                    {
                        _Key = _Key.Substring(0, 8);
                    }
                    else
                    {
                        for (int i = 8; i < _Key.Length; i--)
                        {
                            _Key += "0";
                        }
                    }
                }
                if (null == this._IV)
                {
                    DesHash.GenerateIV();
                    _IV = Encoding.ASCII.GetString(DesHash.IV);
                }
                else
                {
                    if (_IV.Length > 8)
                    {
                        _IV = _IV.Substring(0, 8);
                    }
                    else
                    {
                        for (int i = 8; i < _IV.Length; i--)
                        {
                            _IV += "0";
                        }
                    }
                }
                #endregion


                System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
                ICryptoTransform       ct = DesHash.CreateDecryptor(Encoding.ASCII.GetBytes(this._Key), Encoding.ASCII.GetBytes(this._IV));
                DesHash.Clear();
                CryptoStream           cs = new CryptoStream(ms, ct, CryptoStreamMode.Read);
                System.IO.StreamReader sw = new System.IO.StreamReader(cs);
                return(sw.ReadToEnd());
            }
            catch (System.Exception e)
            {
                throw new System.Exception("解密数据出错,详细原因:" + e.Message);
            }
        }
Пример #45
0
        private static string pepperHash = "f7&eroisldkKDSlsaoei3(djfoOSIdkdleD24dkd";                      // Do Not Change

        /// <summary>
        /// Encrypt the given string using AES.  The string can be decrypted using
        /// DecryptStringAES().  The sharedSecret parameters must match.
        /// </summary>
        /// <param name="plainText">The text to encrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
        public string EncryptStringAES(string plainTextInp, string sharedSecret, string inpSalt = null, int intSomeValue = 0)
        {
            string plainText = plainTextInp.Trim();

            if (string.IsNullOrEmpty(plainText))
            {
                throw new ArgumentNullException("plainText");
            }
            if (string.IsNullOrEmpty(sharedSecret))
            {
                throw new ArgumentNullException("sharedSecret");
            }
            if (!string.IsNullOrEmpty(inpSalt))
            {
                //System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                //salt = encoding.GetBytes(inpSalt);


                salt = Encoding.ASCII.GetBytes(inpSalt + pepperEnc);
                //salt = Encoding.ASCII.GetBytes(inpSalt);
            }

            byte[]          encryptedData;
            string          outStr = null;              // Encrypted string to return
            RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, salt);

                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg           = new RijndaelManaged();
                aesAlg.Padding   = PaddingMode.Zeros;
                aesAlg.BlockSize = 256; // if want interoperability with AES then need block size of 128
                aesAlg.KeySize   = 256;
                aesAlg.Key       = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV        = key.GetBytes(aesAlg.BlockSize / 8);

                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        //csEncrypt.FlushFinalBlock();
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                            swEncrypt.Flush();
                        }
                    }
                    msEncrypt.Close();
                    if (intSomeValue == 1)
                    {
                        outStr = Convert.ToBase64String(msEncrypt.ToArray());
                    }
                    else
                    {
                        encryptedData = msEncrypt.ToArray();
                        SoapHexBinary shb = new SoapHexBinary(encryptedData);
                        outStr = shb.ToString();
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            // Return the encrypted bytes from the memory stream.
            return(outStr);
        }
Пример #46
0
        private async static Task File(string inFile, string outFile, RSACryptoServiceProvider key)
        {
            RSACryptoServiceProvider rsaPrivateKey = key;

            // Create instance of AesManaged for
            // symetric decryption of the data.
            using (AesManaged aesManaged = new AesManaged())
            {
                aesManaged.KeySize   = 256;
                aesManaged.BlockSize = 128;
                aesManaged.Mode      = CipherMode.CBC;

                // Create byte arrays to get the length of
                // the encrypted key and IV.
                // These values were stored as 4 bytes each
                // at the beginning of the encrypted package.
                byte[] LenK  = new byte[4];
                byte[] LenIV = new byte[4];

                // Consruct the file name for the decrypted file.

                // Use FileStream objects to read the encrypted
                // file (inFs) and save the decrypted file (outFs).
                using (FileStream inFs = new FileStream(inFile, FileMode.Open))
                {
                    inFs.Seek(0, SeekOrigin.Begin);
                    inFs.Seek(0, SeekOrigin.Begin);
                    await inFs.ReadAsync(LenK, 0, 3);

                    inFs.Seek(4, SeekOrigin.Begin);
                    await inFs.ReadAsync(LenIV, 0, 3);

                    // Convert the lengths to integer values.
                    int lenK  = BitConverter.ToInt32(LenK, 0);
                    int lenIV = BitConverter.ToInt32(LenIV, 0);

                    // Determine the start postition of
                    // the ciphter text (startC)
                    // and its length(lenC).
                    int startC = lenK + lenIV + 8;
                    int lenC   = (int)inFs.Length - startC;

                    // Create the byte arrays for
                    // the encrypted AesManaged key,
                    // the IV, and the cipher text.
                    byte[] KeyEncrypted = new byte[lenK];
                    byte[] IV           = new byte[lenIV];

                    // Extract the key and IV
                    // starting from index 8
                    // after the length values.
                    inFs.Seek(8, SeekOrigin.Begin);
                    await inFs.ReadAsync(KeyEncrypted, 0, lenK);

                    inFs.Seek(8 + lenK, SeekOrigin.Begin);
                    await inFs.ReadAsync(IV, 0, lenIV);

                    // Use RSACryptoServiceProvider
                    // to decrypt the AesManaged key.
                    byte[] KeyDecrypted = rsaPrivateKey.Decrypt(KeyEncrypted, false);

                    // Decrypt the key.
                    using (ICryptoTransform transform = aesManaged.CreateDecryptor(KeyDecrypted, IV))
                    {
                        // Decrypt the cipher text from
                        // from the FileSteam of the encrypted
                        // file (inFs) into the FileStream
                        // for the decrypted file (outFs).
                        using (FileStream outFs = new FileStream(outFile, FileMode.Create))
                        {
                            int count  = 0;
                            int offset = 0;

                            int    blockSizeBytes = aesManaged.BlockSize / 8;
                            byte[] data           = new byte[blockSizeBytes];

                            // By decrypting a chunk a time,
                            // you can save memory and
                            // accommodate large files.

                            // Start at the beginning
                            // of the cipher text.
                            inFs.Seek(startC, SeekOrigin.Begin);
                            using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                            {
                                do
                                {
                                    count = await inFs.ReadAsync(data, 0, blockSizeBytes);

                                    offset += count;
                                    await outStreamDecrypted.WriteAsync(data, 0, count);
                                }while (count > 0);
                            }
                        }
                    }
                }
            }
        }
Пример #47
0
            private static Stream Encrypt(Stream stream, ExchangePublicKey publicKey)
            {
                if (stream == null)
                {
                    throw new ArgumentNullException(nameof(stream));
                }
                if (publicKey == null)
                {
                    throw new ArgumentNullException(nameof(publicKey));
                }

                try
                {
                    RecyclableMemoryStream outStream = null;

                    try
                    {
                        outStream = new RecyclableMemoryStream(_bufferManager);
                        Varint.SetUInt64(outStream, (uint)ConvertCryptoAlgorithm.Aes256);

                        var cryptoKey = new byte[32];
                        var iv        = new byte[32];

                        using (var random = RandomNumberGenerator.Create())
                        {
                            random.GetBytes(cryptoKey);
                            random.GetBytes(iv);
                        }

                        {
                            var encryptedBuffer = Exchange.Encrypt(publicKey, cryptoKey);
                            Varint.SetUInt64(outStream, (uint)encryptedBuffer.Length);
                            outStream.Write(encryptedBuffer, 0, encryptedBuffer.Length);
                        }

                        outStream.Write(iv, 0, iv.Length);

                        using (var aes = Aes.Create())
                        {
                            aes.KeySize = 256;
                            aes.Mode    = CipherMode.CBC;
                            aes.Padding = PaddingMode.PKCS7;

                            using (var inStream = new WrapperStream(stream))
                                using (var cs = new CryptoStream(inStream, aes.CreateEncryptor(cryptoKey, iv), CryptoStreamMode.Read))
                                    using (var safeBuffer = _bufferManager.CreateSafeBuffer(1024 * 4))
                                    {
                                        int length;

                                        while ((length = cs.Read(safeBuffer.Value, 0, safeBuffer.Value.Length)) > 0)
                                        {
                                            outStream.Write(safeBuffer.Value, 0, length);
                                        }
                                    }
                        }

                        outStream.Seek(0, SeekOrigin.Begin);
                    }
                    catch (Exception)
                    {
                        if (outStream != null)
                        {
                            outStream.Dispose();
                        }

                        throw;
                    }

                    return(outStream);
                }
                catch (Exception e)
                {
                    throw new ArgumentException(e.Message, e);
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }
Пример #48
0
        public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null)
        {
            //User Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
                throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey");

            if (authKey == null || authKey.Length != KeyBitSize / 8)
                throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "authKey");

            if (secretMessage == null || secretMessage.Length < 1)
                throw new ArgumentException("Secret Message Required!", "secretMessage");

            //non-secret payload optional
            nonSecretPayload = nonSecretPayload ?? new byte[] { };

            byte[] cipherText;
            byte[] iv;

            using (var aes = new AesManaged
            {
                KeySize = KeyBitSize,
                BlockSize = BlockBitSize,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            })
            {

                //Use random IV
                aes.GenerateIV();
                iv = aes.IV;

                using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
                using (var cipherStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
                    using (var binaryWriter = new BinaryWriter(cryptoStream))
                    {
                        //Encrypt Data
                        binaryWriter.Write(secretMessage);
                    }

                    cipherText = cipherStream.ToArray();
                }

            }

            //Assemble encrypted message and add authentication
            using (var hmac = new HMACSHA256(authKey))
            using (var encryptedStream = new MemoryStream())
            {
                using (var binaryWriter = new BinaryWriter(encryptedStream))
                {
                    //Prepend non-secret payload if any
                    binaryWriter.Write(nonSecretPayload);
                    //Prepend IV
                    binaryWriter.Write(iv);
                    //Write Ciphertext
                    binaryWriter.Write(cipherText);
                    binaryWriter.Flush();

                    //Authenticate all data
                    var tag = hmac.ComputeHash(encryptedStream.ToArray());
                    //Postpend tag
                    binaryWriter.Write(tag);
                }
                return encryptedStream.ToArray();
            }

        }
Пример #49
0
        /// <summary>
        /// Decrypt the given string.  Assumes the string was encrypted using
        /// EncryptStringAES(), using an identical sharedSecret.
        /// </summary>
        /// <param name="cipherText">The text to decrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
        ///
        public static string DecryptStringAES(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                throw new ArgumentNullException("cipherText");
            }
            if (string.IsNullOrEmpty(sharedSecret))
            {
                throw new ArgumentNullException("sharedSecret");
            }

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create the streams used for decryption.
                byte[] bytes = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    // Create a RijndaelManaged object
                    // with the specified key and IV.
                    aesAlg     = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    // Get the initialization vector from the encrypted stream
                    aesAlg.IV = ReadByteArray(msDecrypt);
                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            return(plaintext);
        }
Пример #50
0
        // This is the only method about exchange data between this software and AirVPN infrastructure.
        // We don't use SSL. Useless layer in our case, and we need to fetch hostname and direct IP that don't permit common-name match.

        // 'S' is the AES 256 bit one-time session key, crypted with a RSA 4096 public-key.
        // 'D' is the data from the client to our server, crypted with the AES.
        // The server answer is XML decrypted with the same AES session.
        public static XmlDocument FetchUrl(string authPublicKey, string url, Dictionary <string, string> parameters)
        {
            // AES
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.KeySize = 256;
                rijAlg.GenerateKey();
                rijAlg.GenerateIV();

                // Generate S

                // Bug workaround: Xamarin 6.1.2 macOS throw an 'Default constructor not found for type System.Diagnostics.FilterElement' error.
                // in 'new System.Xml.Serialization.XmlSerializer', so i avoid that.

                /*
                 * StringReader sr = new System.IO.StringReader(authPublicKey);
                 * System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                 * RSAParameters publicKey = (RSAParameters)xs.Deserialize(sr);
                 */
                RSAParameters publicKey        = new RSAParameters();
                XmlDocument   docAuthPublicKey = new XmlDocument();
                docAuthPublicKey.LoadXml(authPublicKey);
                publicKey.Modulus  = Convert.FromBase64String(docAuthPublicKey.DocumentElement["Modulus"].InnerText);
                publicKey.Exponent = Convert.FromBase64String(docAuthPublicKey.DocumentElement["Exponent"].InnerText);

                Dictionary <string, byte[]> assocParamS = new Dictionary <string, byte[]>();
                assocParamS["key"] = rijAlg.Key;
                assocParamS["iv"]  = rijAlg.IV;

                byte[] bytesParamS = null;
                using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                {
                    csp.ImportParameters(publicKey);
                    bytesParamS = csp.Encrypt(UtilsCore.AssocToUtf8Bytes(assocParamS), false);
                }

                // Generate D

                byte[] aesDataIn   = UtilsCore.AssocToUtf8Bytes(parameters);
                byte[] bytesParamD = null;

                {
                    MemoryStream aesCryptStream  = null;
                    CryptoStream aesCryptStream2 = null;

                    try
                    {
                        aesCryptStream = new MemoryStream();
                        using (ICryptoTransform aesEncryptor = rijAlg.CreateEncryptor())
                        {
                            aesCryptStream2 = new CryptoStream(aesCryptStream, aesEncryptor, CryptoStreamMode.Write);
                            aesCryptStream2.Write(aesDataIn, 0, aesDataIn.Length);
                            aesCryptStream2.FlushFinalBlock();

                            bytesParamD = aesCryptStream.ToArray();
                        }
                    }
                    finally
                    {
                        if (aesCryptStream2 != null)
                        {
                            aesCryptStream2.Dispose();
                        }
                        else if (aesCryptStream != null)
                        {
                            aesCryptStream.Dispose();
                        }
                    }
                }

                // HTTP Fetch
                HttpRequest request = new HttpRequest();
                request.Url             = url;
                request.Parameters["s"] = UtilsString.Base64Encode(bytesParamS);
                request.Parameters["d"] = UtilsString.Base64Encode(bytesParamD);

                HttpResponse response = Engine.Instance.FetchUrl(request);

                try
                {
                    byte[] fetchResponse      = response.BufferData;
                    byte[] fetchResponsePlain = null;

                    MemoryStream aesDecryptStream  = null;
                    CryptoStream aesDecryptStream2 = null;

                    // Decrypt answer

                    try
                    {
                        aesDecryptStream = new MemoryStream();
                        using (ICryptoTransform aesDecryptor = rijAlg.CreateDecryptor())
                        {
                            aesDecryptStream2 = new CryptoStream(aesDecryptStream, aesDecryptor, CryptoStreamMode.Write);
                            aesDecryptStream2.Write(fetchResponse, 0, fetchResponse.Length);
                            aesDecryptStream2.FlushFinalBlock();

                            fetchResponsePlain = aesDecryptStream.ToArray();
                        }
                    }
                    finally
                    {
                        if (aesDecryptStream2 != null)
                        {
                            aesDecryptStream2.Dispose();
                        }
                        else if (aesDecryptStream != null)
                        {
                            aesDecryptStream.Dispose();
                        }
                    }

                    string finalData = System.Text.Encoding.UTF8.GetString(fetchResponsePlain);

                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(finalData);
                    return(doc);
                }
                catch (Exception ex)
                {
                    string message = "";
                    if (response.GetHeader("location") != "")
                    {
                        message = MessagesFormatter.Format(Messages.ManifestFailedUnexpected302, response.GetHeader("location"));
                    }
                    else
                    {
                        message = ex.Message + " - " + response.GetLineReport();
                    }
                    throw new Exception(message);
                }
            }
        }
Пример #51
0
        private List <DomainUserViewModel> FindAllADUsers(int id, string userName)// GetAllADUsers(int id, string UseName)
        {
            try
            {
                string cipherText = "";
                IQueryable <DomainSetting> domainSetting = _context.DomainSetting.Where(w => w.Id == id);

                var domain = domainSetting.Select(w => new DomainSetting
                {
                    UserName = w.UserName,
                    Server   = w.Server,
                    Title    = w.Title,
                    Password = w.Password
                }).FirstOrDefault();
                string EncryptionKey = "MAKV2SPBNI99212";
                byte[] cipherBytes   = Convert.FromBase64String(domain.Password);
                using (Aes encryptor = Aes.Create())
                {
                    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV  = pdb.GetBytes(16);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(cipherBytes, 0, cipherBytes.Length);
                            cs.Close();
                        }
                        cipherText = Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
                List <DomainUserViewModel> lstADUsers     = new List <DomainUserViewModel>();
                DomainUserViewModel        objSurveyUsers = new DomainUserViewModel();
                DomainSettingViewModel     SelectAll      = new DomainSettingViewModel();
                string   dcString = "";
                string   rootNode = "";
                string[] arrString;
                arrString = domain.Title.Split('.');
                if (arrString.Length == 1)
                {
                    dcString = "dc=" + domain.Title + "";
                    rootNode = arrString[0];
                }
                else
                {
                    for (int i = 0; i != arrString.Length; i++)
                    {
                        dcString += "dc=" + arrString[i].ToString() + ",";
                    }
                    if (arrString.Length == 3)
                    {
                        rootNode = arrString[1].ToString();
                    }
                    else if (arrString.Length == 2)
                    {
                        rootNode = arrString[0].ToString();
                    }
                    dcString = dcString.Substring(0, dcString.Length - 1);
                }
                try
                {
                    string DomainPath = "LDAP://" + domain.Server + "/" + dcString;
                    System.DirectoryServices.DirectoryEntry searchRoot = new System.DirectoryServices.DirectoryEntry(DomainPath);
                    searchRoot.Username = domain.UserName;
                    searchRoot.Password = cipherText;
                    DirectorySearcher search = new DirectorySearcher(searchRoot);
                    if (userName == "*")
                    {
                        search.Filter = $"(objectClass=user)";
                    }
                    else
                    {
                        userName      = userName.Split("@")[0];
                        search.Filter = $"(samaccountname=*{userName}*)";
                    }

                    search.PropertiesToLoad.Add("samaccountname");
                    search.PropertiesToLoad.Add("mail");
                    search.PropertiesToLoad.Add("usergroup");
                    search.PropertiesToLoad.Add("displayname"); //first name
                    search.PropertiesToLoad.Add("givenname");   //first name
                    search.PropertiesToLoad.Add("sn");          //first name
                    SearchResult resultFetch;


                    SearchResultCollection resultCol = search.FindAll();
                    if (resultCol != null)
                    {
                        for (int counter = 0; counter < resultCol.Count; counter++)
                        {
                            string UserNameEmailString = string.Empty;
                            resultFetch = resultCol[counter];
                            if (resultFetch.Properties.Contains("samaccountname"))
                            {
                                objSurveyUsers = new DomainUserViewModel();
                                if (resultFetch.Properties.Contains("mail"))
                                {
                                    objSurveyUsers.Email = (String)resultFetch.Properties["mail"][0];
                                }
                                else
                                {
                                    //  objSurveyUsers.Email = (String)resultFetch.Properties["samaccountname"][0] + id.ToString() + "@Pointer.com";
                                }

                                if (resultFetch.Properties.Contains("displayname"))
                                {
                                    objSurveyUsers.DisplayName = (String)resultFetch.Properties["displayname"][0];
                                }
                                else
                                {
                                    objSurveyUsers.DisplayName = (String)resultFetch.Properties["samaccountname"][0];
                                }


                                objSurveyUsers.UserName = (String)resultFetch.Properties["samaccountname"][0];

                                if (resultFetch.Properties.Contains("givenname"))
                                {
                                    objSurveyUsers.FirstName = (String)resultFetch.Properties["givenname"][0];
                                }
                                else
                                {
                                    objSurveyUsers.FirstName = (String)resultFetch.Properties["samaccountname"][0];
                                }
                                if (resultFetch.Properties.Contains("sn"))
                                {
                                    objSurveyUsers.LastName = (String)resultFetch.Properties["sn"][0];
                                }
                                else
                                {
                                    objSurveyUsers.LastName = (String)resultFetch.Properties["samaccountname"][0];
                                }
                                objSurveyUsers.dcString = dcString;
                                lstADUsers.Add(objSurveyUsers);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }
                return(lstADUsers);
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
                return(null);
            }
        }
Пример #52
0
 public SaveSystemSymmetricCryptoStream(CryptoStream cryptoStream, SymmetricAlgorithm algorithm, ICryptoTransform cryptoTransform) : base(cryptoStream)
 {
     this.Algorithm       = algorithm;
     this.CryptoTransform = cryptoTransform;
 }
Пример #53
0
        /// <summary>
        /// Writes the value of 'LicenseString' as an encrypted stream to the file:stream specified
        /// by 'currentFile'.
        /// </summary>
        /// <param name="currentFile">Fully qualified path to the alternate stream</param>
        /// <param name="LicenseString">The string value to encrypt and write to the alternate stream</param>
        public static void WriteAlternateStreamEncrypted(string currentFile, string LicenseString)
        {
            RC2CryptoServiceProvider rc2 = null;
            CryptoStream             cs  = null;
            MemoryStream             ms  = null;
            uint   count  = 0;
            IntPtr buffer = IntPtr.Zero;
            IntPtr hFile  = IntPtr.Zero;

            try
            {
                Encoding enc = Encoding.Unicode;

                byte[] ba = enc.GetBytes(LicenseString);
                ms = new MemoryStream();

                rc2     = new RC2CryptoServiceProvider();
                rc2.Key = GetBytesFromHexString("7a6823a42a3a3ae27057c647db812d0");
                rc2.IV  = GetBytesFromHexString("827d961224d99b2d");

                cs = new CryptoStream(ms, rc2.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(ba, 0, ba.Length);
                cs.FlushFinalBlock();

                buffer = Marshal.AllocHGlobal(1000 * sizeof(char));
                ZeroMemory(buffer, 1000 * sizeof(char));
                uint nBytes = (uint)ms.Length;
                Marshal.Copy(ms.GetBuffer(), 0, buffer, (int)nBytes);

                DeleteFile(currentFile);
                hFile = CreateFile(currentFile, Win32ApiConstant.GENERIC_WRITE, 0, IntPtr.Zero,
                                   Win32ApiConstant.CREATE_ALWAYS, 0, IntPtr.Zero);
                if (-1 != hFile.ToInt32())
                {
                    bool bRtn = WriteFile(hFile, buffer, nBytes, out count, 0);
                }
                else
                {
                    Exception excptn = new Win32Exception(Marshal.GetLastWin32Error());
                    if (!excptn.Message.Contains("cannot find the file"))
                    {
                        throw excptn;
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("WriteAlternateStreamEncrypted()");
                Console.WriteLine(exception.Message);
            }
            finally
            {
                CloseHandle(hFile);
                hFile = IntPtr.Zero;
                if (cs != null)
                {
                    cs.Close();
                    cs.Dispose();
                }

                rc2 = null;
                if (ms != null)
                {
                    ms.Close();
                    ms.Dispose();
                }
                if (buffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buffer);
                }
            }
        }
Пример #54
0
        ///

        /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
        ///

        ///

        /// Base64-formatted ciphertext value.
        ///
        ///

        /// 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.
        ///
        ///

        /// 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.
        ///
        ///

        /// Hash algorithm used to generate password. Allowed values are: “MD5? and
        /// “SHA1?. SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        ///
        ///

        /// Number of iterations used to generate password. One or two iterations
        /// should be enough.
        ///
        ///

        /// 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.
        ///
        ///

        /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
        /// Longer keys are more secure than shorter keys.
        ///
        ///
        /// Decrypted string value.
        ///
        ///
        /// 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.
        ///
        public static string Decrypt(string cipherText, string iVector)
        {
            initVector = iVector;

            // 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);
        }
        /// <summary>
        /// Decrypt the Text
        /// </summary>
        /// <param name="value">Value to be decrypted</param>
        /// <returns>Decrypted Value</returns>
        public byte[] Decrypt(byte[] value)
        {
            byte[] cipherText = value;
            byte[] retVal     = null;
            // TDeclare the streams used
            // to decrypt to an in memory
            // array of bytes.
            MemoryStream msDecrypt = null;
            CryptoStream csDecrypt = null;
            StreamReader srDecrypt = null;

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            //char[] plaintext = null;

            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = SecureKey.key;
                aesAlg.IV  = SecureKey.vector;

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

                // Create the streams used for decryption.
                msDecrypt = new MemoryStream(cipherText);
                csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
                srDecrypt = new StreamReader(csDecrypt);

                // Read the decrypted bytes from the decrypting stream
                // and place them in a string.
                //plaintext = srDecrypt.ReadToEnd().ToCharArray();
                //retVal = srDecrypt.CurrentEncoding.GetBytes(srDecrypt.ReadToEnd());
                retVal = CharArrayToByteArray(srDecrypt.ReadToEnd().ToCharArray());
            }
            finally
            {
                // Clean things up.

                // Close the streams.
                if (srDecrypt != null)
                {
                    srDecrypt.Close();
                }
                if (csDecrypt != null)
                {
                    csDecrypt.Close();
                }
                if (msDecrypt != null)
                {
                    msDecrypt.Close();
                }

                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            //log.Log(Level.ALL, value + " => " + plaintext);


            return(retVal);
        }
Пример #56
0
        public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0)
        {

            //Basic Usage Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
                throw new ArgumentException(String.Format("CryptKey needs to be {0} bit!", KeyBitSize), "cryptKey");

            if (authKey == null || authKey.Length != KeyBitSize / 8)
                throw new ArgumentException(String.Format("AuthKey needs to be {0} bit!", KeyBitSize), "authKey");

            if (encryptedMessage == null || encryptedMessage.Length == 0)
                throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");

            using (var hmac = new HMACSHA256(authKey))
            {
                var sentTag = new byte[hmac.HashSize / 8];
                //Calculate Tag
                var calcTag = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length);
                var ivLength = (BlockBitSize / 8);

                //if message length is to small just return null
                if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength)
                    return null;

                //Grab Sent Tag
                Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length);

                //Compare Tag with constant time comparison
                var compare = 0;
                for (var i = 0; i < sentTag.Length; i++)
                    compare |= sentTag[i] ^ calcTag[i];

                //if message doesn't authenticate return null
                if (compare != 0)
                    return null;

                using (var aes = new AesManaged
                {
                    KeySize = KeyBitSize,
                    BlockSize = BlockBitSize,
                    Mode = CipherMode.CBC,
                    Padding = PaddingMode.PKCS7
                })
                {

                    //Grab IV from message
                    var iv = new byte[ivLength];
                    Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);

                    using (var decrypter = aes.CreateDecryptor(cryptKey, iv))
                    using (var plainTextStream = new MemoryStream())
                    {
                        using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write))
                        using (var binaryWriter = new BinaryWriter(decrypterStream))
                        {
                            //Decrypt Cipher Text from Message
                            binaryWriter.Write(
                              encryptedMessage,
                              nonSecretPayloadLength + iv.Length,
                              encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length
                            );
                        }
                        //Return Plain Text
                        return plainTextStream.ToArray();
                    }
                }
            }
        }
Пример #57
0
        private void personSendBtn_Click(object sender, EventArgs e)
        {
            bool person1To2 = int.Parse(((Button)sender).Tag.ToString()) == 1;

            string messageToSend = person1To2 ? txt_Giden_Mesaj_Kul_1.Text : txt_Giden_Mesaj_Kul_2.Text;

            if (person1PublicKey == null || person1PublicKey.Length <= 0)
            {
                GenerateKeys();
            }

            // Gönderiliyor

            using (Aes aes = new AesCryptoServiceProvider())
            {
                aes.Key = commonKey;

                if (IV == null || IV.Length <= 0)
                {
                    IV = aes.IV;
                }
                else
                {
                    aes.IV = IV;
                }

                ECDiffieHellmanCng_Class.txt_Ortak_Anahtar = Convert.ToBase64String(IV);
                txt_Baslatma_Vektoru_IV.Text = Convert.ToBase64String(IV);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] plainTextMessage = Encoding.UTF8.GetBytes(messageToSend);
                        cs.Write(plainTextMessage, 0, plainTextMessage.Length);
                        cs.Close();

                        if (person1To2)
                        {
                            encryptedMessage1 = ms.ToArray();
                            txt_Sifreli_Gelen_Mesaj_kul_2.Text = Convert.ToBase64String(encryptedMessage1);
                        }
                        else
                        {
                            encryptedMessage2 = ms.ToArray();
                            txt_Sifreli_Gelen_Mesaj_kul_1.Text = Convert.ToBase64String(encryptedMessage2);
                        }
                    }
                }
            }

            // Alınıyor

            using (Aes aes = new AesCryptoServiceProvider())
            {
                aes.Key = commonKey;
                aes.IV  = IV;

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        if (person1To2)
                        {
                            cs.Write(encryptedMessage1, 0, encryptedMessage1.Length);
                        }
                        else
                        {
                            cs.Write(encryptedMessage2, 0, encryptedMessage2.Length);
                        }

                        cs.Close();

                        string receivedMessage = Encoding.UTF8.GetString(ms.ToArray());

                        if (person1To2)
                        {
                            txt_Gelen_Mesaj_Kul_2.Text = receivedMessage;
                        }
                        else
                        {
                            txt_Gelen_Mesaj_Kul_1.Text = receivedMessage;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Encrypt the text
        /// </summary>
        /// <param name="value">Value to be encrypted</param>
        /// <returns>Encrypted Value</returns>
        public string Encrypt(string value)
        {
            // Declare the streams used
            // to encrypt to an in memory
            // array of bytes.
            MemoryStream msEncrypt = null;
            CryptoStream csEncrypt = null;
            StreamWriter swEncrypt = null;

            // Declare the RijndaelManaged object
            // used to encrypt the data.
            RijndaelManaged aesAlg = null;

            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = SecureKey.key;
                aesAlg.IV  = SecureKey.vector;


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

                // Create the streams used for encryption.
                msEncrypt = new MemoryStream();
                csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
                swEncrypt = new StreamWriter(csEncrypt);

                //Write all data to the stream.
                swEncrypt.Write(value);
                //int chunkSize = 3145728;
                //StringBuilder chunkData = null;
                //for (int i = 0; i < value.Length; i += chunkSize)
                //{
                //    chunkData = new StringBuilder(Util.GetValueOfString(value.Substring(i, chunkSize)));
                //    swEncrypt.Write(chunkData.ToString());
                //}
            }
            finally
            {
                // Clean things up.

                // Close the streams.
                if (swEncrypt != null)
                {
                    swEncrypt.Close();
                }
                if (csEncrypt != null)
                {
                    csEncrypt.Close();
                }
                if (msEncrypt != null)
                {
                    msEncrypt.Close();
                }

                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            // Return the encrypted bytes from the memory stream.
            byte[] bFinal = msEncrypt.ToArray();
            if (swEncrypt != null)
            {
                swEncrypt = null;
            }
            if (csEncrypt != null)
            {
                csEncrypt = null;
            }
            if (msEncrypt != null)
            {
                msEncrypt = null;
            }
            string encString = ByteArrayToString(bFinal);

            log.Log(Level.ALL, value + " => " + encString);
            return(encString);
        }
Пример #59
-1
    public static string EncryptRijndael(string original)
    {
        byte[] encrypted;

        byte[] toEncrypt;

        UTF8Encoding utf8Converter = new UTF8Encoding();

        toEncrypt = utf8Converter.GetBytes(original);

        RijndaelManaged myRijndael = new RijndaelManaged();

        MemoryStream ms = new MemoryStream();

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

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

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

        cs.FlushFinalBlock();

        encrypted = ms.ToArray();

        string encryptedString = Convert.ToBase64String(encrypted);

        return encryptedString;
    }
Пример #60
-1
        public static string Decrypt(string cipherText)
        {

            try
            {
                string EncryptionKey = "MAKV2SPBNI99212";
                cipherText = cipherText.Replace(" ", "+");
                byte[] cipherBytes = Convert.FromBase64String(cipherText);
                using (Aes encryptor = Aes.Create())
                {
                    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV = pdb.GetBytes(16);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(cipherBytes, 0, cipherBytes.Length);
                            cs.Close();
                        }
                        cipherText = Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
                return cipherText;
            }
            catch (Exception ex)
            {

                return "0";
            }
        }