コード例 #1
0
    //Encrypts the save file to prevent modification
    public static void EncryptFile(string path)
    {
        if(!File.Exists(path))
        {
            Debug.Log("File Not Found At: " + path);
            return;
        }

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

        xmlFile.Save(path);
    }
コード例 #2
0
ファイル: Encryption.cs プロジェクト: Syriamanal/xprotect
    public static byte[] Encrypt(byte[] data, string password)
    {
        byte[] result = null;
            byte[] passwordBytes = Encoding.Default.GetBytes(password);

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = keySize;
                    AES.BlockSize = 128;
                    var key = new Rfc2898DeriveBytes(passwordBytes, salt, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);
                    AES.Mode = CipherMode.CBC;
                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(data, 0, data.Length);
                        cs.Close();
                    }
                    result = ms.ToArray();
                }

            }
            return result;
    }
コード例 #3
0
    /// <summary>
    /// Encrypt string using AES 128
    /// </summary>
    /// <param name="plaintext"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string Encrypt(string plaintext, string key)
    {
        byte[] keybytes = Encoding.UTF8.GetBytes(key);

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

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

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

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

        cs.FlushFinalBlock();

        byte[] cipherBytes = ms.ToArray();

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

        return Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
    }
コード例 #4
0
ファイル: AES.cs プロジェクト: SteinLabs/Gravity
	public AES()
	{
		RijndaelManaged rm = new RijndaelManaged();
		_encryptor = rm.CreateEncryptor(_key, _vector);
		_decryptor = rm.CreateDecryptor(_key, _vector);
		encoder = new UTF8Encoding();
	}
コード例 #5
0
 // Token: 0x06000EF7 RID: 3831 RVA: 0x00045348 File Offset: 0x00043548
 public static string Encrypt(string unencrypted)
 {
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(SimpleAES.key, SimpleAES.vector);
     UTF8Encoding uTF8Encoding = new UTF8Encoding();
     return Convert.ToBase64String(SimpleAES.Encrypt(uTF8Encoding.GetBytes(unencrypted), encryptor));
 }
コード例 #6
0
ファイル: SimpleAES256.cs プロジェクト: JorgMU/AES256
    public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
    {
        byte[] encryptedBytes = null;

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

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

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

        AES.Mode = CipherMode.CBC;

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

        return encryptedBytes;
        //end public byte[] AES_Encrypt
    }
コード例 #7
0
 public static string Encrypt(string plainText, string passPhrase)
 {
     byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                     {
                         cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                         cryptoStream.FlushFinalBlock();
                         byte[] cipherTextBytes = memoryStream.ToArray();
                         return Convert.ToBase64String(cipherTextBytes);
                     }
                 }
             }
         }
     }
 }
コード例 #8
0
ファイル: XMLFileManager.cs プロジェクト: jcabe4/Reignite
    public static void EncryptFile(string path)
    {
        if (!File.Exists(path))
        {
            Debug.Log("File Not Found At: " + path);
            return;
        }

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

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

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

		// Return the encrypted bytes from the memory stream.
		return encrypted;
	}  
コード例 #10
0
 public static string Encrypt(string toEncrypt) 
 { 
     byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012"); 
     byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); 
     RijndaelManaged rDel = new RijndaelManaged(); 
     rDel.Key = keyArray; 
     rDel.Mode = CipherMode.ECB; 
     rDel.Padding = PaddingMode.PKCS7; 
     ICryptoTransform cTransform = rDel.CreateEncryptor(); 
     byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); 
     return Convert.ToBase64String(resultArray, 0, resultArray.Length); 
 }
コード例 #11
0
ファイル: crypto.cs プロジェクト: LihouzovS/Gwent
    public SimpleAES()
    {
        //Метод шифрования
        RijndaelManaged rm = new RijndaelManaged();

        //Создаем метод шифрования и дешифрования, используя для этого ключ и вектор
        EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
        DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);

        //Используем чтобы перевести байты в текст и наоборот
        UTFEncoder = new System.Text.UTF8Encoding();
    }
コード例 #12
0
ファイル: SimpleAES.cs プロジェクト: skuffe/MailClient
    public SimpleAES()
    {
        //This is our encryption method
        RijndaelManaged rm = new RijndaelManaged();

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

        //Used to translate bytes to text and vice versa
        UTFEncoder = new System.Text.UTF8Encoding();
    }
コード例 #13
0
    /// <summary>
    /// Constructor
    ///
    /// <param name="password">Public key
    public CsharpCryptography(string password)
    {
        //Encode digest
        var md5 = new MD5CryptoServiceProvider();
        _password = md5.ComputeHash(Encoding.UTF8.GetBytes(password));

        //Initialize objects
        _cipher = new RijndaelManaged();
        _cipher.Padding = PaddingMode.PKCS7;
        _decryptor = _cipher.CreateDecryptor(_password, IV);
        _encryptor = _cipher.CreateEncryptor(_password, IV);

    }
コード例 #14
0
    static Boolean Test(CipherMode md)
    {

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

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

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

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

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

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

        PrintByteArray(NewPlainText);
        
        if (!Compare(PlainText, NewPlainText)) {
        	Console.WriteLine("ERROR: roundtrip failed");
        	return false;
        }
        
        return true;
    }
コード例 #15
0
ファイル: XmlSaver.cs プロジェクト: CCCarrion/Star-Counter
	public string Encrypt(string toE)
	{
		//加密和解密采用相同的key,具体自己填,但是必须为32位//
		byte[] keyArray = UTF8Encoding.UTF8.GetBytes(KEY);
		RijndaelManaged rDel = new RijndaelManaged();
		rDel.Key = keyArray;
		rDel.Mode = CipherMode.ECB;
		rDel.Padding = PaddingMode.PKCS7;
		ICryptoTransform cTransform = rDel.CreateEncryptor();
		
		byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toE);
		byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray,0,toEncryptArray.Length);
		
		return Convert.ToBase64String(resultArray,0,resultArray.Length);
	}
コード例 #16
0
ファイル: Data_Deleter.cs プロジェクト: theslimreaper/DnD
    public void DeleteFile()
    {
        string output_file = "characters.xml";
        string character_directory = "Saved Data";
        List<string> keyList = new List<string>();
        List<string> contentList = new List<string>();
        UnicodeEncoding encoding = new UnicodeEncoding();
        byte[] key = null;
        RijndaelManaged RMCrypto = new RijndaelManaged();
        string currentPath = Directory.GetCurrentDirectory();
        Data_Loader Load = ScriptableObject.CreateInstance<Data_Loader>();
        Data_Saver Save = ScriptableObject.CreateInstance<Data_Saver>();
        List<string> tempList = new List<string>();

            contentList = Save.GetAllData();

        character_directory = Path.Combine(currentPath, character_directory);
        output_file = Path.Combine(character_directory, output_file);

        //Get key in byte form
        XML_Loader XML = ScriptableObject.CreateInstance<XML_Loader>();

        key = encoding.GetBytes(Data_Handler_Key.keyvalue);

        //Collect data to be saved and write it to an encrypted xml file using the key retrieved earlier
        FileStream encrypted_file = new FileStream(output_file, FileMode.Create);
        CryptoStream cryptography_stream = new CryptoStream(encrypted_file, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (StreamWriter swEncrypt = new StreamWriter(cryptography_stream))
            {
                swEncrypt.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                swEncrypt.WriteLine("<savedcharacters>");
                    foreach (var content in contentList)
                    {
                        swEncrypt.WriteLine(content);
                    }
                contentList.Clear();
                swEncrypt.WriteLine("</savedcharacters>");
            }
        }

        cryptography_stream.Close();
        encrypted_file.Close();

        tempList = Load.LoadCharacterIDs();
    }
コード例 #17
0
 public static string Encripta(string Cadena)
 {
     byte[] inputBytes = Encoding.ASCII.GetBytes(Cadena);
     byte[] encripted;
     RijndaelManaged cripto = new RijndaelManaged();
     using (MemoryStream ms = new MemoryStream(inputBytes.Length))
     {
         using (CryptoStream objCryptoStream = new CryptoStream(ms, cripto.CreateEncryptor(Clave, IV), CryptoStreamMode.Write))
         {
             objCryptoStream.Write(inputBytes, 0, inputBytes.Length);
             objCryptoStream.FlushFinalBlock();
             objCryptoStream.Close();
         }
         encripted = ms.ToArray();
     }
     return Convert.ToBase64String(encripted);
 }
コード例 #18
0
	// Protect a block of memory.
	internal static void Protect
				(byte[] userData, byte[] optionalEntropy,
				 MemoryProtectionScope scope, byte[] output)
			{
				// Get the key to use.
				byte[] key = GetScopeKey(scope, optionalEntropy);

				// Encrypt the block of memory using AES.
				Rijndael alg = new RijndaelManaged();
				alg.Mode = CipherMode.CFB;
				ICryptoTransform transform = alg.CreateEncryptor(key, null);
				transform.TransformBlock
					(userData, 0, userData.Length, output, 0);
				transform.Dispose();
				alg.Clear();
				Array.Clear(key, 0, key.Length);
			}
コード例 #19
0
    public static string EncryptMessage(byte[] text, string key)
    {
        RijndaelManaged aes = new RijndaelManaged();
        aes.KeySize = 256;
        aes.BlockSize = 256;
        aes.Padding = PaddingMode.Zeros;
        aes.Mode = CipherMode.CBC;

        aes.Key = Encoding.Default.GetBytes(key);
        aes.GenerateIV();

        string IV = ("-[--IV-[-" + Encoding.Default.GetString(aes.IV));

        ICryptoTransform AESEncrypt = aes.CreateEncryptor(aes.Key, aes.IV);
        byte[] buffer = text;

        return Convert.ToBase64String(Encoding.Default.GetBytes(Encoding.Default.GetString(AESEncrypt.TransformFinalBlock(buffer, 0, buffer.Length)) + IV));
    }
コード例 #20
0
ファイル: Security.cs プロジェクト: JingChen1988/Bubble
    /// <summary>
    /// Rijndael加密算法
    /// </summary>
    /// <param name="pString">待加密的明文</param>
    /// <param name="pKey">密钥,长度可以为:64位(byte[8]),128位(byte[16]),192位(byte[24]),256位(byte[32])</param>
    /// <param name="iv">iv向量,长度为128(byte[16])</param>
    /// <returns></returns>
    public static string RijndaelEncrypt(string pString, string pKey = KEY)
    {
        //密钥
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes(pKey);
        //待加密明文数组
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(pString);

        //Rijndael解密算法
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        rDel.Mode = CipherMode.ECB;
        rDel.Padding = PaddingMode.PKCS7;
        ICryptoTransform cTransform = rDel.CreateEncryptor();

        //返回加密后的密文
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
コード例 #21
0
 string Encrypt(string uncoded, string key)
 {
     RijndaelManaged cryptProvider = new RijndaelManaged();
     cryptProvider.KeySize = 256;
     cryptProvider.BlockSize = 256;
     cryptProvider.Mode = CipherMode.CBC;
     SHA256Managed hashSHA256 = new SHA256Managed();
     cryptProvider.Key = hashSHA256.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
     string iv = "user";
     cryptProvider.IV = hashSHA256.ComputeHash(ASCIIEncoding.ASCII.GetBytes(iv));
     byte[] plainTextByteArray = ASCIIEncoding.ASCII.GetBytes(uncoded);
     MemoryStream ms = new MemoryStream();
     CryptoStream cs = new CryptoStream(ms, cryptProvider.CreateEncryptor(), CryptoStreamMode.Write);
     cs.Write(plainTextByteArray, 0, plainTextByteArray.Length);
     cs.FlushFinalBlock();
     cs.Close();
     byte[] byt = ms.ToArray();
     return Convert.ToBase64String(byt);
 }
コード例 #22
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());
                }
            }
        }
    }
コード例 #23
0
    public string Encrypt(string plainText)
    {
        byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        //PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
		Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(passPhrase, System.Text.Encoding.UTF8.GetBytes(salt));
        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);
    }
コード例 #24
0
    static Boolean TestKnownEnc(Byte[] Key, Byte[] IV, Byte[] Plain, Byte[] Cipher, CipherMode mode, PaddingMode padding)
    {

        Byte[]  CipherCalculated;
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(Plain);
        Console.WriteLine("With the following Key:");
        PrintByteArray(Key);
        Console.WriteLine("and IV:");
        PrintByteArray(IV);
        Console.WriteLine("mode: " + mode + "     padding: " + padding);
		Console.WriteLine("Expecting this ciphertext:");
		PrintByteArray(Cipher);        
        
        RijndaelManaged     rjnd = new RijndaelManaged();

        rjnd.Mode = mode;
		rjnd.Padding = padding;
//		rjnd.BlockSize = 128;
//		rjnd.KeySize = 128;

        ICryptoTransform sse = rjnd.CreateEncryptor(Key, IV);
        MemoryStream 	ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(Plain,0,Plain.Length);
        cs.FlushFinalBlock();
        CipherCalculated = ms.ToArray();
        cs.Close();

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

        if (!Compare(Cipher, CipherCalculated)) {
        	Console.WriteLine("ERROR: result is different from the expected");
        	return false;
        }
        
        Console.WriteLine("OK");
        return true;
    }
コード例 #25
0
ファイル: KeyGen.cs プロジェクト: allanckw/GEMS-Web
    //Encrypts any string using the Rijndael algorithm.
    //input text: The string to encrypt.
    // returns A Base64 encrypted string.
    public static string Encrypt(string inputText)
    {
        //Create RijndaelManaged cipher for the symmetric algorithm from the key and initVector
        RijndaelManaged rijndaelCipher = new RijndaelManaged();
        rijndaelCipher.Key = key;
        rijndaelCipher.IV = initVector;

        byte[] plainText = Encoding.Unicode.GetBytes(inputText);

        using (ICryptoTransform enCrypter = rijndaelCipher.CreateEncryptor())
        {
            using (MemoryStream memStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memStream, enCrypter, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainText, 0, plainText.Length);
                    cryptoStream.FlushFinalBlock();
                    return Convert.ToBase64String(memStream.ToArray());
                }
            }
        }
    }
コード例 #26
0
    // Encrypt message with AES-256
    private static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0) throw new System.ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0) throw new System.ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0) throw new System.ArgumentNullException("IV");
        byte[] encrypted;

        // Create a RijndaelManaged object
        // with the specified key and IV.
        using (var rijAlg = new RijndaelManaged())
        {
            rijAlg.KeySize = 256;
            rijAlg.BlockSize = 256;
            rijAlg.Padding = PaddingMode.Zeros;
            rijAlg.Key = Key;
            rijAlg.IV = IV;

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

            // Create the streams used for encryption.
            using (var msEncrypt = new MemoryStream())
            {
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (var swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }

        // Return the encrypted bytes from the memory stream.
        return encrypted;
    }
コード例 #27
0
ファイル: crypto2.cs プロジェクト: LihouzovS/Gwent
    private static Stream CreateCryptoStreamAESWrite(string sharedSecret, Stream stream)
    {
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        // Генерация ключа
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

        // Создание объекта RijndaelManaged object
        RijndaelManaged aesAlg = new RijndaelManaged();
        aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

        // Создание дешифратора для выполнения потока преобразования
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        // Указать вначале IV
        stream.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
        stream.Write(aesAlg.IV, 0, aesAlg.IV.Length);

        CryptoStream csEncrypt = new CryptoStream(stream, encryptor, CryptoStreamMode.Write);
        return csEncrypt;
    }
コード例 #28
0
    private static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv) {
        // Check arguments.  
        if (plainText == null || plainText.Length <= 0) {
            throw new ArgumentNullException("plainText");
        }
        if (key == null || key.Length <= 0) {
            throw new ArgumentNullException("key");
        }
        if (iv == null || iv.Length <= 0) {
            throw new ArgumentNullException("key");
        }
        byte[] encrypted;
        // Create a RijndaelManaged object  
        // with the specified key and IV.  
        using (var rijAlg = new RijndaelManaged()) {
            rijAlg.Mode = CipherMode.CBC;
            rijAlg.Padding = PaddingMode.PKCS7;
            rijAlg.FeedbackSize = 128;

            rijAlg.Key = key;
            rijAlg.IV = iv;

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

            // Create the streams used for encryption.  
            using (var msEncrypt = new MemoryStream()) {
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) {
                    using (var swEncrypt = new StreamWriter(csEncrypt)) {
                        //Write all data to the stream.  
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        // Return the encrypted bytes from the memory stream.  
        return encrypted;
    }
コード例 #29
0
ファイル: Encryption.cs プロジェクト: Daloupe/Syzygy_Git
    public static string EncryptFile(string filePath)
    {
        Debug.Log("Encrypting");
        var output = String.Empty;
        try
        {
            using (RijndaelManaged aes = new RijndaelManaged())
            {
                byte[] key = ASCIIEncoding.UTF8.GetBytes(skey);

                byte[] IV = ASCIIEncoding.UTF8.GetBytes(vkey);

                using (FileStream fsCrypt = new FileStream(filePath + "uSave.dat", FileMode.Create))
                {
                    using (ICryptoTransform encryptor = aes.CreateEncryptor(key, IV))
                    {
                        using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
                        {
                            using (FileStream fsIn = new FileStream(filePath + "eSave.dat", FileMode.Open))
                            {
                                int data;

                                while ((data = fsIn.ReadByte()) != -1)
                                {
                                    cs.WriteByte((byte)data);
                                }
                                output = cs.ToString();
                            }
                        }
                    }
                }
            }
            //File.Delete(filePath + "uSave.dat");
        }
        catch{} // failed to encrypt file

        return output;
    }
コード例 #30
0
        protected void DecodeCertMono(McpeLogin message)
        {
            byte[] buffer = message.payload;

            if (message.payload.Length != buffer.Length)
            {
                Log.Debug($"Wrong lenght {message.payload.Length} != {message.payload.Length}");
                throw new Exception($"Wrong lenght {message.payload.Length} != {message.payload.Length}");
            }

            if (Log.IsDebugEnabled)
            {
                Log.Debug("Lenght: " + message.payload.Length + ", Message: " + buffer.EncodeBase64());
            }

            string certificateChain;
            string skinData;

            try
            {
                var destination = new MemoryStream(buffer);
                destination.Position = 0;
                NbtBinaryReader reader = new NbtBinaryReader(destination, false);

                var countCertData = reader.ReadInt32();
                certificateChain = Encoding.UTF8.GetString(reader.ReadBytes(countCertData));
                if (Log.IsDebugEnabled)
                {
                    Log.Debug($"Certificate Chain (Lenght={countCertData})\n{certificateChain}");
                }

                var countSkinData = reader.ReadInt32();
                skinData = Encoding.UTF8.GetString(reader.ReadBytes(countSkinData));
                if (Log.IsDebugEnabled)
                {
                    Log.Debug($"Skin data (Lenght={countSkinData})\n{skinData}");
                }
            }
            catch (Exception e)
            {
                Log.Error("Parsing login", e);
                return;
            }

            try
            {
                {
                    IDictionary <string, dynamic> headers = JWT.Headers(skinData);
                    dynamic payload = JObject.Parse(JWT.Payload(skinData));

                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug($"Skin JWT Header: {string.Join(";", headers)}");
                    }
                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug($"Skin JWT Payload:\n{payload.ToString()}");
                    }

                    try
                    {
                        _playerInfo.ClientId         = payload.ClientRandomId;
                        _playerInfo.CurrentInputMode = payload.CurrentInputMode;
                        _playerInfo.DefaultInputMode = payload.DefaultInputMode;
                        _playerInfo.DeviceModel      = payload.DeviceModel;
                        _playerInfo.DeviceOS         = payload.DeviceOS;
                        _playerInfo.GameVersion      = payload.GameVersion;
                        _playerInfo.GuiScale         = payload.GuiScale;
                        _playerInfo.LanguageCode     = payload.LanguageCode;
                        _playerInfo.ServerAddress    = payload.ServerAddress;
                        _playerInfo.UIProfile        = payload.UIProfile;

                        _playerInfo.Skin = new Skin()
                        {
                            CapeData         = Convert.FromBase64String((string)payload.CapeData),
                            SkinId           = payload.SkinId,
                            SkinData         = Convert.FromBase64String((string)payload.SkinData),
                            SkinGeometryName = payload.SkinGeometryName,
                            SkinGeometry     = Encoding.UTF8.GetString(Convert.FromBase64String((string)payload.SkinGeometry)),
                        };
                        Log.Warn($"Cape data lenght={_playerInfo.Skin.CapeData.Length}");
                    }
                    catch (Exception e)
                    {
                        Log.Error("Parsing skin data", e);
                    }
                }

                //var chainArray = chain.ToArray();

                string validationKey     = null;
                string identityPublicKey = null;
                //if (!isMono)
                {
                    dynamic json = JObject.Parse(certificateChain);

                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug($"Certificate JSON:\n{json}");
                    }

                    JArray chain = json.chain;

                    foreach (JToken token in chain)
                    {
                        IDictionary <string, dynamic> headers = JWT.Headers(token.ToString());

                        if (Log.IsDebugEnabled)
                        {
                            Log.Debug("Raw chain element:\n" + token.ToString());
                            Log.Debug($"JWT Header: {string.Join(";", headers)}");

                            dynamic jsonPayload = JObject.Parse(JWT.Payload(token.ToString()));
                            Log.Debug($"JWT Payload:\n{jsonPayload}");
                        }

                        // Mojang root x5u cert (string): MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V

                        if (!headers.ContainsKey("x5u"))
                        {
                            continue;
                        }

                        string x5u = headers["x5u"];

                        if (identityPublicKey == null)
                        {
                            if (CertificateData.MojangRootKey.Equals(x5u, StringComparison.InvariantCultureIgnoreCase))
                            {
                                Log.Debug("Key is ok, and got Mojang root");
                            }
                            else if (chain.Count > 1)
                            {
                                Log.Debug("Got client cert (client root)");
                                continue;
                            }
                            else if (chain.Count == 1)
                            {
                                Log.Debug("Selfsigned chain");
                            }
                        }
                        else if (identityPublicKey.Equals(x5u))
                        {
                            Log.Debug("Derived Key is ok");
                        }
                        // Validate

                        var key = PublicKeyFactory.CreateKey(x5u.DecodeBase64Url());

                        CertificateData data = CryptoUtils.Decode(token.ToString(), key);
                        if (data != null)
                        {
                            identityPublicKey = data.IdentityPublicKey;

                            if (Log.IsDebugEnabled)
                            {
                                Log.Debug("Decoded token success");
                            }

                            if (CertificateData.MojangRootKey.Equals(x5u, StringComparison.InvariantCultureIgnoreCase))
                            {
                                Log.Debug("Got Mojang key. Is valid = " + data.CertificateAuthority);
                                validationKey = data.IdentityPublicKey;
                            }
                            else if (validationKey != null && validationKey.Equals(x5u, StringComparison.InvariantCultureIgnoreCase))
                            {
                                _playerInfo.CertificateData = data;
                            }
                            else
                            {
                                if (data.ExtraData == null)
                                {
                                    continue;
                                }

                                // Self signed, make sure they don't fake XUID
                                if (data.ExtraData.Xuid != null)
                                {
                                    Log.Warn("Received fake XUID from " + data.ExtraData.DisplayName);
                                    data.ExtraData.Xuid = null;
                                }

                                _playerInfo.CertificateData = data;
                            }
                        }
                        else
                        {
                            Log.Error("Not a valid Identity Public Key for decoding");
                        }
                    }
                }

                //TODO: Implement disconnect here


                _playerInfo.Username = _playerInfo.CertificateData.ExtraData.DisplayName;
                _session.Username    = _playerInfo.Username;
                string identity = _playerInfo.CertificateData.ExtraData.Identity;

                if (Log.IsDebugEnabled)
                {
                    Log.Debug($"Connecting user {_playerInfo.Username} with identity={identity}");
                }
                _playerInfo.ClientUuid = new UUID(identity);

                bool useEncryption = (Config.GetProperty("UseEncryptionForAll", false) ||
                                      (Config.GetProperty("UseEncryption", true) &&
                                       !string.IsNullOrWhiteSpace(_playerInfo.CertificateData.ExtraData.Xuid)));

                if (useEncryption)
                {
                    var publicKey = PublicKeyFactory.CreateKey(_playerInfo.CertificateData.IdentityPublicKey.DecodeBase64Url());

                    string                    namedCurve = "secp384r1";
                    ECKeyPairGenerator        pGen       = new ECKeyPairGenerator();
                    ECKeyGenerationParameters genParam   = new ECKeyGenerationParameters(
                        SecNamedCurves.GetOid(namedCurve),
                        new SecureRandom());
                    pGen.Init(genParam);

                    AsymmetricCipherKeyPair keyPair = pGen.GenerateKeyPair();

                    ECDHBasicAgreement agreement = new ECDHBasicAgreement();
                    agreement.Init(keyPair.Private);

                    byte[] preHash = agreement.CalculateAgreement(publicKey).ToByteArray();

                    byte[] prepend = Encoding.UTF8.GetBytes("RANDOM SECRET");
                    byte[] secret;

                    SHA256Managed sha = new SHA256Managed();
                    using (var memoryStream = new MemoryStream())
                    {
                        memoryStream.Write(prepend, 0, prepend.Length);
                        memoryStream.Write(preHash, 0, preHash.Length);
                        memoryStream.Position = 0;
                        secret = sha.ComputeHash(memoryStream);
                    }
                    sha.Dispose();

                    //if (Log.IsDebugEnabled) Log.Debug($"SECRET KEY (b64, {secret.Length}):\n{secret.EncodeBase64()}");

                    {
                        RijndaelManaged rijAlg = new RijndaelManaged
                        {
                            BlockSize    = 128,
                            Padding      = PaddingMode.None,
                            Mode         = CipherMode.CFB,
                            FeedbackSize = 8,
                            Key          = secret,
                            IV           = secret.Take(16).ToArray(),
                        };

                        // Create a decrytor to perform the stream transform.
                        ICryptoTransform decryptor      = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
                        MemoryStream     inputStream    = new MemoryStream();
                        CryptoStream     cryptoStreamIn = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read);

                        ICryptoTransform encryptor       = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
                        MemoryStream     outputStream    = new MemoryStream();
                        CryptoStream     cryptoStreamOut = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write);

                        _session.CryptoContext = new CryptoContext
                        {
                            UseEncryption   = true,
                            Algorithm       = rijAlg,
                            Decryptor       = decryptor,
                            Encryptor       = encryptor,
                            InputStream     = inputStream,
                            OutputStream    = outputStream,
                            CryptoStreamIn  = cryptoStreamIn,
                            CryptoStreamOut = cryptoStreamOut
                        };


                        var pubKey1 = ((ECPublicKeyParameters)keyPair.Public);

                        byte[] asn = new byte[24]
                        {
                            0x30, 0x76, 0x30, 0x10, 0x6, 0x7, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x2,
                            0x1, 0x6, 0x5, 0x2b, 0x81, 0x4, 0x0, 0x22, 0x3, 0x62, 0x0, 0x4
                        };
                        string b64Key        = asn.Concat(ConvertToNCryptEccPublicBlob(pubKey1.Q).Skip(8)).ToArray().EncodeBase64();
                        var    handshakeJson = new HandshakeData()
                        {
                            salt = prepend.EncodeBase64()
                        };

                        string val = CryptoUtils.Encode(handshakeJson, keyPair.Private, JwsAlgorithm.ES384,
                                                        new Dictionary <string, object> {
                            { "x5u", b64Key }
                        });

                        var response = McpeServerToClientHandshake.CreateObject();
                        response.NoBatch    = true;
                        response.ForceClear = true;
                        response.token      = val;

                        _session.SendPackage(response);

                        if (Log.IsDebugEnabled)
                        {
                            Log.Warn($"Encryption enabled for {_session.Username}");
                        }
                    }
                }
                else
                {
                    _session.CryptoContext = new CryptoContext
                    {
                        UseEncryption = false
                    };

                    _session.MessageHandler.HandleMcpeClientToServerHandshake(null);
                }
            }
            catch (Exception e)
            {
                Log.Error("Decrypt", e);
            }
        }
コード例 #31
0
ファイル: UsuarioBC.cs プロジェクト: Odlir/talentosApp
        //public UsuarioBE UsuarioValidar(UsuarioBE objUsuarioBE)
        //{
        //    UsuarioDALC dalc = new UsuarioDALC();
        //    return dalc.UsuarioValidar(objUsuarioBE);

        //}

        //public UsuarioBE UsuarioValidarNickName(UsuarioBE objUsuarioBE)
        //{
        //    UsuarioDALC dalc = new UsuarioDALC();
        //    return dalc.UsuarioValidarNickName(objUsuarioBE);

        //}

        //public UsuarioBE UsuarioValidarLog(UsuarioBE objUsuarioBE)
        //{
        //    UsuarioDALC dalc = new UsuarioDALC();
        //    return dalc.UsuarioValidarLog(objUsuarioBE);

        //}

        //public int UsuarioInsertar(UsuarioBE objUsuarioBE)
        //{
        //    UsuarioDALC dalc = new UsuarioDALC();
        //    return dalc.UsuarioInsertar(objUsuarioBE);
        //}

        //public int LogInsertar(UsuarioBE objUsuarioBE)
        //{
        //    UsuarioDALC dalc = new UsuarioDALC();
        //    return dalc.LogInsertar(objUsuarioBE);
        //}


        public UsuarioBE EncriptarMd5(UsuarioBE objUsuario)
        {
            String llave = GenerarLlave("talentos");

            // Convierto la cadena y la clave en arreglos de bytes
            // para poder usarlas en las funciones de encriptacion
            byte[] cadenaBytes = Encoding.UTF8.GetBytes(objUsuario.Password);
            byte[] claveBytes  = Encoding.UTF8.GetBytes(llave);

            // Creo un objeto de la clase Rijndael
            RijndaelManaged rij = new RijndaelManaged();

            // Configuro para que utilice el modo ECB
            rij.Mode = CipherMode.ECB;

            // Configuro para que use encriptacion de 256 bits.
            rij.BlockSize = 256;

            // Declaro que si necesitara mas bytes agregue ceros.
            rij.Padding = PaddingMode.Zeros;

            // Declaro un encriptador que use mi clave secreta y un vector
            // de inicializacion aleatorio
            ICryptoTransform encriptador;

            encriptador = rij.CreateEncryptor(claveBytes, rij.IV);

            // Declaro un stream de memoria para que guarde los datos
            // encriptados a medida que se van calculando
            MemoryStream memStream = new MemoryStream();

            // Declaro un stream de cifrado para que pueda escribir aqui
            // la cadena a encriptar. Esta clase utiliza el encriptador
            // y el stream de memoria para realizar la encriptacion
            // y para almacenarla
            CryptoStream cifradoStream;

            cifradoStream = new CryptoStream(memStream, encriptador, CryptoStreamMode.Write);

            // Escribo los bytes a encriptar. A medida que se va escribiendo
            // se va encriptando la cadena
            cifradoStream.Write(cadenaBytes, 0, cadenaBytes.Length);

            // Aviso que la encriptación se terminó
            cifradoStream.FlushFinalBlock();

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

            // Cierro los dos streams creados
            memStream.Close();
            cifradoStream.Close();

            // Convierto el resultado en base 64 para que sea legible
            // y devuelvo el resultado
            String resultado = Convert.ToBase64String(cipherTextBytes);

            UsuarioBE obj = new UsuarioBE();

            obj          = objUsuario;
            obj.Password = resultado;

            return(obj);
        }
コード例 #32
0
        static public XmlDocument SerializeResponse(XmlDocument aXmlDocumentDS, bool aZip, bool aCrypt, byte[] aEncryptionKey)
        {
            XmlDocument aXmlResponse = new XmlDocument();

            aXmlResponse.LoadXml("<d/>");
            aEncryptionKey = (aEncryptionKey != null && aEncryptionKey.Length == 16) ? aEncryptionKey : System.Text.Encoding.ASCII.GetBytes("1234567890123456");
            try
            {
                aXmlResponse.DocumentElement.Attributes.Append(aXmlResponse.CreateAttribute("zip"));
                aXmlResponse.DocumentElement.Attributes["zip"].Value = aZip ? "1" : "0";
                aXmlResponse.DocumentElement.Attributes.Append(aXmlResponse.CreateAttribute("crypt"));
                aXmlResponse.DocumentElement.Attributes["crypt"].Value = aCrypt ? "1" : "0";
                XmlCDataSection aCData = aXmlResponse.CreateCDataSection("");
                aXmlResponse.DocumentElement.AppendChild(aCData);

                byte [] aBytes = System.Text.Encoding.UTF8.GetBytes(aXmlDocumentDS.DocumentElement.OuterXml);

                aXmlResponse.DocumentElement.Attributes.Append(aXmlResponse.CreateAttribute("size"));
                aXmlResponse.DocumentElement.Attributes["size"].Value = aBytes.Length.ToString();

                if (aZip)
                {
                    int          aBufLen   = 32000;
                    int          aOff      = 0;
                    MemoryStream aWholeZip = new MemoryStream();
                    while (aOff < aBytes.Length)
                    {
                        int aLen = (aBytes.Length - aOff) > aBufLen ? aBufLen : (aBytes.Length - aOff);

                        MemoryStream aOutput = new MemoryStream();
                        System.IO.Compression.DeflateStream aDeflateStream = new DeflateStream(aOutput, CompressionMode.Compress, true);
                        aDeflateStream.Write(aBytes, aOff, aLen);
                        aDeflateStream.Close();
                        byte[] aChunk     = aOutput.ToArray();
                        byte[] aChunkSize = BitConverter.GetBytes((Int16)aChunk.Length);
                        aWholeZip.Write(aChunkSize, 0, aChunkSize.Length);
                        aWholeZip.Write(aChunk, 0, aChunk.Length);
                        aOff += aLen;
                    }
                    // zero length at the end
                    aWholeZip.Write(BitConverter.GetBytes((Int16)0), 0, 2);
                    aBytes = aWholeZip.ToArray();
                }

                if (aCrypt)
                {
                    Rijndael iCryptoService = new RijndaelManaged();
                    iCryptoService.KeySize   = 128;
                    iCryptoService.BlockSize = 256;
                    iCryptoService.Mode      = CipherMode.ECB;//.CBC;//.ECB;

                    MemoryStream aMemoryStream = new MemoryStream();
                    iCryptoService.GenerateIV();
                    byte[]       aIv           = iCryptoService.IV;
                    CryptoStream aCryptoStream = new CryptoStream(aMemoryStream, iCryptoService.CreateEncryptor(aEncryptionKey, aIv), CryptoStreamMode.Write);
                    aCryptoStream.Write(aBytes, 0, aBytes.Length);
                    aCryptoStream.FlushFinalBlock();
                    aBytes = new byte[aMemoryStream.Length];
                    aMemoryStream.Position = 0;
                    aMemoryStream.Read(aBytes, 0, aBytes.Length);
                }

                // base64 encoding 3:4
                aCData.Data = System.Convert.ToBase64String(aBytes);
            }
            catch (Exception e)
            {
                string aDebug = e.Message;
                throw e;
            }
            return(aXmlResponse);
        }
コード例 #33
0
ファイル: RijndaelManagedTest.cs プロジェクト: weeble/mono
        public void ECB()
        {
            byte[] plaintext = new byte[16];
            byte[] iv        = new byte[16];

            for (int i = 0; i < 16; i++)
            {
                plaintext[i] = (byte)(i * 16 + i);
            }

            RijndaelManaged r = new RijndaelManaged();

            r.Mode    = CipherMode.ECB;
            r.Padding = PaddingMode.Zeros;

            byte[] key16 = new byte[16];
            byte[] key24 = new byte[24];
            byte[] key32 = new byte[32];

            for (int i = 0; i < 32; i++)
            {
                if (i < 16)
                {
                    key16[i] = (byte)i;
                }
                if (i < 24)
                {
                    key24[i] = (byte)i;
                }
                key32[i] = (byte)i;
            }


            byte[] exp16 = { 0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30,
                             0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a };
            byte[] exp24 = { 0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0,
                             0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71, 0x91 };
            byte[] exp32 = { 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf,
                             0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 };

            r.Key     = key16;
            r.KeySize = 128;
            CheckECBRoundtrip(
                r.CreateEncryptor(key16, iv), r.CreateDecryptor(key16, iv),
                plaintext, exp16
                );


            r.Key     = key24;
            r.KeySize = 192;
            CheckECBRoundtrip(
                r.CreateEncryptor(key24, iv), r.CreateDecryptor(key24, iv),
                plaintext, exp24
                );


            r.Key     = key32;
            r.KeySize = 256;
            CheckECBRoundtrip(
                r.CreateEncryptor(key32, iv), r.CreateDecryptor(key32, iv),
                plaintext, exp32
                );
        }
コード例 #34
0
        /// <summary>
        /// Encrypt scoped PDU using AES encryption protocol
        /// </summary>
        /// <param name="unencryptedData">Unencrypted scoped PDU byte array</param>
        /// <param name="key">Encryption key. Key has to be at least 32 bytes is length</param>
        /// <param name="engineBoots">Engine boots.</param>
        /// <param name="engineTime">Engine time.</param>
        /// <param name="privacyParameters">Privacy parameters out buffer. This field will be filled in with information
        /// required to decrypt the information. Output length of this field is 8 bytes and space has to be reserved
        /// in the USM header to store this information</param>
        /// <returns>Encrypted byte array</returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key is null or length of the encryption key is too short.</exception>
        internal byte[] Encrypt(byte[] unencryptedData, byte[] key, int engineBoots, int engineTime, byte[] privacyParameters)
        {
#if NETSTANDARD1_3
            throw new PlatformNotSupportedException();
#elif NETCOREAPP2_0
            throw new PlatformNotSupportedException();
#else
            // check the key before doing anything else
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (key.Length < KeyBytes)
            {
                throw new ArgumentOutOfRangeException(nameof(key), "Invalid key length.");
            }

            if (unencryptedData == null)
            {
                throw new ArgumentNullException(nameof(unencryptedData));
            }

            var iv = new byte[16];

            // Set privacy parameters to the local 64 bit salt value
            var bootsBytes = BitConverter.GetBytes(engineBoots);
            iv[0] = bootsBytes[3];
            iv[1] = bootsBytes[2];
            iv[2] = bootsBytes[1];
            iv[3] = bootsBytes[0];
            var timeBytes = BitConverter.GetBytes(engineTime);
            iv[4] = timeBytes[3];
            iv[5] = timeBytes[2];
            iv[6] = timeBytes[1];
            iv[7] = timeBytes[0];

            // Copy salt value to the iv array
            Buffer.BlockCopy(privacyParameters, 0, iv, 8, PrivacyParametersLength);

            using (var rm = new RijndaelManaged())
            {
                rm.KeySize      = KeyBytes * 8;
                rm.FeedbackSize = 128;
                rm.BlockSize    = 128;

                // we have to use Zeros padding otherwise we get encrypt buffer size exception
                rm.Padding = PaddingMode.Zeros;
                rm.Mode    = CipherMode.CFB;

                // make sure we have the right key length
                var pkey = new byte[MinimumKeyLength];
                Buffer.BlockCopy(key, 0, pkey, 0, MinimumKeyLength);
                rm.Key = pkey;
                rm.IV  = iv;
                using (var cryptor = rm.CreateEncryptor())
                {
                    var encryptedData = cryptor.TransformFinalBlock(unencryptedData, 0, unencryptedData.Length);

                    // check if encrypted data is the same length as source data
                    if (encryptedData.Length != unencryptedData.Length)
                    {
                        // cut out the padding
                        var tmp = new byte[unencryptedData.Length];
                        Buffer.BlockCopy(encryptedData, 0, tmp, 0, unencryptedData.Length);
                        return(tmp);
                    }

                    return(encryptedData);
                }
            }
#endif
        }
コード例 #35
0
        public static string Encrypt(
            string value,
            SecureString password,
            SecureString salt,
            SecureString passwordIterations,
            SecureString initialVector,
            SecureString keySize)
        {
            try
            {
                if (string.IsNullOrEmpty(value))
                {
                    return(value);
                }

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

                try
                {
                    saltBytes          = Encoding.ASCII.GetBytes(salt.ToUnsecureString());
                    initialVectorBytes = Encoding.ASCII.GetBytes(initialVector.ToUnsecureString());

                    using (var rfcDeriveBytes = new Rfc2898DeriveBytes(password.ToUnsecureString(), saltBytes, Convert.ToInt32(passwordIterations.ToUnsecureString())))
                        using (var rijndaelManaged = new RijndaelManaged {
                            Mode = CipherMode.CBC
                        })
                        {
                            derivedBytes = rfcDeriveBytes.GetBytes(Convert.ToInt32(keySize.ToUnsecureString()) / 8);
                            using (var encryptor = rijndaelManaged.CreateEncryptor(derivedBytes, initialVectorBytes))
                                using (var memoryStream = new MemoryStream())
                                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                                    {
                                        valueBytes = Encoding.UTF8.GetBytes(value);
                                        cryptoStream.Write(valueBytes, 0, valueBytes.Length);
                                        cryptoStream.FlushFinalBlock();
                                        buffer = memoryStream.ToArray();
                                        memoryStream.Close();
                                        cryptoStream.Close();
                                        rijndaelManaged.Clear();
                                        return(Convert.ToBase64String(buffer));
                                    }
                        }
                }
                finally
                {
                    if (valueBytes != null)
                    {
                        Array.Clear(valueBytes, 0, valueBytes.Length);
                    }
                    if (buffer != null)
                    {
                        Array.Clear(buffer, 0, buffer.Length);
                    }
                    if (saltBytes != null)
                    {
                        Array.Clear(saltBytes, 0, saltBytes.Length);
                    }
                    if (initialVectorBytes != null)
                    {
                        Array.Clear(initialVectorBytes, 0, initialVectorBytes.Length);
                    }
                    if (derivedBytes != null)
                    {
                        Array.Clear(derivedBytes, 0, derivedBytes.Length);
                    }
                }
            }
            finally
            {
                SecureStringCleanup(password, salt, passwordIterations, initialVector, keySize);
            }
        }
コード例 #36
0
        protected void SubmitPreferencesButton_Click(object sender, EventArgs e)
        {
            //No Need for Validation
            DBConnect dbConnection = new DBConnect();
            SqlCommand objCommand = new SqlCommand();
            objCommand.CommandType = CommandType.StoredProcedure;
            objCommand.CommandText = "TPUpdateUserPreference";
            SqlParameter inputParameter = new SqlParameter("@Email", Session["userEmail"].ToString());
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            inputParameter = new SqlParameter("@Login", LoginPreferenceDropDown.SelectedValue);
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            inputParameter = new SqlParameter("@Theme", ThemePreferenceDropDown.SelectedValue);
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            inputParameter = new SqlParameter("@ProfileInfoPrivacy", ProfileInfoPrivacyPreferenceDropDown.SelectedValue);
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            inputParameter = new SqlParameter("@PhotoPrivacy", PhotoPrivacyDropDown.SelectedValue);
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            inputParameter = new SqlParameter("@PersonalContactInfoPrivacy", PersonalContactInfoDropDown.SelectedValue);
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            int ResponseRecevied = dbConnection.DoUpdateUsingCmdObj(objCommand);

            String plainTextEmail = Session["userEmail"].ToString();
            String plainTextPassword = Session["userPassword"].ToString();
            String encryptedEmail;
            String encryptedPassword;
            UTF8Encoding encoder = new UTF8Encoding();
            Byte[] emailBytes;
            Byte[] passwordBytes;

            emailBytes = encoder.GetBytes(plainTextEmail);
            passwordBytes = encoder.GetBytes(plainTextPassword);
            RijndaelManaged rmEncryption = new RijndaelManaged();
            MemoryStream memStream = new MemoryStream();
            CryptoStream encryptionStream = new CryptoStream(memStream, rmEncryption.CreateEncryptor(key, vector), CryptoStreamMode.Write);


            if (ResponseRecevied == 1)
            {
                //Preferences Updated 
                if (LoginPreferenceDropDown.SelectedValue == "NONE")
                {
                    //Do Nothing
                    Response.Redirect("Feed.aspx");
                }
                if (LoginPreferenceDropDown.SelectedValue == "Auto-Login")
                {
                    //Auto Login
                    //Email
                    encryptionStream.Write(emailBytes, 0, emailBytes.Length);
                    encryptionStream.FlushFinalBlock();

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

                    encryptionStream.Close();
                    memStream.Close();

                    //password
                    memStream = new MemoryStream();
                    encryptionStream = new CryptoStream(memStream, rmEncryption.CreateEncryptor(key, vector), CryptoStreamMode.Write);

                    encryptionStream.Write(passwordBytes, 0, passwordBytes.Length);
                    encryptionStream.FlushFinalBlock();

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

                    encryptionStream.Close();
                    memStream.Close();

                    encryptedEmail = Convert.ToBase64String(encryptedEmailBytes);
                    encryptedPassword = Convert.ToBase64String(encryptedPasswordBytes);

                    HttpCookie myCookie = new HttpCookie("LoginCookie");
                    myCookie.Values["Email"] = encryptedEmail;
                    myCookie.Expires = new DateTime(2020, 2, 1);
                    myCookie.Values["Password"] = encryptedPassword;
                    myCookie.Expires = new DateTime(2020, 2, 1);
                    Response.Cookies.Add(myCookie);
                    Response.Redirect("Feed.aspx");
                }
                if (LoginPreferenceDropDown.SelectedValue == "Fast-Login")
                {
                    encryptionStream.Write(emailBytes, 0, emailBytes.Length);
                    encryptionStream.FlushFinalBlock();

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

                    encryptionStream.Close();
                    memStream.Close();

                    encryptedEmail = Convert.ToBase64String(encryptedEmailBytes);

                    HttpCookie myCookie = new HttpCookie("LoginCookie");
                    myCookie.Values["Email"] = encryptedEmail;
                    myCookie.Expires = new DateTime(2020, 2, 1);
                    Response.Cookies.Add(myCookie);
                    Response.Redirect("Feed.aspx");
                }
            }
        }
コード例 #37
0
        static void Main(string[] args)
        {
            const int n      = 100 * 1000;
            var       sw     = new Stopwatch();
            Random    r      = new Random();
            var       data   = new byte[1024];
            var       key8B  = new byte[8];
            var       key16B = new byte[16];
            var       key24B = new byte[24];
            var       key32B = new byte[32];

            r.NextBytes(data);
            r.NextBytes(key8B);
            r.NextBytes(key16B);
            r.NextBytes(key24B);
            r.NextBytes(key32B);
            Action <string> outputToConsole = (s) =>
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(s);
            };

            // AES
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("AES");
            var aes = new AesCryptoServiceProvider();

            aes.Padding = PaddingMode.PKCS7;
            aes.Key     = key16B;
            Action doAes = () => EncryptDecryptAndDispose(aes.CreateEncryptor(), aes.CreateDecryptor(), data);

            doAes.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            aes.Dispose();

            // RSA
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("DES");
            var des = new DESCryptoServiceProvider();

            des.IV  = key8B;
            des.Key = key8B;
            Action doDes = () => EncryptDecryptAndDispose(des.CreateEncryptor(), des.CreateDecryptor(), data);

            doDes.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            des.Dispose();

            // RC2
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("RC2");
            var rc2 = new RC2CryptoServiceProvider();

            rc2.IV  = key8B;
            rc2.Key = key8B;
            Action doRc2 = () => EncryptDecryptAndDispose(rc2.CreateEncryptor(), rc2.CreateDecryptor(), data);

            doRc2.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            rc2.Dispose();

            // Rijndael
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("Rijndael");
            var rijndael = new RijndaelManaged();

            rijndael.IV  = key16B;
            rijndael.Key = key16B;
            Action doRijndael = () => EncryptDecryptAndDispose(rijndael.CreateEncryptor(), rijndael.CreateDecryptor(), data);

            doRijndael.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            rijndael.Dispose();

            // 3DES
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("3DES");
            var tripleDes = new TripleDESCryptoServiceProvider();

            tripleDes.IV  = key8B;
            tripleDes.Key = key24B;
            Action do3des = () => EncryptDecryptAndDispose(tripleDes.CreateEncryptor(), tripleDes.CreateDecryptor(), data);

            do3des.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            tripleDes.Dispose();

            // RSA
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("RSA");
            RSAParameters param = new RSAParameters();

            param.Exponent = new byte[] { 0, 1, 0 };
            var store = new X509Store(StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly);
            X509Certificate cert = null;

            foreach (X509Certificate cer in store.Certificates)
            {
                if (cer != null)
                {
                    cert = cer;
                    break;
                }
            }
            param.Modulus = cert.GetPublicKey();

            var rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(param);


            Action doRsa = () =>
            {
                var encryptedData = rsa.Encrypt(key32B, true);
                //var decryptedData = rsa.Decrypt(encryptedData, true);
            };

            doRsa.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            rsa.Dispose();

            Console.Read();
        }
コード例 #38
0
ファイル: AES.cs プロジェクト: HasinduLanka/Vidusaviya.shasra
        public byte[] Encrypt(byte[] cipher)
        {
            ICryptoTransform encryptor = rijndael.CreateEncryptor();

            return(encryptor.TransformFinalBlock(cipher, 0, cipher.Length));
        }
コード例 #39
0
        public string Process()
        {
            var returnCode = "";

            using (var templateReader = new StringReader(Resources.template))
                using (var writer = new StreamWriter(output, Encoding.UTF8))
                {
                    for (var line = templateReader.ReadLine(); line != null; line = templateReader.ReadLine())
                    {
                        switch (line.Trim())
                        {
                        case "/*AES*/":
                            writer.WriteLine(Resources.aes);
                            break;

                        case "/*B64*/":
                            writer.WriteLine(Resources.b64);
                            break;

                        case "/*INIT*/":
                            writer.WriteLine(Resources.init);
                            break;

                        case "/*DATA*/":
                            using (var aes = new RijndaelManaged())
                                using (var rnd = new RNGCryptoServiceProvider())
                                    using (var ms = new MemoryStream())
                                    {
                                        aes.BlockSize = 128;
                                        aes.KeySize   = 256;
                                        aes.Padding   = PaddingMode.PKCS7;
                                        aes.Mode      = CipherMode.CBC;

                                        var key = new byte[aes.KeySize / 8];
                                        rnd.GetBytes(key);
                                        var iv = new byte[16];
                                        rnd.GetBytes(iv);

                                        using (var encryptor = aes.CreateEncryptor(key, iv))
                                            using (var cryptoStream = new CryptoStream(input, encryptor, CryptoStreamMode.Read))
                                            {
                                                cryptoStream.CopyTo(ms);
                                            }

                                        returnCode = string.Format("{0}", Uri.EscapeUriString(Convert.ToBase64String(key)));
                                        writer.WriteLine("var imageType='{0}';", imageType);
                                        writer.WriteLine("var iv='{0}';", Convert.ToBase64String(iv));
                                        writer.WriteLine("var data='{0}';", Convert.ToBase64String(ms.ToArray()));
                                    }
                            break;

                        case "<title/>":
                            writer.WriteLine("\t<title>{0}</title>", Utility.HtmlEncode(title));
                            break;

                        default:
                            writer.WriteLine(line);
                            break;
                        }
                    }
                }

            return(returnCode);
        }
コード例 #40
0
        /// <summary>
        ///     Encrypt <see cref="ScopedPdu" /> data BER encoded in a byte array.
        /// </summary>
        /// <param name="unencryptedData">BER encoded <see cref="ScopedPdu" /> byte array that needs to be encrypted</param>
        /// <param name="offset">Offset within the BER encoded byte array to start encryption operation from.</param>
        /// <param name="length">Length of data to encrypt</param>
        /// <param name="key">Encryption key</param>
        /// <param name="engineBoots">Authoritative engine boots value. Retrieved as part of SNMP v3 discovery process.</param>
        /// <param name="engineTime">Authoritative engine time value. Retrieved as part of SNMP v3 discovery process.</param>
        /// <param name="privacyParameters">
        ///     Byte array that will receive privacy parameters information that is the result of the
        ///     encryption procedure.
        /// </param>
        /// <param name="authDigest">Authentication digest reference. Not used by AES protocol and can be null</param>
        /// <returns>Byte array containing encrypted <see cref="ScopedPdu" /> BER encoded data</returns>
        public byte[] Encrypt(byte[] unencryptedData, int offset, int length, byte[] key, int engineBoots,
                              int engineTime, out byte[] privacyParameters, IAuthenticationDigest authDigest)
        {
            // check the key before doing anything else
            if (key == null || key.Length < _keyBytes)
            {
                throw new ArgumentOutOfRangeException("encryptionKey", "Invalid key length");
            }

            var iv   = new byte[16];
            var salt = NextSalt();

            privacyParameters = new byte[PrivacyParametersLength];
            var bootsBytes = BitConverter.GetBytes(engineBoots);

            iv[0] = bootsBytes[3];
            iv[1] = bootsBytes[2];
            iv[2] = bootsBytes[1];
            iv[3] = bootsBytes[0];
            var timeBytes = BitConverter.GetBytes(engineTime);

            iv[4] = timeBytes[3];
            iv[5] = timeBytes[2];
            iv[6] = timeBytes[1];
            iv[7] = timeBytes[0];

            // Set privacy parameters to the local 64 bit salt value
            var saltBytes = BitConverter.GetBytes(salt);

            privacyParameters[0] = saltBytes[7];
            privacyParameters[1] = saltBytes[6];
            privacyParameters[2] = saltBytes[5];
            privacyParameters[3] = saltBytes[4];
            privacyParameters[4] = saltBytes[3];
            privacyParameters[5] = saltBytes[2];
            privacyParameters[6] = saltBytes[1];
            privacyParameters[7] = saltBytes[0];

            // Copy salt value to the iv array
            Buffer.BlockCopy(privacyParameters, 0, iv, 8, 8);

            Rijndael rm = new RijndaelManaged();

            rm.KeySize      = _keyBytes * 8;
            rm.FeedbackSize = 128;
            rm.BlockSize    = 128;
            // we have to use Zeros padding otherwise we get encrypt buffer size exception
            rm.Padding = PaddingMode.Zeros;
            rm.Mode    = CipherMode.CFB;
            // make sure we have the right key length
            var pkey = new byte[MinimumKeyLength];

            Buffer.BlockCopy(key, 0, pkey, 0, MinimumKeyLength);
            rm.Key = pkey;
            rm.IV  = iv;
            var cryptor       = rm.CreateEncryptor();
            var encryptedData = cryptor.TransformFinalBlock(unencryptedData, offset, length);

            // check if encrypted data is the same length as source data
            if (encryptedData.Length != unencryptedData.Length)
            {
                // cut out the padding
                var tmp = new byte[unencryptedData.Length];
                Buffer.BlockCopy(encryptedData, 0, tmp, 0, unencryptedData.Length);
                return(tmp);
            }
            return(encryptedData);
        }
コード例 #41
0
 public RsaRijndaelWebApi.Infrastructure.Cryptography.IRijndaelEncryptor CreateDataEncryptor(byte[] key, byte[] vector)
 {
     return(new RsaRijndaelWebApi.Infrastructure.Cryptography.Rijndael(_rijndaelManaged.CreateEncryptor(key, vector)));
 }
コード例 #42
0
        /// <summary>
        /// This encrypts a plain text password, and return it, along with aysm encrypted key and iv
        /// </summary>
        /// <param name="storeName">The name of the aysm key store</param>
        /// <param name="password">The plain text password</param>
        /// <param name="key">The encrypted key</param>
        /// <param name="IV">The encrypted IV</param>
        /// <returns>The encrpted password</returns>
        public static string EncryptPassword(string storeName, string password, ref string key, ref string IV)
        {
            // retrieve the asym key from storage
            string asymkey = GetKey(storeName);
            string retval  = string.Empty;

            // Create values to store encrypted symmetric keys.
            byte[] encryptedSymmetricKey;
            byte[] encryptedSymmetricIV;

            // Create a new instance of the RSACryptoServiceProvider class.
            RSACryptoServiceProvider asymKeyProvider = new RSACryptoServiceProvider();

            // Set RSAKeyInfo to the public key values.
            asymKeyProvider.FromXmlString(asymkey);

            // Create a new instance of the RijndaelManaged class
            RijndaelManaged encryptionWrapper = new RijndaelManaged();

            // Get a new key and vector
            encryptionWrapper.KeySize = 256;
            encryptionWrapper.GenerateIV();
            encryptionWrapper.GenerateKey();

            // create an encrypter
            ICryptoTransform encryptionTransformer = encryptionWrapper.CreateEncryptor();

            // Create a  streams to hold the encrypted data
            MemoryStream targetMemoryStream = null;
            CryptoStream encryptionStream   = null;
            StreamWriter sourceWriterStream = null;

            try
            {
                targetMemoryStream = new MemoryStream();

                // this will do the encrypting
                encryptionStream = new CryptoStream(targetMemoryStream, encryptionTransformer, CryptoStreamMode.Write);

                // this will write the data to the encrypter
                sourceWriterStream = new StreamWriter(encryptionStream);

                // encrypt!
                sourceWriterStream.Write(password);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Whoops", ex.Message);
            }
            finally
            {
                if (sourceWriterStream != null)
                {
                    sourceWriterStream.Close();
                }
                if (encryptionStream != null)
                {
                    targetMemoryStream.Close();
                }
                if (targetMemoryStream != null)
                {
                    targetMemoryStream.Close();
                    retval = Convert.ToBase64String(targetMemoryStream.ToArray());
                }
                if (encryptionTransformer != null)
                {
                    encryptionTransformer.Dispose();
                }
            }

            // Encrypt the symmetric key and IV.
            encryptedSymmetricKey = asymKeyProvider.Encrypt(encryptionWrapper.Key, true);
            encryptedSymmetricIV  = asymKeyProvider.Encrypt(encryptionWrapper.IV, true);

            // set the return values, and we are done.
            key = Convert.ToBase64String(encryptedSymmetricKey);

            IV = Convert.ToBase64String(encryptedSymmetricIV);

            encryptionWrapper.Clear();
            return(Convert.ToBase64String(targetMemoryStream.ToArray()));
        }
コード例 #43
0
 public byte[] Encrypt(byte[] plainBytes, RijndaelManaged rijndaelManaged)
 {
     return(rijndaelManaged.CreateEncryptor()
            .TransformFinalBlock(plainBytes, 0, plainBytes.Length));
 }
コード例 #44
0
        protected void DecodeCert(McpeLogin message)
        {
            byte[] buffer = message.payload;

            if (message.payload.Length != buffer.Length)
            {
                Log.Debug($"Wrong lenght {message.payload.Length} != {message.payload.Length}");
                throw new Exception($"Wrong lenght {message.payload.Length} != {message.payload.Length}");
            }

            if (Log.IsDebugEnabled)
            {
                Log.Debug("Lenght: " + message.payload.Length + ", Message: " + buffer.EncodeBase64());
            }

            string certificateChain;
            string skinData;

            try
            {
                var destination = new MemoryStream(buffer);
                destination.Position = 0;
                NbtBinaryReader reader = new NbtBinaryReader(destination, false);

                var countCertData = reader.ReadInt32();
                certificateChain = Encoding.UTF8.GetString(reader.ReadBytes(countCertData));
                if (Log.IsDebugEnabled)
                {
                    Log.Debug($"Certificate Chain (Lenght={countCertData})\n{certificateChain}");
                }

                var countSkinData = reader.ReadInt32();
                skinData = Encoding.UTF8.GetString(reader.ReadBytes(countSkinData));
                if (Log.IsDebugEnabled)
                {
                    Log.Debug($"Skin data (Lenght={countSkinData})\n{skinData}");
                }
            }
            catch (Exception e)
            {
                Log.Error("Parsing login", e);
                return;
            }

            try
            {
                {
                    IDictionary <string, dynamic> headers = JWT.Headers(skinData);
                    dynamic payload = JObject.Parse(JWT.Payload(skinData));

                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug($"Skin JWT Header: {string.Join(";", headers)}");
                    }
                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug($"Skin JWT Payload:\n{payload.ToString()}");
                    }

                    try
                    {
                        _playerInfo.ClientId         = payload.ClientRandomId;
                        _playerInfo.CurrentInputMode = payload.CurrentInputMode;
                        _playerInfo.DefaultInputMode = payload.DefaultInputMode;
                        _playerInfo.DeviceModel      = payload.DeviceModel;
                        _playerInfo.DeviceOS         = payload.DeviceOS;
                        _playerInfo.GameVersion      = payload.GameVersion;
                        _playerInfo.GuiScale         = payload.GuiScale;
                        _playerInfo.LanguageCode     = payload.LanguageCode;
                        _playerInfo.ServerAddress    = payload.ServerAddress;
                        _playerInfo.UIProfile        = payload.UIProfile;

                        _playerInfo.Skin = new Skin()
                        {
                            CapeData         = Convert.FromBase64String((string)payload.CapeData),
                            SkinId           = payload.SkinId,
                            SkinData         = Convert.FromBase64String((string)payload.SkinData),
                            SkinGeometryName = payload.SkinGeometryName,
                            SkinGeometry     = Encoding.UTF8.GetString(Convert.FromBase64String((string)payload.SkinGeometry)),
                        };
                        Log.Warn($"Cape data lenght={_playerInfo.Skin.CapeData.Length}");
                    }
                    catch (Exception e)
                    {
                        Log.Error("Parsing skin data", e);
                    }
                }

                {
                    dynamic json = JObject.Parse(certificateChain);

                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug($"Certificate JSON:\n{json}");
                    }

                    JArray chain = json.chain;
                    //var chainArray = chain.ToArray();

                    string validationKey     = null;
                    string identityPublicKey = null;

                    foreach (JToken token in chain)
                    {
                        IDictionary <string, dynamic> headers = JWT.Headers(token.ToString());

                        if (Log.IsDebugEnabled)
                        {
                            Log.Debug("Raw chain element:\n" + token.ToString());
                            Log.Debug($"JWT Header: {string.Join(";", headers)}");

                            dynamic jsonPayload = JObject.Parse(JWT.Payload(token.ToString()));
                            Log.Debug($"JWT Payload:\n{jsonPayload}");
                        }

                        // Mojang root x5u cert (string): MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V

                        if (!headers.ContainsKey("x5u"))
                        {
                            continue;
                        }

                        string x5u = headers["x5u"];

                        if (identityPublicKey == null)
                        {
                            if (CertificateData.MojangRootKey.Equals(x5u, StringComparison.InvariantCultureIgnoreCase))
                            {
                                Log.Debug("Key is ok, and got Mojang root");
                            }
                            else if (chain.Count > 1)
                            {
                                Log.Debug("Got client cert (client root)");
                                continue;
                            }
                            else if (chain.Count == 1)
                            {
                                Log.Debug("Selfsigned chain");
                            }
                        }
                        else if (identityPublicKey.Equals(x5u))
                        {
                            Log.Debug("Derived Key is ok");
                        }

                        ECDiffieHellmanCngPublicKey newKey = (ECDiffieHellmanCngPublicKey)CryptoUtils.FromDerEncoded(x5u.DecodeBase64Url());
                        CertificateData             data   = JWT.Decode <CertificateData>(token.ToString(), newKey.Import());

                        // Validate

                        if (data != null)
                        {
                            identityPublicKey = data.IdentityPublicKey;

                            if (Log.IsDebugEnabled)
                            {
                                Log.Debug("Decoded token success");
                            }

                            if (CertificateData.MojangRootKey.Equals(x5u, StringComparison.InvariantCultureIgnoreCase))
                            {
                                Log.Debug("Got Mojang key. Is valid = " + data.CertificateAuthority);
                                validationKey = data.IdentityPublicKey;
                            }
                            else if (validationKey != null && validationKey.Equals(x5u, StringComparison.InvariantCultureIgnoreCase))
                            {
                                _playerInfo.CertificateData = data;
                            }
                            else
                            {
                                if (data.ExtraData == null)
                                {
                                    continue;
                                }

                                // Self signed, make sure they don't fake XUID
                                if (data.ExtraData.Xuid != null)
                                {
                                    Log.Warn("Received fake XUID from " + data.ExtraData.DisplayName);
                                    data.ExtraData.Xuid = null;
                                }

                                _playerInfo.CertificateData = data;
                            }
                        }
                        else
                        {
                            Log.Error("Not a valid Identity Public Key for decoding");
                        }
                    }

                    //TODO: Implement disconnect here

                    {
                        _playerInfo.Username = _playerInfo.CertificateData.ExtraData.DisplayName;
                        _session.Username    = _playerInfo.Username;
                        string identity = _playerInfo.CertificateData.ExtraData.Identity;

                        if (Log.IsDebugEnabled)
                        {
                            Log.Debug($"Connecting user {_playerInfo.Username} with identity={identity}");
                        }
                        _playerInfo.ClientUuid = new UUID(identity);

                        _session.CryptoContext = new CryptoContext
                        {
                            UseEncryption = Config.GetProperty("UseEncryptionForAll", false) || (Config.GetProperty("UseEncryption", true) && !string.IsNullOrWhiteSpace(_playerInfo.CertificateData.ExtraData.Xuid)),
                        };

                        if (_session.CryptoContext.UseEncryption)
                        {
                            ECDiffieHellmanPublicKey publicKey = CryptoUtils.FromDerEncoded(_playerInfo.CertificateData.IdentityPublicKey.DecodeBase64Url());
                            if (Log.IsDebugEnabled)
                            {
                                Log.Debug($"Cert:\n{publicKey.ToXmlString()}");
                            }

                            // Create shared shared secret
                            ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(384);
                            ecKey.HashAlgorithm         = CngAlgorithm.Sha256;
                            ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
                            ecKey.SecretPrepend         = Encoding.UTF8.GetBytes("RANDOM SECRET");                     // Server token
                            byte[] secret = ecKey.DeriveKeyMaterial(publicKey);

                            if (Log.IsDebugEnabled)
                            {
                                Log.Debug($"SECRET KEY (b64):\n{secret.EncodeBase64()}");
                            }

                            {
                                RijndaelManaged rijAlg = new RijndaelManaged
                                {
                                    BlockSize    = 128,
                                    Padding      = PaddingMode.None,
                                    Mode         = CipherMode.CFB,
                                    FeedbackSize = 8,
                                    Key          = secret,
                                    IV           = secret.Take(16).ToArray(),
                                };

                                // Create a decrytor to perform the stream transform.
                                ICryptoTransform decryptor      = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
                                MemoryStream     inputStream    = new MemoryStream();
                                CryptoStream     cryptoStreamIn = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read);

                                ICryptoTransform encryptor       = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
                                MemoryStream     outputStream    = new MemoryStream();
                                CryptoStream     cryptoStreamOut = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write);

                                _session.CryptoContext.Algorithm       = rijAlg;
                                _session.CryptoContext.Decryptor       = decryptor;
                                _session.CryptoContext.Encryptor       = encryptor;
                                _session.CryptoContext.InputStream     = inputStream;
                                _session.CryptoContext.OutputStream    = outputStream;
                                _session.CryptoContext.CryptoStreamIn  = cryptoStreamIn;
                                _session.CryptoContext.CryptoStreamOut = cryptoStreamOut;

                                string b64Key        = ecKey.PublicKey.ToDerEncoded().EncodeBase64();
                                var    handshakeJson = new HandshakeData()
                                {
                                    salt = ecKey.SecretPrepend.EncodeBase64()
                                };

                                string val = JWT.Encode(handshakeJson, ecKey.Key, JwsAlgorithm.ES384, new Dictionary <string, object> {
                                    { "x5u", b64Key }
                                });

                                var response = McpeServerToClientHandshake.CreateObject();
                                response.NoBatch    = true;
                                response.ForceClear = true;
                                response.token      = val;

                                _session.SendPackage(response);

                                if (Log.IsDebugEnabled)
                                {
                                    Log.Warn($"Encryption enabled for {_session.Username}");
                                }
                            }
                        }
                    }
                }
                if (!_session.CryptoContext.UseEncryption)
                {
                    _session.MessageHandler.HandleMcpeClientToServerHandshake(null);
                }
            }
            catch (Exception e)
            {
                Log.Error("Decrypt", e);
            }
        }
コード例 #45
0
        // Token: 0x0600032A RID: 810 RVA: 0x00027FEC File Offset: 0x000261EC
        private static ICryptoTransform GetAesTransform(byte[] byte_0, byte[] byte_1, bool bool_0)
        {
            ICryptoTransform result;

            using (SymmetricAlgorithm symmetricAlgorithm = new RijndaelManaged())
            {
                result = (bool_0 ? symmetricAlgorithm.CreateDecryptor(byte_0, byte_1) : symmetricAlgorithm.CreateEncryptor(byte_0, byte_1));
            }
            return(result);
        }
コード例 #46
0
        public static async Task <byte[]> EncryptBytesAsync(
            byte[] value,
            SecureString password,
            SecureString salt,
            SecureString passwordIterations,
            SecureString initialVector,
            SecureString keySize,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                if (value == null || value.Length == 0)
                {
                    return(value);
                }

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

                try
                {
                    saltBytes          = Encoding.ASCII.GetBytes(salt.ToUnsecureString());
                    initialVectorBytes = Encoding.ASCII.GetBytes(initialVector.ToUnsecureString());

                    using (var rfcDeriveBytes = new Rfc2898DeriveBytes(password.ToUnsecureString(), saltBytes, Convert.ToInt32(passwordIterations.ToUnsecureString())))
                        using (var rijndaelManaged = new RijndaelManaged {
                            Mode = CipherMode.CBC
                        })
                        {
                            derivedBytes = rfcDeriveBytes.GetBytes(Convert.ToInt32(keySize.ToUnsecureString()) / 8);
                            using (var encryptor = rijndaelManaged.CreateEncryptor(derivedBytes, initialVectorBytes))
                                using (var memoryStream = new MemoryStream())
                                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                                    {
                                        await cryptoStream.WriteAsync(value, 0, value.Length, cancellationToken);

                                        cryptoStream.FlushFinalBlock();
                                        buffer = memoryStream.ToArray();
                                        memoryStream.Close();
                                        cryptoStream.Close();
                                        rijndaelManaged.Clear();
                                        return(Encoding.ASCII.GetBytes(Convert.ToBase64String(buffer)));
                                    }
                        }
                }
                finally
                {
                    if (buffer != null)
                    {
                        Array.Clear(buffer, 0, buffer.Length);
                    }
                    if (saltBytes != null)
                    {
                        Array.Clear(saltBytes, 0, saltBytes.Length);
                    }
                    if (initialVectorBytes != null)
                    {
                        Array.Clear(initialVectorBytes, 0, initialVectorBytes.Length);
                    }
                    if (derivedBytes != null)
                    {
                        Array.Clear(derivedBytes, 0, derivedBytes.Length);
                    }
                }
            }
            finally
            {
                SecureStringCleanup(password, salt, passwordIterations, initialVector, keySize);
            }
        }
コード例 #47
0
        internal ICryptoTransform GetServiceProvider(byte[] _Key, byte[] _IV)
        {
            ICryptoTransform _Transform = null;

            switch (_algorithm)
            {
            case EnumCryptoProvider.DES:
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                switch (_Action)
                {
                case EnumCryptoAction.Encrypt:
                    _Transform = des.CreateEncryptor(_Key, _IV);
                    break;

                case EnumCryptoAction.Desencrypt:
                    _Transform = des.CreateDecryptor(_Key, _IV);
                    break;
                }
                return(_Transform);

            case EnumCryptoProvider.TripleDES:
                TripleDESCryptoServiceProvider des3 = new TripleDESCryptoServiceProvider();
                switch (_Action)
                {
                case EnumCryptoAction.Encrypt:
                    _Transform = des3.CreateEncryptor(_Key, _IV);
                    break;

                case EnumCryptoAction.Desencrypt:
                    _Transform = des3.CreateDecryptor(_Key, _IV);
                    break;
                }
                return(_Transform);

            case EnumCryptoProvider.RC2:
                RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
                switch (_Action)
                {
                case EnumCryptoAction.Encrypt:
                    _Transform = rc2.CreateEncryptor(_Key, _IV);
                    break;

                case EnumCryptoAction.Desencrypt:
                    _Transform = rc2.CreateDecryptor(_Key, _IV);
                    break;
                }
                return(_Transform);

            case EnumCryptoProvider.Rijndael:
                RijndaelManaged rijndael = new RijndaelManaged();
                switch (_Action)
                {
                case EnumCryptoAction.Encrypt:
                    _Transform = rijndael.CreateEncryptor(_Key, _IV);
                    break;

                case EnumCryptoAction.Desencrypt:
                    _Transform = rijndael.CreateDecryptor(_Key, _IV);
                    break;
                }
                return(_Transform);

            default:
                throw new CryptographicException("Error al inicializar al proveedor de cifrado");
            }
        }
コード例 #48
0
ファイル: Encrypt.cs プロジェクト: miguelC/Sirona.Utilities
        ///''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        // SAMPLE: Symmetric key encryption and decryption using Rijndael algorithm.
        //
        // To run this sample, create a new Visual Basic.NET project using the Console
        // Application template and replace the contents of the Module1.vb file with
        // the code below.
        //
        // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
        // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
        // WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
        //
        // Copyright (C) 2002 Obviex(TM). All rights reserved.
        //



        // <summary>
        // This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and
        // decrypt data. As long as encryption and decryption routines use the same
        // parameters to generate the keys, the keys are guaranteed to be the same.
        // The class uses static functions with duplicate code to make it easier to
        // demonstrate encryption and decryption logic. In a real-life application,
        // this may not be the most efficient way of handling encryption, so - as
        // soon as you feel comfortable with it - you may want to redesign this class.
        // </summary>


        // <summary>
        // Encrypts specified plaintext using Rijndael symmetric key algorithm
        // and returns a base64-encoded result.
        // </summary>
        // <param name="plainText">
        // Plaintext value to be encrypted.
        // </param>
        // <param name="passPhrase">
        // Passphrase from which a pseudo-random password will be derived. The
        // derived password will be used to generate the encryption key.
        // Passphrase can be any string. In this example we assume that this
        // passphrase is an ASCII string.
        // </param>
        // <param name="saltValue">
        // Salt value used along with passphrase to generate password. Salt can
        // be any string. In this example we assume that salt is an ASCII string.
        // </param>
        // <param name="hashAlgorithm">
        // Hash algorithm used to generate password. Allowed values are: "MD5" and
        // "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        // </param>
        // <param name="passwordIterations">
        // Number of iterations used to generate password. One or two iterations
        // should be enough.
        // </param>
        // <param name="initVector">
        // Initialization vector (or IV). This value is required to encrypt the
        // first block of plaintext data. For RijndaelManaged class IV must be
        // exactly 16 ASCII characters long.
        // </param>
        // <param name="keySize">
        // Size of encryption key in bits. Allowed values are: 128, 192, and 256.
        // Longer keys are more secure than shorter keys.
        // </param>
        // <returns>
        // Encrypted value formatted as a base64-encoded string.
        // </returns>
        public static string AESEncrypt(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 = null;
            initVectorBytes = Encoding.ASCII.GetBytes(initVector);

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

            // Convert our plaintext into a byte array.
            // Let us assume that plaintext contains UTF8-encoded characters.
            byte[] plainTextBytes = null;
            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 = null;

            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 = null;
            keyBytes = password.GetBytes(keySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = null;

            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 = null;

            encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);

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

            memoryStream = new MemoryStream();

            // Define cryptographic stream (always use Write mode for encryption).
            CryptoStream cryptoStream = null;

            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 = null;
            cipherTextBytes = memoryStream.ToArray();

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

            // Convert encrypted data into a base64-encoded string.
            string cipherText = null;

            cipherText = Convert.ToBase64String(cipherTextBytes);

            // Return encrypted string.
            return(cipherText);
        }
コード例 #49
0
        /// <summary>
        /// 根据提供的枚举信息,获得需要使用的加密算法的接口
        /// </summary>
        /// <param name="algorithm">算法枚举</param>
        /// <returns></returns>
        internal ICryptoTransform GetEncryptoServiceProvider(EncryptionAlgorithm algorithm)
        {
            switch (algorithm)
            {
            case EncryptionAlgorithm.Des:
            {
                DES des = new DESCryptoServiceProvider();
                des.Mode = CipherMode.CBC;
                if (null != m_Key)
                {
                    des.Key = m_Key;
                }
                else
                {
                    m_Key = des.Key;
                }
                if (null != m_initVec)
                {
                    des.IV = m_initVec;
                }
                else
                {
                    m_initVec = des.IV;
                }
                return(des.CreateEncryptor());
            }


            case EncryptionAlgorithm.Rc2:
            {
                RC2 rc = new RC2CryptoServiceProvider();
                rc.Mode = CipherMode.CBC;
                if (null != m_Key)
                {
                    rc.Key = m_Key;
                }
                else
                {
                    m_Key = rc.Key;
                }
                if (null != m_initVec)
                {
                    rc.IV = m_initVec;
                }
                else
                {
                    m_initVec = rc.IV;
                }
                return(rc.CreateEncryptor());
            }

            case EncryptionAlgorithm.Rijndael:
            {
                Rijndael rijndael = new RijndaelManaged();
                rijndael.Mode = CipherMode.CBC;
                if (null != m_Key)
                {
                    rijndael.Key = m_Key;
                }
                else
                {
                    m_Key = rijndael.Key;
                }
                if (null != m_initVec)
                {
                    rijndael.IV = m_initVec;
                }
                else
                {
                    m_initVec = rijndael.IV;
                }
                return(rijndael.CreateEncryptor());
            }

            case EncryptionAlgorithm.TripleDes:
            {
                TripleDES edes = new TripleDESCryptoServiceProvider();
                edes.Mode = CipherMode.CBC;
                if (null != m_Key)
                {
                    edes.Key = m_Key;
                }
                else
                {
                    m_Key = edes.Key;
                }
                if (null != m_initVec)
                {
                    edes.IV = m_initVec;
                }
                else
                {
                    m_initVec = edes.IV;
                }
                return(edes.CreateEncryptor());
            }

            default:
                throw new CryptographicException("Algorithm ID '" + algorithm + "' not supported.");
            }
        }
コード例 #50
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 RijndaelEnhanced(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);
        }
コード例 #51
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                DBConnect  objDB      = new DBConnect();
                SqlCommand objCommand = new SqlCommand();
                objCommand.CommandType = CommandType.StoredProcedure;
                objCommand.CommandText = "TP_LoginAccount";
                objCommand.Parameters.AddWithValue("@email", txtLoginEmail.Text);
                objCommand.Parameters.AddWithValue("@password", txtLoginPassword.Text);
                DataSet ds = objDB.GetDataSetUsingCmdObj(objCommand);
                if (ds.Tables[0].Rows[0]["Email"].ToString() == txtLoginEmail.Text && ds.Tables[0].Rows[0]["Password"].ToString() == txtLoginPassword.Text)
                {
                    if (chkRememberMe.Checked)
                    {
                        Session.Add("Email", txtLoginEmail.Text);
                        Session.Add("Password", txtLoginPassword.Text);
                        Session.Add("VerificationToken", ds.Tables[0].Rows[0]["VerificationToken"].ToString());
                        string       email             = txtLoginEmail.Text;
                        string       plainTextPassword = txtLoginPassword.Text;
                        string       encryptedPassword;
                        string       verificationToken = Session["VerificationToken"].ToString();
                        UTF8Encoding encoder           = new UTF8Encoding(); // used to convert bytes to characters, and back
                        Byte[]       textBytes;                              // stores the plain text data as bytes

                        // Perform Encryption
                        //-------------------
                        // Convert a string to a byte array, which will be used in the encryption process.
                        textBytes = encoder.GetBytes(plainTextPassword);

                        // Create an instances of the encryption algorithm (Rinjdael AES) for the encryption to perform,
                        // a memory stream used to store the encrypted data temporarily, and
                        // a crypto stream that performs the encryption algorithm.

                        RijndaelManaged rmEncryption       = new RijndaelManaged();
                        MemoryStream    myMemoryStream     = new MemoryStream();
                        CryptoStream    myEncryptionStream = new CryptoStream(myMemoryStream, rmEncryption.CreateEncryptor(key, vector), CryptoStreamMode.Write);

                        // Use the crypto stream to perform the encryption on the plain text byte array.
                        myEncryptionStream.Write(textBytes, 0, textBytes.Length);
                        myEncryptionStream.FlushFinalBlock();

                        // Retrieve the encrypted data from the memory stream, and write it to a separate byte array.
                        myMemoryStream.Position = 0;
                        Byte[] encryptedBytes = new Byte[myMemoryStream.Length];
                        myMemoryStream.Read(encryptedBytes, 0, encryptedBytes.Length);

                        // Close all the streams.
                        myEncryptionStream.Close();
                        myMemoryStream.Close();

                        // Convert the bytes to a string and display it.
                        encryptedPassword = Convert.ToBase64String(encryptedBytes);

                        // Write encrypted password to a cookie
                        HttpCookie myCookie = new HttpCookie("Login");
                        myCookie.Values["Email"]    = txtLoginEmail.Text;
                        myCookie.Values["Password"] = encryptedPassword;
                        //myCookie.Values["Password"] = txtLoginPassword.txt;
                        myCookie.Values["VerificationToken"] = Session["VerificationToken"].ToString();
                        myCookie.Expires = DateTime.Now.AddDays(1d);
                        Response.Cookies.Add(myCookie);
                        Server.Transfer("Profile.aspx", false);
                    }
                    else
                    {
                        Session.Add("Email", txtLoginEmail.Text);
                        Session.Add("Password", txtLoginPassword.Text);
                        Session.Add("VerificationToken", ds.Tables[0].Rows[0]["VerificationToken"].ToString());
                        Server.Transfer("Profile.aspx", false);
                    }
                }
            }
            catch (IndexOutOfRangeException)
            {
                return;
            }
        }
コード例 #52
0
        /// <summary>
        /// Encrypt the given string using AES.  The string can be decrypted using
        /// Decrypt().  The password and salt parameters must match.
        /// </summary>
        /// <param name="plainText">The text to encrypt.</param>
        /// <param name="salt">A salt used to increase security of encryption.</param>
        /// <param name="password">A password used to generate a key for encryption.</param>
        public string Encrypt(string plainText, string salt, string password)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                throw new ArgumentNullException("plainText");
            }
            if (string.IsNullOrEmpty(salt))
            {
                throw new ArgumentNullException("salt");
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }

            byte[] _salt = Encoding.ASCII.GetBytes(salt);

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

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

                // Create a RijndaelManaged object
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

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

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    // prepend the IV
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            // Return the encrypted bytes from the memory stream.
            return(outStr);
        }
コード例 #53
0
        byte[] Encrypt(byte[] asm, int key0)
        {
            RijndaelManaged rijn = ObfuscationHelper.CreateRijndael();

            int dictionary = 1 << 23;

            Int32 posStateBits   = 2;
            Int32 litContextBits = 3; // for normal files
            // UInt32 litContextBits = 0; // for 32-bit data
            Int32 litPosBits = 0;
            // UInt32 litPosBits = 2; // for 32-bit data
            Int32  algorithm    = 2;
            Int32  numFastBytes = 128;
            string mf           = "bt4";

            SevenZip.CoderPropID[] propIDs =
            {
                SevenZip.CoderPropID.DictionarySize,
                SevenZip.CoderPropID.PosStateBits,
                SevenZip.CoderPropID.LitContextBits,
                SevenZip.CoderPropID.LitPosBits,
                SevenZip.CoderPropID.Algorithm,
                SevenZip.CoderPropID.NumFastBytes,
                SevenZip.CoderPropID.MatchFinder,
                SevenZip.CoderPropID.EndMarker
            };
            object[] properties =
            {
                (int)dictionary,
                (int)posStateBits,
                (int)litContextBits,
                (int)litPosBits,
                (int)algorithm,
                (int)numFastBytes,
                mf,
                false
            };

            MemoryStream final   = new MemoryStream();
            var          encoder = new SevenZip.Compression.LZMA.Encoder();

            encoder.SetCoderProperties(propIDs, properties);
            encoder.WriteCoderProperties(final);
            Int64 fileSize;

            fileSize = asm.Length;
            for (int i = 0; i < 8; i++)
            {
                final.WriteByte((Byte)(fileSize >> (8 * i)));
            }
            encoder.Code(new MemoryStream(asm), final, -1, -1, null);

            var dat = new MemoryStream();

            using (var x = new CryptoStream(dat, rijn.CreateEncryptor(), CryptoStreamMode.Write))
            {
                x.Write(BitConverter.GetBytes(asm.Length), 0, 4);
                x.Write(final.ToArray(), 0, (int)final.Length);
            }

            byte[] key = rijn.Key;
            for (int j = 0; j < key.Length; j += 4)
            {
                key[j + 0] ^= (byte)((key0 & 0x000000ff) + 51 >> 0);
                key[j + 1] ^= (byte)((key0 & 0x0000ff00) - 51 >> 8);
                key[j + 2] ^= (byte)((key0 & 0x00ff0000) + 51 >> 16);
                key[j + 3] ^= (byte)((key0 & 0xff000000) - 51 >> 24);
            }
            MemoryStream str = new MemoryStream();

            using (BinaryWriter wtr = new BinaryWriter(str))
            {
                byte[] b = dat.ToArray();
                wtr.Write(b.Length);
                wtr.Write(b);
                wtr.Write(rijn.IV.Length);
                wtr.Write(rijn.IV);
                wtr.Write(key.Length);
                wtr.Write(key);
            }
            return(str.ToArray());
        }
コード例 #54
0
 public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV)
 {
     return(_rm.CreateEncryptor(rgbKey, rgbIV));
 }
コード例 #55
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);
        }
コード例 #56
0
    public bool TransformFile(string sInFile, string sOutFile, [System.Runtime.InteropServices.OptionalAttribute, System.Runtime.InteropServices.DefaultParameterValueAttribute(true)]      // ERROR: Optional parameters aren't supported in C#
                              bool encrypt)
    {
        //make sure that all the initialisation has been completed:
        if (!bInitialised)
        {
            if (Finished != null)
            {
                Finished(ReturnType.Badly);
            }
            return(false);
        }
        if (!IO.File.Exists(sInFile))
        {
            if (Finished != null)
            {
                Finished(ReturnType.Badly);
            }
            return(false);
        }

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

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

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

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

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

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

                //this is the main decryption routine. it loops over the input data in blocks of 4KB,
                //and writes the decrypted data to disk
                do
                {
                    if (bCancel)
                    {
                        //if the cancel flag is set,
                        //then jump out
                        encStream.Clear();
                        encStream = null;
                        break;                         // TODO: might not be correct. Was : Exit Try
                    }
                    lBytesToWrite = encStream.Read(bBuffer, 0, 4096);
                    if (lBytesToWrite == 0)
                    {
                        break;                                         // TODO: might not be correct. Was : Exit Do
                    }
                    fsOut.Write(bBuffer, 0, lBytesToWrite);
                    lBytesRead += lBytesToWrite;
                    if (Progress != null)
                    {
                        Progress((int)(lBytesRead / lFileSize) * 100);
                    }
                }while (true);
                if (Progress != null)
                {
                    Progress(100);
                }
                retVal = ReturnType.Well;
            }
        }
        catch (Exception ex) {
            Console.WriteLine("*****************ERROR*****************");
            Console.WriteLine(ex.ToString());
            Console.WriteLine("****************/ERROR*****************");
        }
        finally {
            //close all I/O streams (encStream first)
            if ((encStream != null))
            {
                encStream.Close();
            }
            if ((fsOut != null))
            {
                fsOut.Close();
            }
            if ((fsIn != null))
            {
                fsIn.Close();
            }
        }
        //only delete the file if the password was bad, and
        //therefore its only an empty file
        if (retVal == ReturnType.IncorrectPassword)
        {
            IO.File.Delete(sOutFile);
        }
        //raise the Finished event, and then reset bCancel
        if (Finished != null)
        {
            Finished(retVal);
        }
        bCancel = false;
    }
コード例 #57
0
 private byte[] Encrypt(byte[] encData, RijndaelManaged rijndaelManaged)
 {
     return(rijndaelManaged.CreateEncryptor().TransformFinalBlock(encData, 0, encData.Length));
 }
コード例 #58
0
        private void UploadBtn_Click(object sender, RoutedEventArgs e)
        {
            foreach (FileInfo fileinfo in fil)
            {
                //string scanResult = scanFile(fileinfo.FullName);
                string scanResult = "Clean";
                if (scanResult.Equals("Clean"))
                {
                    string fileext  = fileinfo.Extension;
                    string filename = fileinfo.Name.Substring(0, fileinfo.Name.Length - fileext.Length);
                    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                    {
                        string serverpub = ms.getPubkey();
                        rsa.FromXmlString(serverpub);
                        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                        {
                            byte[] key = new byte[32];
                            byte[] IV  = new byte[16];
                            rng.GetBytes(key);
                            rng.GetBytes(IV);
                            using (RijndaelManaged aes = new RijndaelManaged())
                            {
                                aes.Mode = CipherMode.CBC;
                                aes.IV   = IV;
                                aes.Key  = key;
                                using (FileStream fsInput = new FileStream(fileinfo.FullName, FileMode.Open, FileAccess.Read))
                                {
                                    using (FileStream fsEncrypted = new FileStream(encryptpath + filename + ".ee", FileMode.Create, FileAccess.Write))
                                    {
                                        ICryptoTransform encryptor = aes.CreateEncryptor();
                                        using (CryptoStream cryptostream = new CryptoStream(fsEncrypted, encryptor, CryptoStreamMode.Write))
                                        {
                                            int    bytesread;
                                            byte[] buffer = new byte[16384];
                                            while (true)
                                            {
                                                bytesread = fsInput.Read(buffer, 0, 16384);
                                                if (bytesread == 0)
                                                {
                                                    break;
                                                }
                                                cryptostream.Write(buffer, 0, bytesread);
                                            }
                                            cryptostream.Close();
                                            byte[] data = getFileData(encryptpath + filename + ".ee");

                                            bool result = ms.uploadFiles(fileinfo.Length, grouplist.SelectedItem as string, user, filename, fileext, Convert.ToBase64String(rsa.Encrypt(aes.Key, false)), Convert.ToBase64String(aes.IV), data);
                                            if (!result)
                                            {
                                                MessageBox.Show(filename + " already exists!", "Error");
                                            }
                                            File.Delete(encryptpath + filename + ".ee");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else if (scanResult.Equals("Error!"))
                {
                    System.Windows.Forms.MessageBox.Show("An error has occurred");
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show(scanResult);
                }
            }
            this.Close();
        }
コード例 #59
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);
        }
コード例 #60
-1
ファイル: Encrypt.cs プロジェクト: ivladyka/OurTravels
    public static string EncryptRijndael(string original)
    {
        byte[] encrypted;

        byte[] toEncrypt;

        UTF8Encoding utf8Converter = new UTF8Encoding();

        toEncrypt = utf8Converter.GetBytes(original);

        RijndaelManaged myRijndael = new RijndaelManaged();

        MemoryStream ms = new MemoryStream();

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

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

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

        cs.FlushFinalBlock();

        encrypted = ms.ToArray();

        string encryptedString = Convert.ToBase64String(encrypted);

        return encryptedString;
    }