Example #1
0
        public byte[] DecryptData(EncryptedPacket encryptedPacket, RSAWithRSAParameterKey rsaParams)
        {
            // Decrypt AES Key with RSA
            var decryptedSessionKey = rsaParams.DecryptData(encryptedPacket.EncryptedSessionKey);

            // Integrity Check
            var hmacToCheck = HMac.ComputeHMACSha256(encryptedPacket.EncryptedData, decryptedSessionKey);

            if (!Compare(encryptedPacket.HMAC, hmacToCheck))
            {
                throw new CryptographicException("HMAC for decryption does not match encrypted package HMAC code received. This means the message has been tampered with.");
            }

            // Decrypt our data with AES using the decryptedSessionKey
            return(_aes.Decrypt(encryptedPacket.EncryptedData, decryptedSessionKey, encryptedPacket.IV));
        }
Example #2
0
        public EncryptedPacket EncryptData(byte[] original, RSAWithRSAParameterKey rsaParams)
        {
            // Generate our session key
            var sessionKey = _aes.GenerateRandomNumber(32);

            // Create the encrypted packet and generate the IV
            var encryptedPacket = new EncryptedPacket
            {
                IV = _aes.GenerateRandomNumber(16)
            };

            // Encrypt our data with AES
            encryptedPacket.EncryptedData = _aes.Encrypt(original, sessionKey, encryptedPacket.IV);

            // Encrypt the session key with RSA
            encryptedPacket.EncryptedSessionKey = rsaParams.EncryptData(sessionKey);

            // Calculate a HMAC
            encryptedPacket.HMAC = HMac.ComputeHMACSha256(encryptedPacket.EncryptedData, sessionKey);

            return(encryptedPacket);
        }