public EncryptedPacket Encrypt(byte[] data) { var sessionKey = _aes.GenerateRandomNumber(32); var packet = new EncryptedPacket(); packet.Iv = _aes.GenerateRandomNumber(16); packet.EncryptedData = _aes.Encrypt(data, sessionKey, packet.Iv); packet.EncryptedSessionKey = _rsa.Encrypt(sessionKey); using (var hmac = new HMACSHA256(sessionKey)) { packet.Hmac = hmac.ComputeHash(Combine(packet.EncryptedData, packet.Iv)); } packet.Signature = _digitalSignature.SignData(packet.Hmac); return(packet); }
public byte[] Decrypt(EncryptedPacket packet) { var sessionKey = _rsa.Decrypt(packet.EncryptedSessionKey); using (var hmac = new HMACSHA256(sessionKey)) { var hmacToCheck = hmac.ComputeHash(Combine(packet.EncryptedData, packet.Iv)); if (!Compare(packet.Hmac, hmacToCheck)) { throw new CryptographicException("HMAC does not match encrypted packet."); } } if (!_digitalSignature.Verify(packet.Hmac, packet.Signature)) { throw new CryptographicException("Digital signature cannot be verified."); } return(_aes.Decrypt(packet.EncryptedData, sessionKey, packet.Iv)); }