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

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

        return writer.ToString();
    }
コード例 #2
0
ファイル: AesCalculator.cs プロジェクト: relaxar/bin.net
    // Encrypt a string into a string using a password
    //    Uses Encrypt(byte[], byte[], byte[])
    public static string Encrypt(string clearText, string Password)
    {
        // First we need to turn the input string into a byte array.
        byte[] clearBytes =
          System.Text.Encoding.Unicode.GetBytes(clearText);
        // Then, we need to turn the password into Key and IV
        // We are using salt to make it harder to guess our key
        // using a dictionary attack -
        // trying to guess a password by enumerating all possible words.
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
        // Now get the key/IV and do the encryption using the
        // function that accepts byte arrays.
        // Using PasswordDeriveBytes object we are first getting
        // 32 bytes for the Key
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV.
        // IV should always be the block size, which is by default
        // 16 bytes (128 bit) for Rijndael.
        // If you are using DES/TripleDES/RC2 the block size is
        // 8 bytes and so should be the IV size.
        // You can also read KeySize/BlockSize properties off
        // the algorithm to find out the sizes.
        byte[] encryptedData = Encrypt(clearBytes,
                 pdb.GetBytes(32), pdb.GetBytes(16));

        // Now we need to turn the resulting byte array into a string.
        // A common mistake would be to use an Encoding class for that.
        //It does not work because not all byte values can be
        // represented by characters.
        // We are going to be using Base64 encoding that is designed
        //exactly for what we are trying to do.
        return Convert.ToBase64String(encryptedData);
    }
コード例 #3
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);
    }
コード例 #4
0
 /// <summary>
 /// Decrypts a Base64 encoded string previously generated with a specific crypt class, returns a string
 /// </summary>
 /// <param name="cipherText">A base64 encoded string containing encryption information</param>
 /// <param name="passPhrase">The passphrase used to encrypt the inputed text</param>
 /// <returns></returns>
 public string Decrypt(string cipherText, string passPhrase)
 {
     try
         {
             var ciphertextS = DecodeFrom64(cipherText);
             var ciphersplit = Regex.Split(ciphertextS, "-");
             var passsalt = Convert.FromBase64String(ciphersplit[1]);
             var initVectorBytes = Convert.FromBase64String(ciphersplit[0]);
             var cipherTextBytes = Convert.FromBase64String(ciphersplit[2]);
             var password = new PasswordDeriveBytes(passPhrase, passsalt, "SHA512", 100);
             var keyBytes = password.GetBytes(256/8);
             var symmetricKey = new RijndaelManaged();
             symmetricKey.Mode = CipherMode.CBC;
             var decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
             var memoryStream = new MemoryStream(cipherTextBytes);
             var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
             var plainTextBytes = new byte[cipherTextBytes.Length];
             var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
             memoryStream.Close();
             cryptoStream.Close();
             return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
         }
         catch (Exception m)
         {
             return "error";
         }
 }
コード例 #5
0
ファイル: TEncrypt.cs プロジェクト: ranyaof/gismaster
 public static string Decrypt(string cipherText, string Password)
 {
     byte[] cipherBytes = Convert.FromBase64String(cipherText);
     PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 73, 118, 97, 110, 32, 77, 101, 100, 118, 101, 100, 101, 118 });
     byte[] decryptedData = TEncrypt.Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
     return Encoding.UTF8.GetString(decryptedData);
 }
コード例 #6
0
ファイル: Program.cs プロジェクト: LCruel/LCrypt2
 public static string Decrypt(string cipherText, string passPhrase)
 {
     byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                 {
                     try
                     {
                         using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                         {
                             byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                             int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                             return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                         }
                     }
                     catch
                     {
                         return "ERROR";
                     }
                 }
             }
         }
     }
 }
コード例 #7
0
ファイル: TEncrypt.cs プロジェクト: ranyaof/gismaster
 public static string Encrypt(string clearText, string Password)
 {
     byte[] clearBytes = Encoding.UTF8.GetBytes(clearText);
     PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 73, 118, 97, 110, 32, 77, 101, 100, 118, 101, 100, 101, 118 });
     byte[] encryptedData = TEncrypt.Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
     return Convert.ToBase64String(encryptedData);
 }
コード例 #8
0
ファイル: Program.cs プロジェクト: LCruel/LCrypt2
 public static string Encrypt(string plainText, string passPhrase)
 {
     byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                     {
                         cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                         cryptoStream.FlushFinalBlock();
                         byte[] cipherTextBytes = memoryStream.ToArray();
                         return Convert.ToBase64String(cipherTextBytes);
                     }
                 }
             }
         }
     }
 }
コード例 #9
0
ファイル: Program.cs プロジェクト: LCruel/LCrypt2
        public static byte[] Decrypt(byte[] cipherText, string passPhrase,bool padding)
        {
            byte[] cipherTextBytes = cipherText;
            using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
            {
                byte[] keyBytes = password.GetBytes(keysize / 8);
                using (RijndaelManaged symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.Mode = CipherMode.CBC;
                    if(!padding)
                        symmetricKey.Padding = PaddingMode.None;
                    using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                    {
                        using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                        {

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

                        }
                    }
                }
            }
        }
コード例 #10
0
ファイル: QueryStringModule.cs プロジェクト: kiquenet/B4F
    /// <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;
    }
コード例 #11
0
 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);
     }
 }
コード例 #12
0
ファイル: host.cs プロジェクト: Diullei/Storm
    public static string Decrypt(string inName, string password)
    {
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, keySalt);

        Rijndael alg = Rijndael.Create();
        alg.Key = pdb.GetBytes(32);
        alg.IV = pdb.GetBytes(16);

        using (var fin = new FileStream(inName, FileMode.Open, FileAccess.Read))
        using (var fout = new MemoryStream())
        using (var cs = new CryptoStream(fout, alg.CreateDecryptor(), CryptoStreamMode.Write))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            do
            {
                bytesRead = fin.Read(buffer, 0, buffer.Length);
                cs.Write(buffer, 0, bytesRead);
            }
            while (bytesRead != 0);

            cs.FlushFinalBlock();
            return Encoding.ASCII.GetString(fout.ToArray());
        }
    }
コード例 #13
0
 public static void Ctor_DiminishedSalt()
 {
     using (var pdb = new PasswordDeriveBytes(TestPassword, new byte[7]))
     {
         Assert.Equal(DefaultIterationCount, pdb.IterationCount);
         Assert.Equal(7, pdb.Salt.Length);
         Assert.Equal("SHA1", pdb.HashName);
     }
 }
コード例 #14
0
 public static void Ctor_NullPasswordBytes()
 {
     using (var pdb = new PasswordDeriveBytes((byte[])null, s_testSalt))
     {
         Assert.Equal(DefaultIterationCount, pdb.IterationCount);
         Assert.Equal(s_testSalt, pdb.Salt);
         Assert.Equal("SHA1", pdb.HashName);
     }
 }
コード例 #15
0
 public static void Ctor_NullSalt()
 {
     using (var pdb = new PasswordDeriveBytes(TestPassword, null))
     {
         Assert.Equal(DefaultIterationCount, pdb.IterationCount);
         Assert.Equal(null, pdb.Salt);
         Assert.Equal("SHA1", pdb.HashName);
     }
 }
コード例 #16
0
 public static void Ctor_EmptySalt()
 {
     using (var pdb = new PasswordDeriveBytes(TestPassword, Array.Empty<byte>()))
     {
         Assert.Equal(DefaultIterationCount, pdb.IterationCount);
         Assert.Equal(Array.Empty<byte>(), pdb.Salt);
         Assert.Equal("SHA1", pdb.HashName);
     }
 }
コード例 #17
0
	/// <summary>
	///		GetBytes with small values
	/// </summary>
	private static bool GetBytesSmall()
	{
		string password = "******";
		byte[] salt		= new byte[] {0, 1, 2, 3, 4, 5, 6, 7};
		int	   c		= 5;

    	PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA1", c);
    	pdb.Salt = salt;

    	byte[] res1 = pdb.GetBytes(1);
    	byte[] res2 = pdb.GetBytes(2);

		return
			res1 != null && res1.Length == 1 &&
			res2 != null && res2.Length == 2;
	}
コード例 #18
0
ファイル: StringCipher.cs プロジェクト: satishinext/php
 public string Decrypt(string cipherText, string passPhrase)
 {
     byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
     byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
     PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
     byte[] keyBytes = password.GetBytes(keysize / 8);
     RijndaelManaged symmetricKey = new RijndaelManaged();
     symmetricKey.Mode = CipherMode.CBC;
     ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
     MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
     CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
     byte[] plainTextBytes = new byte[cipherTextBytes.Length];
     int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
     memoryStream.Close();
     cryptoStream.Close();
     return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
 }
コード例 #19
0
 //Encrypt
 public string EncryptString(string plainText)
 {
     string passPhrase = "c00ked!n";
     byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
     byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
     byte[] keyBytes = password.GetBytes(keysize / 8);
     RijndaelManaged symmetricKey = new RijndaelManaged();
     symmetricKey.Mode = CipherMode.CBC;
     ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
     MemoryStream memoryStream = new MemoryStream();
     CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
     cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
     cryptoStream.FlushFinalBlock();
     byte[] cipherTextBytes = memoryStream.ToArray();
     memoryStream.Close();
     cryptoStream.Close();
     return Convert.ToBase64String(cipherTextBytes);
 }
コード例 #20
0
ファイル: QueryStringModule.cs プロジェクト: kiquenet/B4F
    /// <summary>
    /// Encrypts any string using the Rijndael algorithm.
    /// </summary>
    /// <param name="inputText">The string to encrypt.</param>
    /// <returns>A Base64 encrypted string.</returns>
    public static string Encrypt(string inputText)
    {
        RijndaelManaged rijndaelCipher = new RijndaelManaged();
        byte[] plainText = Encoding.Unicode.GetBytes(inputText);
        PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

        using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainText, 0, plainText.Length);
                    cryptoStream.FlushFinalBlock();
                    return "?" + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray());
                }
            }
        }
    }
コード例 #21
0
	// Get the encryption key to use to protect memory for a scope.
	private static byte[] GetScopeKey(MemoryProtectionScope scope, byte[] salt)
			{
				String key;
				PasswordDeriveBytes derive;
				if(scope == MemoryProtectionScope.SameLogon)
				{
					key = Environment.UserName;
				}
				else
				{
					key = Environment.UserName + "/" + Environment.MachineName;
				}
				if(salt == null)
				{
					salt = new byte [16];
				}
				derive = new PasswordDeriveBytes(key, salt);
				return derive.CryptDeriveKey("Rijndael", "SHA1", 16, null);
			}
コード例 #22
0
ファイル: CryptoHelper.cs プロジェクト: oxan/mpwebservices
    public static string Crypt(string s_Data, bool b_Encrypt)
    {
        if (!b_Encrypt)
          s_Data = HexToStr(s_Data);
        PasswordDeriveBytes i_Pass = new PasswordDeriveBytes(CryptoPwd(), u8_Salt);

        Rijndael i_Alg = Rijndael.Create();
        i_Alg.Key = i_Pass.GetBytes(32);
        i_Alg.IV = i_Pass.GetBytes(16);

        ICryptoTransform i_Trans = (b_Encrypt) ? i_Alg.CreateEncryptor() : i_Alg.CreateDecryptor();

        MemoryStream i_Mem = new MemoryStream();
        CryptoStream i_Crypt = new CryptoStream(i_Mem, i_Trans, CryptoStreamMode.Write);

        byte[] u8_Data;
        try
        {
          if (b_Encrypt)
        u8_Data = Encoding.Unicode.GetBytes(s_Data);
          else
        u8_Data = Convert.FromBase64String(s_Data);
        }
        catch (Exception)
        {
          return "";
        }

        try
        {
          i_Crypt.Write(u8_Data, 0, u8_Data.Length);
          i_Crypt.Close();
          if (b_Encrypt)
        return StrToHex(Convert.ToBase64String(i_Mem.ToArray()));
          else
        return Encoding.Unicode.GetString(i_Mem.ToArray());
        }
        catch
        {
          return null;
        }
    }
コード例 #23
0
ファイル: TEncrypt.cs プロジェクト: ranyaof/gismaster
 public static void Decrypt(string fileIn, string fileOut, string Password)
 {
     int bytesRead;
     FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
     FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
     PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 73, 118, 97, 110, 32, 77, 101, 100, 118, 101, 100, 101, 118 });
     Rijndael alg = Rijndael.Create();
     alg.Key = pdb.GetBytes(32);
     alg.IV = pdb.GetBytes(16);
     CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write);
     int bufferLen = 4096;
     byte[] buffer = new byte[bufferLen];
     do
     {
         bytesRead = fsIn.Read(buffer, 0, bufferLen);
         cs.Write(buffer, 0, bytesRead);
     }
     while (bytesRead != 0);
     cs.Close();
     fsIn.Close();
 }
コード例 #24
0
	public static Boolean TestRepeated()
	{
		Boolean bRes = true;
		int l, key_size;
		Char[] ach;
		String s;
		Byte[] salt, the_key, temp_key, iv = new Byte[8];
		PasswordDeriveBytes pdb;

		for(int i=0; i<NO_PASSES; i++) {
			l = Rnd.Next(MAX_PASS_LEN)+1;
			ach = new Char[l];
			for(int k=0; k<l; k++) ach[k] = (Char)(Rnd.Next(26)+65);
			s = new String(ach);
			salt = new Byte[Rnd.Next(MAX_SALT_LEN)];
			Rnd.NextBytes(salt);
			key_size = Rnd.Next(128);
			Rnd.NextBytes(iv);

			pdb = new PasswordDeriveBytes(s, salt);
			the_key = pdb.CryptDeriveKey("RC2", "SHA1", /*key_size*/ 128, iv);

			Console.WriteLine("--------------------------------------");
			PrintByteArray(the_key);

			for (int j=0; j<MAX_COMP;j++) {
				temp_key = pdb.CryptDeriveKey("RC2", "SHA1", /*key_size*/ 128, iv);
				Console.WriteLine("--------------------------------------");
				PrintByteArray(temp_key);
				if (!Compare(the_key, temp_key)) {
					bRes = false;
					Console.WriteLine("Two passes of CryptDeriveKey yielded different results");
					break;
				}
			}
			if (bRes == false) break;
		}

		return bRes;
	}
コード例 #25
0
    protected string EncryptString(string InputText, string attribute)
    {
        RijndaelManaged RijndaelCipher = new RijndaelManaged();
        byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);
        byte[] Salt = Encoding.ASCII.GetBytes(attribute.Length.ToString());
        PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(attribute, Salt);
        ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);

        cryptoStream.Write(PlainText, 0, PlainText.Length);

        cryptoStream.FlushFinalBlock();

        byte[] CipherBytes = memoryStream.ToArray();

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

        string EncryptedData = Convert.ToBase64String(CipherBytes);

        return EncryptedData;
    }
コード例 #26
0
ファイル: host.cs プロジェクト: Diullei/Storm
    public static void EncryptFile(string inName, string outName, string password)
    {
        var pdb = new PasswordDeriveBytes(password, keySalt);

        var alg = Rijndael.Create();
        alg.Key = pdb.GetBytes(32);
        alg.IV = pdb.GetBytes(16);

        using (var fin = new FileStream(inName, FileMode.Open, FileAccess.Read))
        using (var fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write))
        using (var cs = new CryptoStream(fout, alg.CreateEncryptor(), CryptoStreamMode.Write))
        {
            var buffer = new byte[4096];
            int bytesRead;

            do
            {
                bytesRead = fin.Read(buffer, 0, buffer.Length);
                cs.Write(buffer, 0, bytesRead);
            }
            while (bytesRead != 0);
        }
    }
コード例 #27
0
 /// <summary>
 /// Encrypts a String with a proivded Passphrase. Returns a base64 encoded string
 /// </summary>
 /// <param name="plainText">Input text to be encrypted</param>
 /// <param name="passPhrase">Password used to encrypt the Plain Text</param>
 /// <returns></returns>
 public string Encrypt(string plainText, string passPhrase)
 {
     var initvector = new byte[16]; //MUST BE 16 Bytes for AES 256
         var passsalt = new byte[16]; //For Salt
         rng.GetBytes(initvector);
         rng.GetBytes(passsalt);
         var initVectorBytes = initvector;
         var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
         var password = new PasswordDeriveBytes(passPhrase, passsalt, "SHA512", 100);
         var keyBytes = password.GetBytes(256/8);
         var symmetricKey = new RijndaelManaged();
         symmetricKey.Mode = CipherMode.CBC;
         var encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
         var memoryStream = new MemoryStream();
         var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
         cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
         cryptoStream.FlushFinalBlock();
         var cipherTextBytes = memoryStream.ToArray();
         memoryStream.Close();
         cryptoStream.Close();
         return
             EncodeTo64(Convert.ToBase64String(initVectorBytes) + "-" + Convert.ToBase64String(passsalt) + "-" +
                        Convert.ToBase64String(cipherTextBytes));
 }
コード例 #28
0
    /// <summary>
    /// Encrypt a string into a string using a password 
    /// </summary>
    /// <param name="clearText"></param>
    /// <param name="Password"></param>
    /// <returns></returns>
    public static string EncryptString(string clearText)
    {
        string strReturn = null;
        if (clearText == null)
        {
            return strReturn;
        }

        try
        {
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(passCode, saltValueBytes, hashAlgo, pwdIterations);

            byte[] encryptedData = EncryptBytes(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            strReturn = Convert.ToBase64String(encryptedData);
        }
        catch (Exception)
        {
            return strReturn;
        }
        return strReturn;
    }
コード例 #29
0
        public string Encrypt(string plainText, string passPhrase, string saltValue)
        {
            int hashSize = 0;

            string hashAlgorithm      = "SHA512";
            int    passwordIterations = 1000;
            string initVector         = "";
            int    keySizeInBytes     = 32;

            if (hashAlgorithm == "MD5")
            {
                hashSize = 16;
            }
            else if (hashAlgorithm == "SHA1")
            {
                hashSize = 16;
            }
            else if (hashAlgorithm == "SHA256")
            {
                hashSize = 32;
            }
            else if (hashAlgorithm == "SHA384")
            {
                hashSize = 48;
            }
            else if (hashAlgorithm == "SHA512")
            {
                hashSize = 64;
            }

            if (keySizeInBytes > hashSize)
            {
                throw new Exception("Selected hash algorithm is not capable of returning the keysize");
            }

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

            // Convert our plaintext into a byte array.
            // Let us assume that plaintext contains UTF8-encoded characters.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // Convert our passPhrase into a byte array.
            byte[] passPhraseBytes = Encoding.UTF8.GetBytes(passPhrase);


            // 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(passPhraseBytes, 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(keySizeInBytes);

            byte[] initVectorBytes;
            if (initVector == "")
            {
                password.Reset();
                initVectorBytes = password.GetBytes(16);
            }
            else
            {
                initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            }

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

            symmetricKey.Padding = PaddingMode.PKCS7;

            // 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 encryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);

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

            // Define cryptographic stream (always use Write mode for encryption).
            CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

            // Start encrypting.
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

            // Finish encrypting.
            cryptoStream.FlushFinalBlock();

            // Convert our encrypted data from a memory stream into a byte array.
            byte[] cipherTextBytes = memoryStream.ToArray();

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

            // Convert encrypted data into a base64-encoded string.
            string cipherText = Convert.ToBase64String(cipherTextBytes);

            // Return encrypted string.
            return(cipherText);
        }
コード例 #30
0
        /// <summary>
        /// Descrypts file(s) with a password as new file(s) without an .enx extension.
        /// </summary>
        /// <param name="directory">Directory where file(s) to be encrypted reside.</param>
        /// <param name="filemask">Filename which may contain wildcards, representing file(s) to decrypt.</param>
        /// <param name="password">Password to decrypt with</param>
        public void DecryptFiles(string directory, string filemask, string password)
        {
            if (directory == null || directory == "")
            {
                directory = Directory.GetCurrentDirectory();
            }

            string[] matchingFiles = Directory.GetFiles(directory, filemask);

            SymmetricAlgorithm sa = new RijndaelManaged();

            foreach (string filename in matchingFiles)
            {
                string newFilename = filename.Replace(".enx", "");

                byte[] rgbIV          = sa.IV;
                byte[] saltValueBytes = Encoding.ASCII.GetBytes("s0d1uMv4l" + password.Length.ToString());

                PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, saltValueBytes, "SHA1", 2);

                // 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 = pdb.GetBytes(256 / 8);

                sa.Mode = CipherMode.CBC;

                byte[] fileBytes;

                // Decryption
                using (Stream inputStream = new FileStream(filename, FileMode.Open))
                {
                    // Before decrypting the stream get the initialization vector out of the first 16 chars.
                    byte[] iv = new byte[16];
                    inputStream.Read(iv, 0, 16);

                    byte[] riv = iv.Reverse().ToArray();
                    rgbIV = riv;

                    ICryptoTransform transform = sa.CreateDecryptor(keyBytes, rgbIV);
                    using (Stream cryptoStream = new CryptoStream(inputStream, transform, CryptoStreamMode.Read))
                    {
                        // Read data into the cryptoStream (which will fetch encrypted
                        // data from the inputStream and then decrypt it before returning
                        // it to us)
                        using (BinaryReader br = new BinaryReader(cryptoStream))
                        {
                            // Now that we have set up an decryption output stream, let us pipe through it the not-yet-decrypted input stream
                            using (FileStream fs = new FileStream(newFilename, FileMode.Create))
                            {
                                using (BinaryWriter bw = new BinaryWriter(fs))
                                {
                                    //int chunkSize = 1024 * 1024; // 1m chunks

                                    fileBytes = br.ReadBytes(99999999);

                                    bw.Write(fileBytes);
                                }
                            }
                        }
                    }
                }
            }
        }
        public static Dictionary <int, string> ListTransactionIndex = new Dictionary <int, string>();                                              // index, hash.

        /// <summary>
        ///     Load transaction in cache.
        /// </summary>
        /// <param name="walletAddress"></param>
        /// <returns></returns>
        public static void LoadWalletCache(string walletAddress)
        {
            if (ListTransaction != null)
            {
                ListTransaction.Clear();
            }
            else
            {
                ListTransaction = new Dictionary <string, ClassWalletTransactionObject>();
            }
            if (!string.IsNullOrEmpty(walletAddress))
            {
                OnLoad = true;
                try
                {
                    Task.Factory.StartNew(() =>
                    {
                        walletAddress += "ANONYMITY";

                        if (Directory.Exists(
                                ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory +
                                                         WalletTransactionCacheDirectory + walletAddress + "\\")))
                        {
                            if (File.Exists(ClassUtility.ConvertPath(
                                                AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory +
                                                walletAddress + "\\" + WalletTransactionCacheFileExtension)))
                            {
                                byte[] AesKeyIv = null;
                                byte[] AesSalt  = null;
                                using (var password = new PasswordDeriveBytes(
                                           Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress +
                                           Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletKey,
                                           ClassUtils.GetByteArrayFromString(ClassUtils.FromHex(
                                                                                 (Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress +
                                                                                  Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletKey)
                                                                                 .Substring(0, 8)))))
                                {
                                    AesKeyIv = password.GetBytes(
                                        ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE / 8);
                                    AesSalt = password.GetBytes(16);
                                }

                                var listTransactionEncrypted = new List <string>();

                                using (var fs = File.Open(
                                           ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory +
                                                                    WalletTransactionCacheDirectory + walletAddress +
                                                                    "\\" +
                                                                    WalletTransactionCacheFileExtension), FileMode.Open,
                                           FileAccess.Read, FileShare.Read))
                                    using (var bs = new BufferedStream(fs))
                                        using (var sr = new StreamReader(bs))
                                        {
                                            string line;
                                            while ((line = sr.ReadLine()) != null)
                                            {
                                                listTransactionEncrypted.Add(line);
                                            }
                                        }

                                if (listTransactionEncrypted.Count > 0)
                                {
                                    var line = 0;

                                    foreach (var transactionEncrypted in listTransactionEncrypted)
                                    {
                                        line++;

                                        OnLoad = true;

                                        var walletTransactionDecrypted =
                                            ClassAlgo.GetDecryptedResult(ClassAlgoEnumeration.Rijndael,
                                                                         transactionEncrypted, ClassWalletNetworkSetting.KeySize, AesKeyIv,
                                                                         AesSalt);
                                        if (walletTransactionDecrypted != ClassAlgoErrorEnumeration.AlgoError)
                                        {
                                            var splitTransaction =
                                                walletTransactionDecrypted.Split(new[] { "#" },
                                                                                 StringSplitOptions.None);
                                            if (!ListTransaction.ContainsKey(splitTransaction[1]))
                                            {
                                                var splitBlockchainHeight = splitTransaction[7]
                                                                            .Split(new[] { "~" }, StringSplitOptions.None);
                                                var transactionObject = new ClassWalletTransactionObject
                                                {
                                                    TransactionType          = splitTransaction[0],
                                                    TransactionHash          = splitTransaction[1],
                                                    TransactionWalletAddress = splitTransaction[2],
                                                    TransactionAmount        =
                                                        decimal.Parse(
                                                            splitTransaction[3].ToString(Program.GlobalCultureInfo),
                                                            NumberStyles.Currency, Program.GlobalCultureInfo),
                                                    TransactionFee = decimal.Parse(
                                                        splitTransaction[4].ToString(Program.GlobalCultureInfo),
                                                        NumberStyles.Currency, Program.GlobalCultureInfo),
                                                    TransactionTimestampSend    = long.Parse(splitTransaction[5]),
                                                    TransactionTimestampRecv    = long.Parse(splitTransaction[6]),
                                                    TransactionBlockchainHeight =
                                                        splitBlockchainHeight[0].Replace("{", "")
                                                };
                                                ListTransaction.Add(splitTransaction[1], transactionObject);
                                                ListTransactionIndex.Add(ListTransactionIndex.Count, splitTransaction[1]);
                                                Program.WalletXiropht.UpdateLabelSyncInformation(
                                                    "On load transaction database - total transactions loaded and decrypted: " +
                                                    (ClassWalletTransactionCache.ListTransaction.Count +
                                                     ListTransaction.Count));
                                            }
#if DEBUG
                                            else
                                            {
                                                Log.WriteLine("Duplicate anonymous transaction: " + walletTransactionDecrypted);
                                            }
#endif
                                        }
#if DEBUG
                                        else
                                        {
                                            Log.WriteLine("Wrong anonymous transaction at line: " + line);
                                        }
#endif
                                    }
                                }

                                Program.WalletXiropht.ClassWalletObject.TotalTransactionInSyncAnonymity =
                                    ListTransaction.Count;
                                listTransactionEncrypted.Clear();
                                AesKeyIv = null;
                                AesSalt  = null;
                            }
                            else
                            {
                                File.Create(ClassUtility.ConvertPath(
                                                AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory +
                                                walletAddress + "\\" + WalletTransactionCacheFileExtension)).Close();
                            }
                        }
                        else
                        {
                            if (Directory.Exists(ClassUtility.ConvertPath(
                                                     AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory)) ==
                                false)
                            {
                                Directory.CreateDirectory(ClassUtility.ConvertPath(
                                                              AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory));
                            }

                            Directory.CreateDirectory(ClassUtility.ConvertPath(
                                                          AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory +
                                                          walletAddress));
                        }


                        Program.WalletXiropht.ClassWalletObject.TotalTransactionInSyncAnonymity = ListTransaction.Count;
                        OnLoad = false;
                    }, Program.WalletXiropht.WalletCancellationToken.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current).ConfigureAwait(false);
                }
                catch
                {
                    Program.WalletXiropht.ClassWalletObject.TotalTransactionInSyncAnonymity = 0;
                    ListTransaction.Clear();
                    ListTransactionIndex.Clear();
                    OnLoad = false;
                }
            }
        }
コード例 #32
0
        private static int keySize            = 256;                                // Может быть 192 или 128

        public static string Encrypt
        (
            string plainText
        )
        {
            //Преобразование строк в байтовые массивы.
            //Предположим, что строки содержат только коды ASCII.
            //Если строки содержат символы Юникода, используйте Юникод, UTF7 или UTF8
            //Кодировки.
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);

            //Преобразование открытого текста в массив байтов.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // Во-первых, мы должны создать пароль, из которого будет получен ключ.
            //Этот пароль будет создан из указанной парольной фразы и
            //соли. Пароль будет создан с использованием указанного хэша
            //алгоритма. Создание пароля может выполняться в нескольких итерациях.
            PasswordDeriveBytes password = new PasswordDeriveBytes
                                           (
                passPhrase,
                saltValueBytes,
                hashAlgorithm,
                passwordIterations
                                           );

            //Используйте пароль для создания псевдослучайных байтов для шифрования
            //ключа. Укажите размер ключа в байтах (вместо битов).
            byte[] keyBytes = password.GetBytes(keySize / 8);

            //Создать неинициализированный объект шифрования Rijndael.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            symmetricKey.Mode = CipherMode.CBC;

            //Создать шифратор из существующих байтов ключа и инициализации
            //вектор. Размер ключа определяется на основе количества байтов ключа.
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor
                                         (
                keyBytes,
                initVectorBytes
                                         );

            //Определите поток памяти, который будет использоваться для хранения зашифрованных данных.
            MemoryStream memoryStream = new MemoryStream();

            //Определите криптографический поток (всегда используйте режим записи для шифрования).
            CryptoStream cryptoStream = new CryptoStream
                                        (
                memoryStream,
                encryptor,
                CryptoStreamMode.Write
                                        );

            //Начните шифровать.
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

            //Шифровка конца.
            cryptoStream.FlushFinalBlock();

            //Преобразование зашифрованных данных из потока памяти в массив байтов.
            byte[] cipherTextBytes = memoryStream.ToArray();

            //Закройте оба потока.
            memoryStream.Close();
            cryptoStream.Close();

            //Преобразование зашифрованных данных в строку в кодировке base64.
            string cipherText = Convert.ToBase64String(cipherTextBytes);

            //Возвратите зашифрованную последовательность.
            return(cipherText);
        }
コード例 #33
0
 private void sandbox()
 {
     var test = new PasswordDeriveBytes("test", new byte[] { 0, 1, 2, 3 });
 }
コード例 #34
0
        /// <summary>
        ///     Send packet to seed node.
        /// </summary>
        /// <param name="packet"></param>
        /// <param name="certificate"></param>
        /// <param name="isSeedNode"></param>
        /// <param name="isEncrypted"></param>
        /// <returns></returns>
        public async Task <bool> SendPacketToSeedNodeAsync(string packet, string certificate, bool isSeedNode = false, bool isEncrypted = false)
        {
            if (!ReturnStatus())
            {
                return(false);
            }
            try
            {
                using (var bufferedNetworkStream = new NetworkStream(_connector.Client))
                {
                    // 10/08/2018 - MAJOR_UPDATE_1_SECURITY
                    if (ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY) // SSL Layer for Send packet.
                    {
                        if (isEncrypted)
                        {
                            if (AesIvCertificate == null)
                            {
                                using (PasswordDeriveBytes password = new PasswordDeriveBytes(certificate, ClassUtils.GetByteArrayFromString(ClassUtils.FromHex(certificate.Substring(0, 8)))))
                                {
                                    AesIvCertificate   = password.GetBytes(ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE / 8);
                                    AesSaltCertificate = password.GetBytes(16);
                                }
                            }
                            using (ClassSeedNodeConnectorObjectSendPacket packetObject = new ClassSeedNodeConnectorObjectSendPacket(ClassAlgo.GetEncryptedResult(ClassAlgoEnumeration.Rijndael, packet, ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE, AesIvCertificate, AesSaltCertificate) + ClassConnectorSetting.PacketSplitSeperator))
                            {
                                await bufferedNetworkStream.WriteAsync(packetObject.packetByte, 0, packetObject.packetByte.Length);

                                await bufferedNetworkStream.FlushAsync();
                            }
                        }
                        else
                        {
                            if (isSeedNode)
                            {
                                using (ClassSeedNodeConnectorObjectSendPacket packetObject = new ClassSeedNodeConnectorObjectSendPacket(packet + ClassConnectorSetting.PacketSplitSeperator))
                                {
                                    await bufferedNetworkStream.WriteAsync(packetObject.packetByte, 0, packetObject.packetByte.Length);

                                    await bufferedNetworkStream.FlushAsync();
                                }
                            }
                            else
                            {
                                using (ClassSeedNodeConnectorObjectSendPacket packetObject = new ClassSeedNodeConnectorObjectSendPacket(packet))
                                {
                                    await bufferedNetworkStream.WriteAsync(packetObject.packetByte, 0, packetObject.packetByte.Length);

                                    await bufferedNetworkStream.FlushAsync();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception error)
            {
#if DEBUG
                Console.WriteLine("Error to send packet on seed node: " + error.Message);
#endif
                _isConnected = false;
                return(false);
            }

            return(true);
        }
コード例 #35
0
        // Decrypt a string into a string using a password

        //    Uses Decrypt(byte[], byte[], byte[])


        public static string Decrypt(string cipherText, string Password)
        {
            // First we need to turn the input string into a byte array.

            // We presume that Base64 encoding was used

            byte[] cipherBytes = Convert.FromBase64String(cipherText);

            // Then, we need to turn the password into Key and IV

            // We are using salt to make it harder to guess our key

            // using a dictionary attack -

            // trying to guess a password by enumerating all possible words.

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
                                                              new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65,
                                                                           0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

            // Now get the key/IV and do the decryption using

            // the function that accepts byte arrays.

            // Using PasswordDeriveBytes object we are first

            // getting 32 bytes for the Key

            // (the default Rijndael key length is 256bit = 32bytes)

            // and then 16 bytes for the IV.

            // IV should always be the block size, which is by

            // default 16 bytes (128 bit) for Rijndael.

            // If you are using DES/TripleDES/RC2 the block size is

            // 8 bytes and so should be the IV size.

            // You can also read KeySize/BlockSize properties off

            // the algorithm to find out the sizes.

            byte[] decryptedData = Decrypt(cipherBytes,
                                           pdb.GetBytes(32), pdb.GetBytes(16));

            // Now we need to turn the resulting byte array into a string.

            // A common mistake would be to use an Encoding class for that.

            // It does not work

            // because not all byte values can be represented by characters.

            // We are going to be using Base64 encoding that is

            // designed exactly for what we are trying to do.

            return(System.Text.Encoding.Unicode.GetString(decryptedData));
        }
コード例 #36
0
        // Decrypt a file into another file using a password

        public static void Decrypt(string fileIn,
                                   string fileOut, string Password)
        {
            // First we are going to open the file streams

            FileStream fsIn = new FileStream(fileIn,
                                             FileMode.Open, FileAccess.Read);
            FileStream fsOut = new FileStream(fileOut,
                                              FileMode.OpenOrCreate, FileAccess.Write);

            // Then we are going to derive a Key and an IV from

            // the Password and create an algorithm

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
                                                              new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
                                                                           0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            Rijndael alg = Rijndael.Create();

            alg.Key = pdb.GetBytes(32);
            alg.IV  = pdb.GetBytes(16);

            // Now create a crypto stream through which we are going

            // to be pumping data.

            // Our fileOut is going to be receiving the Decrypted bytes.

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

            // Now will will initialize a buffer and will be

            // processing the input file in chunks.

            // This is done to avoid reading the whole file (which can be

            // huge) into memory.

            int bufferLen = 4096;

            byte[] buffer = new byte[bufferLen];
            int    bytesRead;

            do
            {
                // read a chunk of data from the input file

                bytesRead = fsIn.Read(buffer, 0, bufferLen);

                // Decrypt it

                cs.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);

            // close everything

            cs.Close(); // this will also close the unrelying fsOut stream

            fsIn.Close();
        }
コード例 #37
0
        /// <summary>
        /// Encrypts text using Rijndael symmetric key algorithm and returns base64-encoded result.
        /// </summary>
        /// <param name="plainText">Plain text data to be encrypted.</param>
        /// <returns>Encrypted value formatted as a base64-encoded string.</returns>
        public static string Encrypt(string plainText, out string randomKeyText)
        {
            // Convert init vector / salt value ASCII strings into byte arrays
            // 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 plain text into a byte array
            // Assume plain text can contains UTF8 characters
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // Using the specified hash algorithm, create a password from the specified passphrase
            // and salt value from which we will derive the key
            // Password creation can be done in one or more iterations
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                passPhrase,
                saltValueBytes,
                hashAlgorithm,
                passwordIterations);

            // Use  password to generate random bytes for encryption key.
            // Specify the size of the key in bytes (instead of bits)
            // Set string equivalent of the random key byte array.
            byte[] keyBytes = password.GetBytes(keySize / 8);
            randomKeyText = GetString(keyBytes);

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

            // Set encryption mode to Cipher Block Chaining
            symmetricKey.Mode    = CipherMode.CBC;
            symmetricKey.Padding = PaddingMode.ISO10126;
            // Generate encryptor from the key bytes and initialization vector.
            // Key size will be based on the number of key bytes
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                keyBytes,
                initVectorBytes);

            // Define memory stream to contain encrypted data
            MemoryStream memoryStream = new MemoryStream();

            // Define cryptographic stream (always use Write mode for encryption)
            CryptoStream cryptoStream = new CryptoStream(
                memoryStream,
                encryptor,
                CryptoStreamMode.Write);

            // Start and finish encrypting.
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();

            // Convert encrypted data from a memory stream into a byte array
            byte[] cipherTextBytes = memoryStream.ToArray();

            // Close memory and cryptographic streams
            memoryStream.Close();
            cryptoStream.Close();

            // Convert encrypted data into a base64-encoded string and return
            return(Convert.ToBase64String(cipherTextBytes));
        }
コード例 #38
0
        /// <summary>
        /// Шифрование/Дешифрование файла
        /// </summary>
        /// <param name="isEncrypting">Шифровать?</param>
        /// <param name="key_word">Пароль, из которого генерируется ключ</param>
        /// <param name="key_size">Длина ключа</param>
        /// <param name="src_file">Входной файл</param>
        /// <param name="dst_file">Выходной файл (путь д.б. уже создан)</param>
        /// <param name="pr_b">Прогресс бар</param>
        public void crypt_file(bool isEncrypting, string key_word, int key_size, string src_file, string dst_file, ProgressBar pr_b)
        {
            if (string.IsNullOrEmpty(key_word))
            {
                key_word = FileCrypt.default_key;
            }
            SymmetricAlgorithm alg;

            alg = (SymmetricAlgorithm)RijndaelManaged.Create();                //пример создания класса RijndaelManaged

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(key_word, null); //класс, позволяющий генерировать ключи на базе паролей

            pdb.HashName = "SHA512";                                           //будем использовать SHA512
            int keylen = key_size;                                             //получаем размер ключа из ComboBox’а

            alg.KeySize = keylen;                                              //устанавливаем размер ключа
            alg.Key     = pdb.GetBytes(keylen >> 3);                           //получаем ключ из пароля
            alg.Mode    = CipherMode.CBC;                                      //используем режим CBC
            alg.IV      = new Byte[alg.BlockSize >> 3];                        //и пустой инициализационный вектор
            ICryptoTransform tr;

            if (isEncrypting)
            {
                tr = alg.CreateEncryptor(); //создаем encryptor
            }
            else
            {
                tr = alg.CreateDecryptor(); //создаем decryptor
            }

            FileStream instream  = new FileStream(src_file, FileMode.Open, FileAccess.Read, FileShare.Read);
            FileStream outstream = new FileStream(dst_file, FileMode.Create, FileAccess.Write, FileShare.None);
            int        buflen    = ((2 << 16) / alg.BlockSize) * alg.BlockSize;

            byte[] inbuf  = new byte[buflen];
            byte[] outbuf = new byte[buflen];
            int    len;
            long   input_size = instream.Length;
            long   c_position = 0;

            pr_b.Maximum = int.MaxValue;

            while ((len = instream.Read(inbuf, 0, buflen)) == buflen)
            {
                int enclen = tr.TransformBlock(inbuf, 0, buflen, outbuf, 0); //собственно шифруем
                outstream.Write(outbuf, 0, enclen);
                c_position += enclen;
                pr_b.Value  = (int)Math.Ceiling((double)int.MaxValue * ((double)c_position / (double)input_size));
                if (CryptFileTail != null)
                {
                    CryptFileTail.Invoke(((double)c_position / (double)input_size));
                }
                Application.DoEvents();
            }
            instream.Close();
            outbuf = tr.TransformFinalBlock(inbuf, 0, len); //шифруем финальный блок
            outstream.Write(outbuf, 0, outbuf.Length);
            pr_b.Value = int.MaxValue;
            outstream.Close();
            alg.Clear(); //осуществляем зачистку
        }
コード例 #39
0
        protected virtual void DecryptElement(XmlElement element, string password)
        {
            var saltXmlAttributeNode = XmlHelpers.GetAttributeNode(element, "Salt");

            if (string.IsNullOrEmpty(saltXmlAttributeNode?.Value))
            {
                throw new InvalidXmlException($"Encrypted element {element.Name} does not contain required Attribute \"Salt\", or its contents is empty", element);
            }
            byte[] rgbSalt;
            try
            {
                rgbSalt = Convert.FromBase64String(saltXmlAttributeNode.Value);
            }
            catch (FormatException)
            {
                throw new InvalidXmlException($"Invalid value of Attribute \"Salt\" ({saltXmlAttributeNode.Value}) in encrypted element {element.Name}", element);
            }
            var ivXmlAttributeNode = XmlHelpers.GetAttributeNode(element, "IV");

            if (string.IsNullOrEmpty(ivXmlAttributeNode?.Value))
            {
                throw new InvalidXmlException($"Encrypted element {element.Name} does not contain required Attribute \"IV\", or its contents is empty", element);
            }
            byte[] iv;
            try
            {
                iv = Convert.FromBase64String(ivXmlAttributeNode.Value);
            }
            catch (FormatException)
            {
                throw new InvalidXmlException($"Invalid value of Attribute \"IV\" ({ivXmlAttributeNode.Value}) in encrypted element {element.Name} ", element);
            }
            var cryptoServiceProvider = new TripleDESCryptoServiceProvider {
                IV = iv
            };

            var passwordDeriveBytes = new PasswordDeriveBytes(password, rgbSalt);

            cryptoServiceProvider.Key = passwordDeriveBytes.CryptDeriveKey("TripleDES", "SHA1", 192,
                                                                           cryptoServiceProvider.IV);
            string xml;

            byte[] buffer;
            try
            {
                buffer = Convert.FromBase64String(element.InnerText);
            }
            catch (FormatException)
            {
                throw new InvalidXmlException($"Invalid value of encrypted element {element.Name}.", element);
            }
            try
            {
                using (var memoryStream = new MemoryStream(buffer))
                {
                    using (
                        var cryptoStream = new CryptoStream(memoryStream, cryptoServiceProvider.CreateDecryptor(),
                                                            CryptoStreamMode.Read))
                    {
                        using (var streamReader = new StreamReader(cryptoStream, Encoding.UTF8))
                            xml = streamReader.ReadToEnd();
                    }
                }
            }
            catch (CryptographicException)
            {
                throw new InvalidPaswordException();
            }

            var xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(xml);

            // The reason to not simply import the new node is because namespace declaration will also be imported with the node.
            element.Attributes.Remove(saltXmlAttributeNode);
            element.Attributes.Remove(ivXmlAttributeNode);

            foreach (XmlNode childNode in element.ChildNodes)
            {
                element.RemoveChild(childNode);
            }
            element.InnerXml = xmlDocument.DocumentElement?.InnerXml;
        }
コード例 #40
0
        /// <summary>
        /// Generates a sequence based on specified string password and salt.
        /// </summary>
        /// <param name="password">The string password.</param>
        /// <param name="salt">The salt.</param>
        /// <param name="size">The size of the result sequence.</param>
        /// <returns>The generated sequence.</returns>
        public static byte[] GeneratePasswordBasedSequence(string password, byte[] salt, int size)
        {
            PasswordDeriveBytes passwordDeriveBytes = new PasswordDeriveBytes(password, salt);

            return(passwordDeriveBytes.GetBytes(size));
        }
コード例 #41
0
ファイル: main_class.cs プロジェクト: bahmany/tracking
    public static string Encrypt(string plainText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
    {
        // Convert strings 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 plaintext into a byte array.
        // Let us assume that plaintext contains UTF8-encoded characters.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        // 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 encryptor from the existing key bytes and initialization
        // vector. Key size will be defined based on the number of the key
        // bytes.
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                                                         keyBytes,
                                                         initVectorBytes);

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

        // Define cryptographic stream (always use Write mode for encryption).
        CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                     encryptor,
                                                     CryptoStreamMode.Write);
        // Start encrypting.
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

        // Finish encrypting.
        cryptoStream.FlushFinalBlock();

        // Convert our encrypted data from a memory stream into a byte array.
        byte[] cipherTextBytes = memoryStream.ToArray();

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

        // Convert encrypted data into a base64-encoded string.
        string cipherText = Convert.ToBase64String(cipherTextBytes);

        // Return encrypted string.
        return cipherText;
    }
コード例 #42
0
        /// <summary>
        ///     Listen and return packet from Seed Node.
        /// </summary>
        /// <returns></returns>
        public async Task <string> ReceivePacketFromSeedNodeAsync(string certificate, bool isSeedNode = false, bool isEncrypted = false)
        {
            try
            {
                if (ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY) // New Layer for receive packet.
                {
                    using (var bufferPacket = new ClassSeedNodeConnectorObjectPacket())
                    {
                        using (var bufferedNetworkStream = new NetworkStream(_connector.Client))
                        {
                            int received = 0;

                            while ((received = await bufferedNetworkStream.ReadAsync(bufferPacket.buffer, 0, bufferPacket.buffer.Length)) > 0)
                            {
                                if (received > 0)
                                {
                                    bufferPacket.packet = Encoding.UTF8.GetString(bufferPacket.buffer, 0, received);

                                    if (bufferPacket.packet != ClassSeedNodeStatus.SeedError && bufferPacket.packet != ClassSeedNodeStatus.SeedNone)
                                    {
                                        if (isEncrypted)
                                        {
                                            if (AesIvCertificate == null)
                                            {
                                                using (PasswordDeriveBytes password = new PasswordDeriveBytes(certificate, ClassUtils.GetByteArrayFromString(ClassUtils.FromHex(certificate.Substring(0, 8)))))
                                                {
                                                    AesIvCertificate   = password.GetBytes(ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE / 8);
                                                    AesSaltCertificate = password.GetBytes(16);
                                                }
                                            }
                                            if (bufferPacket.packet.Contains(ClassConnectorSetting.PacketSplitSeperator))
                                            {
                                                if (!string.IsNullOrEmpty(_malformedPacket))
                                                {
                                                    bufferPacket.packet = _malformedPacket + bufferPacket.packet;
                                                    _malformedPacket    = string.Empty;
                                                }
                                                var splitPacket = bufferPacket.packet.Split(new[] { ClassConnectorSetting.PacketSplitSeperator }, StringSplitOptions.None);
                                                bufferPacket.packet = string.Empty;
                                                foreach (var packetEach in splitPacket)
                                                {
                                                    if (!string.IsNullOrEmpty(packetEach))
                                                    {
                                                        if (packetEach.Length > 1)
                                                        {
                                                            if (packetEach.Contains(ClassRemoteNodeCommand.ClassRemoteNodeRecvFromSeedEnumeration.RemoteSendTransactionPerId))
                                                            {
                                                                bufferPacket.packet += packetEach.Replace(ClassConnectorSetting.PacketSplitSeperator, "") + ClassConnectorSetting.PacketSplitSeperator;
                                                            }
                                                            else
                                                            {
                                                                string packetDecrypt = ClassAlgo.GetDecryptedResult(ClassAlgoEnumeration.Rijndael, packetEach.Replace(ClassConnectorSetting.PacketSplitSeperator, ""), ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE, AesIvCertificate, AesSaltCertificate);

                                                                if (packetDecrypt.Contains(ClassSeedNodeCommand.ClassReceiveSeedEnumeration.WalletSendSeedNode))
                                                                {
                                                                    var packetNewSeedNode = packetDecrypt.Replace(ClassSeedNodeCommand.ClassReceiveSeedEnumeration.WalletSendSeedNode, "");
                                                                    packetNewSeedNode = packetNewSeedNode.Replace(ClassConnectorSetting.PacketSplitSeperator, "");
                                                                    var splitPacketNewSeedNode = packetNewSeedNode.Split(new[] { ";" }, StringSplitOptions.None);
                                                                    var newSeedNodeHost        = splitPacketNewSeedNode[0];
                                                                    var newSeedNodeCountry     = splitPacketNewSeedNode[1];

                                                                    if (!ClassConnectorSetting.SeedNodeIp.ContainsKey(newSeedNodeHost))
                                                                    {
                                                                        ClassConnectorSetting.SeedNodeIp.Add(newSeedNodeHost, new Tuple <string, bool>(newSeedNodeCountry, false));
                                                                    }
                                                                    if (!ClassConnectorSetting.SeedNodeDisconnectScore.ContainsKey(newSeedNodeHost))
                                                                    {
                                                                        ClassConnectorSetting.SeedNodeDisconnectScore.Add(newSeedNodeHost, new Tuple <int, long>(0, 0));
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    bufferPacket.packet += packetDecrypt + ClassConnectorSetting.PacketSplitSeperator;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (!bufferPacket.packet.Contains(ClassRemoteNodeCommand.ClassRemoteNodeRecvFromSeedEnumeration.RemoteSendTransactionPerId))
                                                {
                                                    try
                                                    {
                                                        string packetDecrypt = ClassAlgo.GetDecryptedResult(ClassAlgoEnumeration.Rijndael, bufferPacket.packet, ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE, AesIvCertificate, AesSaltCertificate);


                                                        if (bufferPacket.packet.Contains(ClassSeedNodeCommand.ClassReceiveSeedEnumeration.WalletSendSeedNode))
                                                        {
                                                            var packetNewSeedNode      = packetDecrypt.Replace(ClassSeedNodeCommand.ClassReceiveSeedEnumeration.WalletSendSeedNode, "");
                                                            var splitPacketNewSeedNode = packetNewSeedNode.Split(new[] { ";" }, StringSplitOptions.None);
                                                            var newSeedNodeHost        = splitPacketNewSeedNode[0];
                                                            var newSeedNodeCountry     = splitPacketNewSeedNode[1];
                                                            if (!ClassConnectorSetting.SeedNodeIp.ContainsKey(newSeedNodeHost))
                                                            {
                                                                ClassConnectorSetting.SeedNodeIp.Add(newSeedNodeHost, new Tuple <string, bool>(newSeedNodeCountry, false));
                                                            }
                                                            if (!ClassConnectorSetting.SeedNodeDisconnectScore.ContainsKey(newSeedNodeHost))
                                                            {
                                                                ClassConnectorSetting.SeedNodeDisconnectScore.Add(newSeedNodeHost, new Tuple <int, long>(0, 0));
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (packetDecrypt != ClassAlgoErrorEnumeration.AlgoError)
                                                            {
                                                                bufferPacket.packet = packetDecrypt + ClassConnectorSetting.PacketSplitSeperator;
                                                            }
                                                            else
                                                            {
                                                                if (_malformedPacket.Length - 1 >= int.MaxValue || (long)(_malformedPacket.Length + bufferPacket.packet.Length) >= int.MaxValue)
                                                                {
                                                                    _malformedPacket = string.Empty;
                                                                }
                                                                _malformedPacket += bufferPacket.packet;
                                                            }
                                                        }
                                                    }
                                                    catch
                                                    {
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (bufferPacket.packet == ClassSeedNodeCommand.ClassReceiveSeedEnumeration.DisconnectPacket)
                                    {
                                        _isConnected = false;
                                        return(ClassSeedNodeStatus.SeedError);
                                    }

                                    return(bufferPacket.packet);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                _isConnected = false;
                return(ClassSeedNodeStatus.SeedError);
            }

            return(ClassSeedNodeStatus.SeedNone);
        }
コード例 #43
0
        private byte[] GetPasswordBytes(string password)
        {
            var passwordDeriveBytes = new PasswordDeriveBytes(password, SaltBuffer, GetHashAlgorithm(), 17);

            return(passwordDeriveBytes.GetBytes(Constants.KeySize / 8));
        }
コード例 #44
0
        /// <summary>
        /// Use this constructor if you are planning to perform encryption/
        /// decryption with the key derived from the explicitly specified
        /// parameters.
        /// </summary>
        /// <param name="passPhrase">
        /// Passphrase from which a pseudo-random password will be derived.
        /// The derived password will be used to generate the encryption key
        /// Passphrase can be any string. In this example we assume that the
        /// passphrase is an ASCII string. Passphrase value must be kept in
        /// secret.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be
        /// exactly 16 ASCII characters long. IV value does not have to be kept
        /// in secret.
        /// </param>
        /// <param name="minSaltLen">
        /// Min size (in bytes) of randomly generated salt which will be added at
        /// the beginning of plain text before encryption is performed. When this
        /// value is less than 4, the default min value will be used (currently 4
        /// bytes).
        /// </param>
        /// <param name="maxSaltLen">
        /// Max size (in bytes) of randomly generated salt which will be added at
        /// the beginning of plain text before encryption is performed. When this
        /// value is negative or greater than 255, the default max value will be
        /// used (currently 8 bytes). If max value is 0 (zero) or if it is smaller
        /// than the specified min value (which can be adjusted to default value),
        /// salt will not be used and plain text value will be encrypted as is.
        /// In this case, salt will not be processed during decryption either.
        /// </param>
        /// <param name="keySize">
        /// Size of symmetric key (in bits): 128, 192, or 256.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hashing algorithm: "MD5" or "SHA1". SHA1 is recommended.
        /// </param>
        /// <param name="saltValue">
        /// Salt value used for password hashing during key generation. This is
        /// not the same as the salt we will use during encryption. This parameter
        /// can be any string.
        /// </param>
        /// <param name="passwordIterations">
        /// Number of iterations used to hash password. More iterations are
        /// considered more secure but may take longer.
        /// </param>
        public Cryptography(string passPhrase,
                            string initVector,
                            int minSaltLen,
                            int maxSaltLen,
                            int keySize,
                            string hashAlgorithm,
                            string saltValue,
                            int passwordIterations)
        {
            // Save min salt length; set it to default if invalid value is passed.
            if (minSaltLen < MIN_ALLOWED_SALT_LEN)
            {
                this.minSaltLen = DEFAULT_MIN_SALT_LEN;
            }
            else
            {
                this.minSaltLen = minSaltLen;
            }

            // Save max salt length; set it to default if invalid value is passed.
            if (maxSaltLen < 0 || maxSaltLen > MAX_ALLOWED_SALT_LEN)
            {
                this.maxSaltLen = DEFAULT_MAX_SALT_LEN;
            }
            else
            {
                this.maxSaltLen = maxSaltLen;
            }

            // Set the size of cryptographic key.
            if (keySize <= 0)
            {
                keySize = DEFAULT_KEY_SIZE;
            }

            // Set the name of algorithm. Make sure it is in UPPER CASE and does
            // not use dashes, e.g. change "sha-1" to "SHA1".
            if (hashAlgorithm == null)
            {
                hashAlgorithm = DEFAULT_HASH_ALGORITHM;
            }
            else
            {
                hashAlgorithm = hashAlgorithm.ToUpper().Replace("-", "");
            }

            // Initialization vector converted to a byte array.
            byte[] initVectorBytes = null;

            // Salt used for password hashing (to generate the key, not during
            // encryption) converted to a byte array.
            byte[] saltValueBytes = null;

            // Get bytes of initialization vector.
            if (initVector == null)
            {
                initVectorBytes = new byte[0];
            }
            else
            {
                initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            }

            // Get bytes of salt (used in hashing).
            if (saltValue == null)
            {
                saltValueBytes = new byte[0];
            }
            else
            {
                saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
            }

            // Generate password, which will be used to derive the key.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                passPhrase,
                saltValueBytes,
                hashAlgorithm,
                passwordIterations);

            // Convert key to a byte array adjusting the size from bits to bytes.
            byte[] keyBytes = password.GetBytes(keySize / 8);

            // Initialize Rijndael key object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // If we do not have initialization vector, we cannot use the CBC mode.
            // The only alternative is the ECB mode (which is not as good).
            if (initVectorBytes.Length == 0)
            {
                symmetricKey.Mode = CipherMode.ECB;
            }
            else
            {
                symmetricKey.Mode = CipherMode.CBC;
            }

            // Create encryptor and decryptor, which we will use for cryptographic
            // operations.
            encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
        }
コード例 #45
0
        public static string Decrypt(string cipherText, string passPhrase = chiave, string saltValue = iv, string hashAlgorithm = "MD5", int passwordIterations = 3, string initVector = "@1B2c3D4e5F6g7H8", int keySize = 256)
        {
            string plainText = string.Empty;



            try

            {
                byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);

                byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);



                byte[] cipherTextBytes = Convert.FromBase64String(cipherText);



                PasswordDeriveBytes password = new PasswordDeriveBytes(

                    passPhrase,

                    saltValueBytes,

                    hashAlgorithm,

                    passwordIterations);

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



                RijndaelManaged symmetricKey = new RijndaelManaged();



                symmetricKey.Mode = CipherMode.CBC;

                ICryptoTransform decryptor = symmetricKey.CreateDecryptor(

                    keyBytes,

                    initVectorBytes);



                MemoryStream memoryStream = new MemoryStream(cipherTextBytes);



                CryptoStream cryptoStream = new CryptoStream(memoryStream,

                                                             decryptor,

                                                             CryptoStreamMode.Read);

                byte[] plainTextBytes = new byte[cipherTextBytes.Length];

                int decryptedByteCount = cryptoStream.Read(plainTextBytes,

                                                           0,

                                                           plainTextBytes.Length);

                memoryStream.Close();

                cryptoStream.Close();



                plainText = Encoding.UTF8.GetString(plainTextBytes,

                                                    0,

                                                    decryptedByteCount);
            }

            catch (CryptographicException)

            {
                throw;
            }



            return(plainText);
        }
コード例 #46
0
ファイル: AES.cs プロジェクト: h5p9sl/Crypto-Notepad
        public static string Encrypt(string plainText, string password,
                                     string salt            = null, string hashAlgorithm = "SHA1",
                                     int passwordIterations = 2, int keySize             = 256)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                return(null);
            }
            if (string.IsNullOrEmpty(password))
            {
                return(null);
            }

            byte[] plainTextBytes;
            byte[] saltValueBytes;

            // In case user wants a random salt or salt is null/empty for some other reason
            if (string.IsNullOrEmpty(salt))
            {
                saltValueBytes = new byte[64]; // Nice and long
                saltValueBytes = GenerateSecureNonZeroByteArray(saltValueBytes.Length);
            }
            else
            {
                saltValueBytes = Encoding.ASCII.GetBytes(salt);
            }

            plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            PasswordDeriveBytes derivedPassword = new PasswordDeriveBytes
                                                      (password, saltValueBytes, hashAlgorithm, passwordIterations);

            // Null password; adds *some* memory dump protection
            password = null;

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

            symmetricKey.Mode = CipherMode.CBC;

            // Generate IV
            symmetricKey.IV = GenerateSecureNonZeroByteArray(symmetricKey.IV.Length);

            byte[] cipherTextBytes = null;

            using (MemoryStream memStream = new MemoryStream())
            {
                AESMetadata.WriteMetadata(memStream, symmetricKey.IV, saltValueBytes);

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

            symmetricKey.Dispose();
            return(Convert.ToBase64String(cipherTextBytes));
        }
コード例 #47
0
        public static string Encrypt(string plainText, string passPhrase = chiave, string saltValue = iv, string hashAlgorithm = "MD5", int passwordIterations = 3, string initVector = "@1B2c3D4e5F6g7H8", int keySize = 256)
        {
            string cipherText = string.Empty;



            try
            {
                //Create byte arrays of our strings so that we can use them

                //with the .NET Rijndael classes.

                byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);

                byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);



                PasswordDeriveBytes password = new PasswordDeriveBytes(

                    passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);

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



                RijndaelManaged symmetricKey = new RijndaelManaged();

                symmetricKey.Mode = CipherMode.CBC;



                ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,

                                                                          initVectorBytes);



                MemoryStream memoryStream = new MemoryStream();

                CryptoStream cryptoStream = new CryptoStream(memoryStream,

                                                             encryptor, CryptoStreamMode.Write);



                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);



                cryptoStream.FlushFinalBlock();



                byte[] cipherTextBytes = memoryStream.ToArray();



                memoryStream.Close();

                cryptoStream.Close();



                cipherText = Convert.ToBase64String(cipherTextBytes);
            }

            catch
            {
                cipherText = string.Empty;
            }



            return(cipherText);
        }
コード例 #48
0
        public void LoadFromEncryptedString(string encryptedString, RMSecureString password)
        {
            Clear();

            if (encryptedString.StartsWith("p"))
            {
                LoadFromProtectedString(encryptedString, password);
            }
            else if (encryptedString.StartsWith("e!2!"))
            {
                LoadFromEncryptedStringv2(encryptedString, password);
            }
            else if (encryptedString.StartsWith("e"))
            {
                // Trim leading 'e', which is just an indicator to say that this is an encrypted and not a protected string
                encryptedString = encryptedString.Substring(1);

                IntPtr PasswordPtr = IntPtr.Zero;

                try
                {
                    // Get the secure password string into a memory buffer
                    PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
                    int PasswordSize = password.Length * sizeof(byte);

                    // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                    unsafe
                    {
                        byte[] Decrypted     = null;
                        byte[] PasswordBytes = new byte[PasswordSize];
                        fixed(byte *ptr = PasswordBytes)
                        {
                            try
                            {
                                Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);

                                PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(PasswordBytes, Encoding.ASCII.GetBytes("RMSecureString"), "SHA512", 12345);
                                using (RijndaelManaged SymmetricKey = new RijndaelManaged())
                                {
                                    SymmetricKey.Mode = CipherMode.CBC;
                                    using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(DerivedPassword.GetBytes(32), DerivedPassword.GetBytes(16)))
                                    {
                                        using (MemoryStream MemStream = new MemoryStream(Convert.FromBase64String(encryptedString)))
                                        {
                                            using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                                            {
                                                byte[] DecryptedByte = new byte[1];

                                                int ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
                                                while (ByteCount > 0)
                                                {
                                                    _SecureString.AppendChar((char)DecryptedByte[0]);
                                                    ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                // Ensure managed array is cleared
                                if (Decrypted != null)
                                {
                                    Array.Clear(Decrypted, 0, Decrypted.Length);
                                }
                                Array.Clear(PasswordBytes, 0, PasswordSize);
                            }
                        }
                    }
                }
                finally
                {
                    // Ensure unmanaged memory is released.
                    if (PasswordPtr != IntPtr.Zero)
                    {
                        Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
                    }
                }
            }
        }
コード例 #49
0
        public static string Decrypt
        (
            string cipherText
        )
        {
            //Преобразование строк, определяющих характеристики ключа шифрования, в байтовые массивы.
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);

            //Преобразование нашего зашифрованного текста в массив байтов.
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            //Во-первых, мы должны создать пароль, из которого будет получен ключ
            //Этот пароль будет создан из указанной парольной фразы и значения соли.
            //Пароль будет создан с использованием указанного алгоритма хэша. Создание пароля может выполняться в нескольких итерациях.
            PasswordDeriveBytes password = new PasswordDeriveBytes
                                           (
                passPhrase,
                saltValueBytes,
                hashAlgorithm,
                passwordIterations
                                           );

            //Используйте пароль для создания псевдослучайных байтов для шифрования
            //ключа. Укажите размер ключа в байтах (вместо битов).
            byte[] keyBytes = password.GetBytes(keySize / 8);

            //Создать неинициализированный объект шифрования Rijndael.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            //Целесообразно установить режим шифрования "Цепочка блоков шифрования"
            //(CBC). Используйте параметры по умолчанию для других симметричных ключевых параметров.
            symmetricKey.Mode = CipherMode.CBC;

            //Создать дешифратор из существующих байтов ключа и инициализации
            //вектора. Размер ключа определяется на основе номера ключа
            //байты.
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor
                                         (
                keyBytes,
                initVectorBytes
                                         );

            //Определите поток памяти, который будет использоваться для хранения зашифрованных данных.
            MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

            //Определите криптографический поток (всегда используйте режим чтения для шифрования).
            CryptoStream cryptoStream = new CryptoStream
                                        (
                memoryStream,
                decryptor,
                CryptoStreamMode.Read
                                        );

            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            //Начните расшифровывать.
            int decryptedByteCount = cryptoStream.Read
                                     (
                plainTextBytes,
                0,
                plainTextBytes.Length
                                     );

            //Закройте оба потока.
            memoryStream.Close();
            cryptoStream.Close();

            //Преобразование расшифрованных данных в строку.
            //Предположим, что исходная строка открытого текста была UTF8-encoded.
            string plainText = Encoding.UTF8.GetString
                               (
                plainTextBytes,
                0,
                decryptedByteCount
                               );

            //Возвратите расшифрованную последовательность.
            return(plainText);
        }
コード例 #50
0
        public static byte[] Decrypt(byte[] CipherData, string Password)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

            return(Decrypt(CipherData, pdb.GetBytes(32), pdb.GetBytes(16)));
        }
コード例 #51
0
        public static string Decrypt
        (
            string cipherText,
            string passPhrase,
            string saltValue,
            string hashAlgorithm,
            int passwordIterations,
            string initVector,
            int keySize
        )
        {
            // Convert strings defining encryption key characteristics into byte arrays.
            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
                                        );

            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);
        }
コード例 #52
0
        /// <summary>
        ///     Encrypts specified plaintext using Rijndael symmetric key algorithm
        ///     and returns a base64-encoded result.
        /// </summary>
        /// <param name="plainText">
        ///     Plaintext value to be encrypted.
        /// </param>
        /// <param name="passPhrase">
        ///     Passphrase from which a pseudo-random password will be derived. The
        ///     derived password will be used to generate the encryption key.
        ///     Passphrase can be any string. In this example we assume that this
        ///     passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        ///     Salt value used along with passphrase to generate password. Salt can
        ///     be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <returns>
        ///     Encrypted value formatted as a base64-encoded string.
        /// </returns>
        public static string Encrypt(string plainText,
                                     string passPhrase,
                                     string saltValue)
        {
            // Convert strings 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("@IBAg3D4e5E6g7H5");
            byte [] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);

            // Convert our plaintext into a byte array.
            // Let us assume that plaintext contains UTF8-encoded characters.
            byte [] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // 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,
                EncryptorType,
                EncryptIterations);

            // 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);
            password.Dispose();

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged {
                Mode = CipherMode.CBC
            };

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

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


            // Define memory stream which will be used to hold encrypted data.
            string       cipherText   = string.Empty;
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = null;

            try {
                // Define cryptographic stream (always use Write mode for encryption).
                cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
                // Start encrypting.
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

                // Finish encrypting.
                cryptoStream.FlushFinalBlock();

                // Convert our encrypted data from a memory stream into a byte array.
                byte [] cipherTextBytes = memoryStream.ToArray();

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

                // Convert encrypted data into a base64-encoded string.
                cipherText = Convert.ToBase64String(cipherTextBytes);
            } catch {
                if (cryptoStream != null)
                {
                    cryptoStream.Close();
                }
            }

            // Return encrypted string.
            return(cipherText);
        }
コード例 #53
0
        /// <summary>
        /// Retrieve the string data from an encrypted file.   Retrieve assumes
        /// that Create was used to create the file.
        /// </summary>
        /// <param name="filename">File name to retrieve encrypted data from.</param>
        /// <param name="pswd">Password phrase used when data was encrypted.</param>
        /// <returns>Unencrypted string contents of file</returns>
        static public string Retrieve(string filename, string pswd)
        {
            FileStream fs = null;

            byte[] salt = new byte[IV_SIZE];
            byte[] enc  = null;
            try
            {
                fs = File.OpenRead(filename);
                fs.Read(salt, 0, salt.Length);
                enc = new byte[fs.Length - salt.Length];
                fs.Read(enc, 0, enc.Length);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }

            // create the key from the password phrase
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(pswd, salt);

            byte[] key = pdb.GetBytes(KEY_SIZE);

            // Create an instance of the RijndaelManaged class
            RijndaelManaged rm      = new RijndaelManaged();
            CryptoStream    cs      = null;
            MemoryStream    ms      = null;
            MemoryStream    ms2     = null;
            string          outdata = null;

            try
            {
                ms  = new MemoryStream(enc);                            // memory stream to read encrypted data from
                ms2 = new MemoryStream();                               // decrypted memory stream
                cs  = new CryptoStream(ms, rm.CreateDecryptor(key, salt), CryptoStreamMode.Read);
                byte[] ta    = new byte[256];
                int    count = 0;
                while (true)
                {
                    count = cs.Read(ta, 0, ta.Length);
                    if (count <= 0)
                    {
                        break;
                    }
                    ms2.Write(ta, 0, count);
                }
                ta      = ms2.ToArray();
                outdata = Encoding.UTF8.GetString(ta);
            }
            finally
            {
                if (cs != null)
                {
                    cs.Close();
                }
                if (ms != null)
                {
                    ms.Close();
                }
                if (ms2 != null)
                {
                    ms2.Close();
                }
            }

            return(outdata);
        }
コード例 #54
0
        /// <summary>
        ///     Decrypts specified ciphertext using Rijndael symmetric key algorithm.
        /// </summary>
        /// <param name="cipherText">
        ///     Base64-formatted ciphertext value.
        /// </param>
        /// <param name="passPhrase">
        ///     Passphrase from which a pseudo-random password will be derived. The
        ///     derived password will be used to generate the encryption key.
        ///     Passphrase can be any string. In this example we assume that this
        ///     passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        ///     Salt value used along with passphrase to generate password. Salt can
        ///     be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <returns>
        ///     Decrypted string value.
        /// </returns>
        /// <remarks>
        ///     Most of the logic in this function is similar to the Encrypt
        ///     logic. In order for decryption to work, all parameters of this function
        ///     - except cipherText value - must match the corresponding parameters of
        ///     the Encrypt function which was called to generate the
        ///     ciphertext.
        /// </remarks>
        public static string Decrypt(string cipherText,
                                     string passPhrase,
                                     string saltValue)
        {
            // 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("@IBAg3D4e5E6g7H5");
            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,
                EncryptorType,
                EncryptIterations);

            // 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);
            password.Dispose();

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged {
                Mode = CipherMode.CBC
            };

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

            // 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 = 0;

            try {
                decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            } catch (Exception) {
                return("");
            }

            // Close both streams.
            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);
        }
コード例 #55
0
ファイル: AES.cs プロジェクト: h5p9sl/Crypto-Notepad
        public static string Decrypt(string cipherText, string password, string salt = "Kosher",
                                     string hashAlgorithm   = "SHA1",
                                     int passwordIterations = 2,
                                     int keySize            = 256)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                return(null);
            }
            if (string.IsNullOrEmpty(password))
            {
                return(null);
            }

            byte[] initialVectorBytes;
            byte[] saltValueBytes;
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            // Extract metadata from file
            AESMetadata metadata = new AESMetadata();

            if (!metadata.GetMetadata(cipherTextBytes))
            {
                // Metadata parsing error
                DialogResult result = MessageBox.Show("Unable to parse file metadata.\nAttempt to open anyway?\n(May result in a \'Incorrect Key\' error if the salt is wrong.)",
                                                      "Missing or Corrupted Metadata", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk);
                if (result == DialogResult.Yes)
                {
                    // Default initialization vector from builds v1.1.2 and older
                    const string default_IV = "16CHARSLONG12345";

                    initialVectorBytes = Encoding.ASCII.GetBytes(default_IV);
                    saltValueBytes     = Encoding.ASCII.GetBytes(salt);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                saltValueBytes     = metadata.Salt;
                initialVectorBytes = metadata.InitialVector;
                metadata.DeleteMetadataFromBuffer(ref cipherTextBytes);
            }

            PasswordDeriveBytes derivedPassword = new PasswordDeriveBytes
                                                      (password, saltValueBytes, hashAlgorithm, passwordIterations);

            byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);

            RijndaelManaged symmetricKey = new RijndaelManaged();

            symmetricKey.Mode = CipherMode.CBC;

            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
            int    byteCount      = 0;

            using (MemoryStream memStream = new MemoryStream(cipherTextBytes))
            {
                using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor
                                                        (keyBytes, initialVectorBytes))
                {
                    using (CryptoStream cryptoStream
                               = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                    {
                        byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }

                symmetricKey.Dispose();
            }

            return(Encoding.UTF8.GetString(plainTextBytes, 0, byteCount));
        }
コード例 #56
0
        public static string Decrypt(string cipherText, string passPhrase, string saltValue)
        {
            string hashAlgorithm      = "SHA512";
            int    passwordIterations = 1000;
            string initVector         = "";
            int    keySizeInBytes     = 32;

            //if (keySize >= 256 && (hashAlgorithm != "SHA256" && hashAlgorithm != "SHA384" && hashAlgorithm != "SHA512"))
            //    throw new Exception("Selected hash algorithm is not capable of returning the keysize");

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

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

            // Convert our passPhrase into a byte array.
            byte[] passPhraseBytes = Encoding.UTF8.GetBytes(passPhrase);

            // 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(passPhraseBytes, saltValueBytes, hashAlgorithm, passwordIterations);

            //Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(passPhrase, saltValueBytes, 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(keySizeInBytes);

            byte[] initVectorBytes;
            if (initVector == "")
            {
                password.Reset();
                initVectorBytes = password.GetBytes(16);
            }
            else
            {
                initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            }

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

            symmetricKey.Padding = PaddingMode.PKCS7;

            // 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.
            plainText = plainText.Replace("\0", "");
            return(plainText);
        }
コード例 #57
0
        public string CipherText(string objText, string convertTool)
        {
            string passPhrase = "Rajeev Biswas";
            string saltValue  = "Vipin Gera";
            string initVector = "Infocept Pty Ltd.";
            string cipherText;

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

                PasswordDeriveBytes password = new PasswordDeriveBytes
                                               (
                    passPhrase,
                    saltValueBytes,
                    hashAlgorithm,
                    passwordIterations
                                               );
                byte[]          keyBytes     = password.GetBytes(keySize / 8);
                RijndaelManaged symmetricKey = new RijndaelManaged();
                symmetricKey.Mode = CipherMode.CBC;
                ICryptoTransform encryptor = symmetricKey.CreateEncryptor
                                             (
                    keyBytes,
                    initVectorBytes
                                             );
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream
                                            (
                    memoryStream,
                    encryptor,
                    CryptoStreamMode.Write
                                            );
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                cryptoStream.FlushFinalBlock();
                byte[] cipherTextBytes = memoryStream.ToArray();
                memoryStream.Close();
                cryptoStream.Close();
                cipherText = Convert.ToBase64String(cipherTextBytes);
                cipherText = HttpUtility.UrlEncode(cipherText);
            }
            else
            {
                int    keySize            = 256;
                int    passwordIterations = 03;
                string hashAlgorithm      = "MD5";
                try
                {
                    cipherText = HttpUtility.UrlDecode(objText);
                    byte[] initVectorBytes       = Encoding.ASCII.GetBytes(initVector);
                    byte[] saltValueBytes        = Encoding.ASCII.GetBytes(saltValue);
                    byte[] cipherTextBytes       = Convert.FromBase64String(cipherText);
                    PasswordDeriveBytes password = new PasswordDeriveBytes
                                                   (
                        passPhrase,
                        saltValueBytes,
                        hashAlgorithm,
                        passwordIterations
                                                   );
                    byte[]          keyBytes     = password.GetBytes(keySize / 8);
                    RijndaelManaged symmetricKey = new RijndaelManaged();
                    symmetricKey.Mode = CipherMode.CBC;
                    ICryptoTransform decryptor = symmetricKey.CreateDecryptor
                                                 (
                        keyBytes,
                        initVectorBytes
                                                 );
                    MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
                    CryptoStream cryptoStream = new CryptoStream
                                                (
                        memoryStream,
                        decryptor,
                        CryptoStreamMode.Read
                                                );
                    byte[] plainTextBytes     = new byte[cipherTextBytes.Length];
                    int    decryptedByteCount = cryptoStream.Read
                                                (
                        plainTextBytes,
                        0,
                        plainTextBytes.Length
                                                );
                    memoryStream.Close();
                    cryptoStream.Close();
                    cipherText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                }
                catch (Exception ex)
                {
                    cipherText = "";
                }
            }
            return(cipherText);
        }
コード例 #58
0
ファイル: Encryption.cs プロジェクト: sagius-li/Lydia
        private static byte[] Encrypt(byte[] clearData, string Password)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

            return(Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16)));
        }
コード例 #59
0
ファイル: Common.cs プロジェクト: himanshujoshi19/Test
    public static byte[] Encrypt(byte[] clearData, string Password)
    {
        // We need to turn the password into Key and IV. 
        // We are using salt to make it harder to guess our key
        // using a dictionary attack - 
        // trying to guess a password by enumerating all possible words. 
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});

        // Now get the key/IV and do the encryption using the function
        // that accepts byte arrays. 
        // Using PasswordDeriveBytes object we are first getting
        // 32 bytes for the Key 
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV. 
        // IV should always be the block size, which is by default
        // 16 bytes (128 bit) for Rijndael. 
        // If you are using DES/TripleDES/RC2 the block size is 8
        // bytes and so should be the IV size. 
        // You can also read KeySize/BlockSize properties off the
        // algorithm to find out the sizes. 
        return Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16));

    }
コード例 #60
0
ファイル: CryptoUtils.cs プロジェクト: vkuttyp/websitepanel
        public string Encrypt(string InputText)
        {
            string Password = CryptoKey;

            if (!EncryptionEnabled)
            {
                return(InputText);
            }

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

            // We are now going to create an instance of the
            // Rihndael class.
            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            // First we need to turn the input strings into a byte array.
            byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);


            // We are using salt to make it harder to guess our key
            // using a dictionary attack.
            byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());


            // The (Secret Key) will be generated from the specified
            // password and salt.
            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);


            // Create a encryptor from the existing SecretKey bytes.
            // We use 32 bytes for the secret key
            // (the default Rijndael key length is 256 bit = 32 bytes) and
            // then 16 bytes for the IV (initialization vector),
            // (the default Rijndael IV length is 128 bit = 16 bytes)
            ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));


            // Create a MemoryStream that is going to hold the encrypted bytes
            MemoryStream memoryStream = new MemoryStream();


            // Create a CryptoStream through which we are going to be processing 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. (always use write mode for encryption)
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);

            // Start the encryption process.
            cryptoStream.Write(PlainText, 0, PlainText.Length);


            // Finish encrypting.
            cryptoStream.FlushFinalBlock();

            // Convert our encrypted data from a memoryStream into a byte array.
            byte[] CipherBytes = memoryStream.ToArray();



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



            // Convert encrypted data into a base64-encoded string.
            // A common mistake would be to use an Encoding class for that.
            // It does not work, because not all byte values can be
            // represented by characters. We are going to be using Base64 encoding
            // That is designed exactly for what we are trying to do.
            string EncryptedData = Convert.ToBase64String(CipherBytes);



            // Return encrypted string.
            return(EncryptedData);
        }