new public CBORObject EncodeToCBORObject() { CBORObject cborBodyAttributes = null; byte[] rgbBody = null; if (m_msgToSign != null) { if (m_msgToSign.GetType() == typeof(EnvelopedMessage)) { EnvelopedMessage msg = (EnvelopedMessage)m_msgToSign; msg.Encrypt(); CBORObject obj = msg.EncodeToCBORObject(); if (obj[1].Type != CBORType.ByteString) { throw new Exception("Internal error"); } if (obj[3].Type != CBORType.ByteString) { throw new Exception("Internal error"); } rgbBody = obj[3].GetByteString(); cborBodyAttributes = obj[1]; } } else if (m_signerToSign != null) { CBORObject obj = m_signerToSign.EncodeToCBORObject(); } return(base.EncodeToCBORObject(cborBodyAttributes.GetByteString(), rgbBody)); }
public void nullKey() { EnvelopedMessage msg = new EnvelopedMessage(); msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, true); msg.SetContent(strContent); msg.Encrypt(); }
public void noContent() { EnvelopedMessage msg = new EnvelopedMessage(); msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, true); Recipient r = new Recipient(key128, AlgorithmValues.Direct); msg.AddRecipient(r); msg.Encrypt(); }
public void noAlgorithm() { EnvelopedMessage msg = new EnvelopedMessage(); msg.SetContent(strContent); Recipient r = new Recipient(key128, AlgorithmValues.Direct); msg.AddRecipient(r); msg.Encrypt(); }
public void unsupportedAlgorithm() { EnvelopedMessage msg = new EnvelopedMessage(); msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.HMAC_SHA_256, true); msg.SetContent(strContent); Recipient r = new Recipient(key128, AlgorithmValues.Direct); msg.AddRecipient(r); msg.Encrypt(); }
public void unknownAlgorithm() { EnvelopedMessage msg = new EnvelopedMessage(); msg.AddAttribute(HeaderKeys.Algorithm, CBORObject.FromObject("Unknown"), true); msg.SetContent(strContent); Recipient r = new Recipient(key128, AlgorithmValues.Direct); msg.AddRecipient(r); msg.Encrypt(); }
public void incorrectIV() { EnvelopedMessage msg = new EnvelopedMessage(); msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, true); msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV128), false); msg.SetContent(strContent); Recipient r = new Recipient(key128, AlgorithmValues.Direct); msg.AddRecipient(r); msg.Encrypt(); }
public void encryptNoEmitContent() { EnvelopedMessage msg = new EnvelopedMessage(true, false); msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, true); msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), false); msg.SetContent(strContent); Recipient r = new Recipient(key128, AlgorithmValues.Direct); msg.AddRecipient(r); msg.Encrypt(); CBORObject cn = msg.EncodeToCBORObject(); Assert.IsTrue(cn[2].IsNull); }
public void Test_that_Reject_call_calls_Reject_method_of_underlying_consumer_with_correct_delivery_tag() { const ulong deliveryTag = 42; var consumerMock = new Mock <IMessageConsumer>(); var message = new EnvelopedMessage ( Enumerable.Empty <byte>(), consumerMock.Object, string.Empty, string.Empty, deliveryTag, string.Empty ); message.Reject(); consumerMock.Verify(x => x.Reject(deliveryTag), Times.Once); }
public void roundTrip() { EnvelopedMessage msg = new EnvelopedMessage(); msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, true); msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), false); msg.SetContent(strContent); Recipient r = new Recipient(key128, AlgorithmValues.Direct); msg.AddRecipient(r); msg.Encrypt(); byte[] rgbMsg = msg.EncodeToBytes(); msg = (EnvelopedMessage)Message.DecodeFromBytes(rgbMsg); r = msg.RecipientList[0]; r.SetKey(key128); msg.Decrypt(r); Assert.AreEqual <string>(msg.GetContentAsString(), strContent); }
public void nullKeyForDecrypt() { EnvelopedMessage msg = new EnvelopedMessage(true, true); // thrown.expect(CoseException.class); // thrown.expectMessage("No Enveloped Content Specified"); msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, true); msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), false); msg.SetContent(strContent); Recipient r = new Recipient(key128, AlgorithmValues.Direct); msg.AddRecipient(r); msg.Encrypt(); byte[] rgb = msg.EncodeToBytes(); msg = (EnvelopedMessage)Message.DecodeFromBytes(rgb); msg.Decrypt(null); }
public void roundTripDetached() { EnvelopedMessage msg = new EnvelopedMessage(true, false); msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, true); msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), false); msg.SetContent(strContent); Recipient r = new Recipient(key128, AlgorithmValues.Direct); msg.AddRecipient(r); msg.Encrypt(); byte[] content = msg.GetEncryptedContent(); byte[] rgb = msg.EncodeToBytes(); msg = (EnvelopedMessage)Message.DecodeFromBytes(rgb); msg.SetEncryptedContent(content); r = msg.RecipientList[0]; r.SetKey(key128); msg.Decrypt(r); }
public void Test_that_WithIncreasedRetryCount_creates_new_message_instance_with_incremented_RetryCount_value() { var consumerMock = new Mock <IMessageConsumer>(); var right = new EnvelopedMessage ( Enumerable.Empty <byte>(), consumerMock.Object, string.Empty, string.Empty, 42, string.Empty ); for (var i = 0; i < 10; i++) { var left = right.WithIncreasedRetryCount(); Assert.AreNotEqual(left, right); Assert.AreEqual(1, left.RetryCount - right.RetryCount); right = left; } }
public static Message DecodeFromBytes(byte[] messageData, Tags defaultTag = Tags.Unknown) { CBORObject messageObject = CBORObject.DecodeFromBytes(messageData); if (messageObject.Type != CBORType.Array) { throw new CoseException("Message is not a COSE security message."); } if (messageObject.IsTagged) { if (messageObject.GetTags().Count() != 1) { throw new CoseException("Malformed message - too many tags"); } if (defaultTag == Tags.Unknown) { defaultTag = (COSE.Tags)messageObject.OutermostTag.intValue(); } else if (defaultTag != (COSE.Tags)messageObject.OutermostTag.intValue()) { throw new CoseException("Passed in tag does not match actual tag"); } } switch (defaultTag) { case Tags.Unknown: throw new CoseException("Message was not tagged and no default tagging option given"); case Tags.Signed: SignMessage sig = new SignMessage(); sig.DecodeFromCBORObject(messageObject); return(sig); case Tags.Signed0: Sign0Message sig0 = new Sign0Message(); sig0.DecodeFromCBORObject(messageObject); return(sig0); case Tags.MAC: { MACMessage mac = new MACMessage(); mac.DecodeFromCBORObject(messageObject); return(mac); } case Tags.MAC0: MAC0Message mac0 = new MAC0Message(); mac0.DecodeFromCBORObject(messageObject); return(mac0); case Tags.Enveloped: // It is an encrytion message EnvelopedMessage enc = new EnvelopedMessage(); enc.DecodeFromCBORObject(messageObject); return(enc); case Tags.Encrypted: EncryptMessage enc0 = new EncryptMessage(); enc0.DecodeFromCBORObject(messageObject); return(enc0); default: throw new CoseException("Message is not recognized as a COSE security message."); } }
/// <summary> /// 发送请求 /// </summary> /// <param name="message">消息</param> /// <param name="methodName">方法名</param> /// <param name="correlationId">关联ID</param> public void SendRequest <T>(Envelope <T> message, string methodName, string correlationId) where T : class { if (message == null || message.Body == null) { throw new ArgumentNullException("message"); } var queueName = _disableQueuePrefix ? methodName : $"rpc.{methodName}"; var callbackQueueName = $"{queueName}.callback"; var body = Serializer.Serialize(message.Body); var messageTypeName = MessageTypeAttribute.GetTypeName(message.Body.GetType()); var routingKey = string.IsNullOrEmpty(ExchangeName) ? queueName : methodName; var envelopedMessage = new EnvelopedMessage(message.MessageId, messageTypeName, message.Timestamp, Serializer.GetString(body), routingKey, correlationId, callbackQueueName); var context = new MessageSendingTransportationContext(ExchangeName, new Dictionary <string, object> { { MessagePropertyConstants.MESSAGE_ID, string.IsNullOrEmpty(message.MessageId) ? Guid.NewGuid().ToString() : message.MessageId }, { MessagePropertyConstants.MESSAGE_TYPE, messageTypeName }, { MessagePropertyConstants.TIMESTAMP, message.Timestamp }, { MessagePropertyConstants.CONTENT_TYPE, Serializer.ContentType }, { MessagePropertyConstants.PAYLOAD, Serializer.GetString(body) }, { MessagePropertyConstants.ROUTING_KEY, routingKey }, { MessagePropertyConstants.REPLY_TO, callbackQueueName }, { MessagePropertyConstants.CORRELATION_ID, correlationId } }); TriggerOnMessageSent(new MessageSentEventArgs(this.GetSenderType(), context)); try { if (!IsRunning()) { throw new ObjectDisposedException(nameof(RpcClient)); } IncreaseRetryingMessageCount(); RetryPolicy.Retry(() => { using (var channel = _conn.CreateChannel()) { var properties = channel.CreateBasicProperties(); properties.Persistent = true; properties.DeliveryMode = 2; properties.ContentType = Serializer.ContentType; properties.MessageId = message.MessageId; properties.Type = messageTypeName; properties.Timestamp = new AmqpTimestamp(DateTime2UnixTime.ToUnixTime(message.Timestamp)); properties.ReplyTo = callbackQueueName; properties.CorrelationId = correlationId; if (_confirmEnabled) { channel.ConfirmSelect(); } channel.BasicPublish(exchange: ExchangeName, routingKey: routingKey, mandatory: true, basicProperties: properties, body: body); if (_confirmEnabled && !channel.WaitForConfirms()) { throw new Exception("Wait for confirm after sending message failed"); } } }, cancelOnFailed: (retryCount, retryException) => { return(false); }, retryCondition: ex => IOHelper.IsIOError(ex) || RabbitMQExceptionHelper.IsChannelError(ex), retryTimeInterval: 1000, maxRetryCount: _maxRetryCount); TriggerOnMessageSendingSucceeded(new MessageSendingSucceededEventArgs(this.GetSenderType(), context)); } catch (Exception ex) { var realEx = ex is TargetInvocationException ? ex.InnerException : ex; context.LastException = realEx; TriggerOnMessageSendingFailed(new MessageSendingFailedEventArgs(this.GetSenderType(), context)); throw new MessageSendFailedException(envelopedMessage, ExchangeName, realEx); } finally { DecreaseRetryingMessageCount(); } }
/// <summary> /// 发送消息 /// </summary> /// <param name="message">消息</param> public void SendMessage <T>(Envelope <T> message) where T : class { if (message == null || message.Body == null) { throw new ArgumentNullException("message"); } var body = Serializer.Serialize(message.Body); var messageTypeName = MessageTypeAttribute.GetTypeName(message.Body.GetType()); var routingKey = string.Empty; if (_publishToExchange) { uint routingKeyHashCode = 0; if (!uint.TryParse(message.RoutingKey, out routingKeyHashCode)) { routingKeyHashCode = (uint)message.RoutingKey.GetHashCode(); } routingKey = (routingKeyHashCode % _publishToExchangeQueueCount).ToString(); } else { routingKey = message.RoutingKey == null ? string.Empty : message.RoutingKey; } var envelopedMessage = new EnvelopedMessage(message.MessageId, messageTypeName, message.Timestamp, Serializer.GetString(body), routingKey, string.Empty, string.Empty); var context = new MessageSendingTransportationContext(ExchangeName, new Dictionary <string, object> { { MessagePropertyConstants.MESSAGE_ID, string.IsNullOrEmpty(message.MessageId) ? Guid.NewGuid().ToString() : message.MessageId }, { MessagePropertyConstants.MESSAGE_TYPE, messageTypeName }, { MessagePropertyConstants.TIMESTAMP, message.Timestamp }, { MessagePropertyConstants.CONTENT_TYPE, Serializer.ContentType }, { MessagePropertyConstants.PAYLOAD, Serializer.GetString(body) }, { MessagePropertyConstants.ROUTING_KEY, routingKey } }); try { TriggerOnMessageSent(new MessageSentEventArgs(this.GetSenderType(), context)); if (!IsRunning()) { throw new ObjectDisposedException(nameof(PubsubSender)); } IncreaseRetryingMessageCount(); RetryPolicy.Retry(() => { using (var channel = _conn.CreateChannel()) { var properties = channel.CreateBasicProperties(); properties.Persistent = true; properties.DeliveryMode = 2; properties.ContentType = Serializer.ContentType; properties.MessageId = message.MessageId; properties.Type = messageTypeName; properties.Timestamp = new AmqpTimestamp(DateTime2UnixTime.ToUnixTime(message.Timestamp)); if (_confirmEnabled) { channel.ConfirmSelect(); } channel.BasicPublish(exchange: ExchangeName, routingKey: routingKey, mandatory: _atLeastMatchOneQueue, basicProperties: properties, body: body); if (_confirmEnabled && !channel.WaitForConfirms()) { throw new Exception("Wait for confirm after sending message failed"); } } }, cancelOnFailed: (retryCount, retryException) => { return(false); }, retryCondition: ex => IOHelper.IsIOError(ex) || RabbitMQExceptionHelper.IsChannelError(ex), retryTimeInterval: 1000, maxRetryCount: _maxRetryCount); TriggerOnMessageSendingSucceeded(new MessageSendingSucceededEventArgs(this.GetSenderType(), context)); } catch (Exception ex) { var realEx = ex is TargetInvocationException ? ex.InnerException : ex; context.LastException = realEx; TriggerOnMessageSendingFailed(new MessageSendingFailedEventArgs(this.GetSenderType(), context)); throw new MessageSendFailedException(envelopedMessage, ExchangeName, realEx); } finally { DecreaseRetryingMessageCount(); } }
/// <summary> /// 重发到队列 /// </summary> /// <param name="queueName">队列名</param> /// <param name="messageId">消息ID</param> /// <param name="messageTypeName">消息类型名</param> /// <param name="messageTimestamp">消息时间戳</param> /// <param name="messageBody">消息体</param> /// <param name="correlationId">关联ID</param> /// <param name="replyTo">响应队列名</param> public void RedeliverToQueue(string queueName, string messageId, string messageTypeName, DateTime messageTimestamp, string messageBody, string correlationId = "", string replyTo = "") { if (string.IsNullOrEmpty(queueName)) { throw new ArgumentNullException("queueName", "must not empty"); } if (string.IsNullOrEmpty(messageId)) { throw new ArgumentNullException("messageId", "must not empty"); } if (string.IsNullOrEmpty(messageTypeName)) { throw new ArgumentNullException("messageTypeName", "must not empty"); } if (messageTimestamp == DateTime.MinValue) { throw new ArgumentNullException("messageTimestamp", "must not empty"); } if (string.IsNullOrEmpty(messageBody)) { throw new ArgumentNullException("messageBody", "must not empty"); } var body = Serializer.GetBytes(messageBody); var routingKey = queueName; var envelopedMessage = new EnvelopedMessage(messageId, messageTypeName, messageTimestamp, messageBody, routingKey, correlationId, replyTo); try { var context = new MessageSendingTransportationContext(string.Empty, new Dictionary <string, object> { { MessagePropertyConstants.MESSAGE_ID, string.IsNullOrEmpty(messageId) ? Guid.NewGuid().ToString() : messageId }, { MessagePropertyConstants.MESSAGE_TYPE, messageTypeName }, { MessagePropertyConstants.TIMESTAMP, messageTimestamp }, { MessagePropertyConstants.CONTENT_TYPE, Serializer.ContentType }, { MessagePropertyConstants.PAYLOAD, Serializer.GetString(body) }, { MessagePropertyConstants.ROUTING_KEY, routingKey }, { MessagePropertyConstants.REPLY_TO, replyTo }, { MessagePropertyConstants.CORRELATION_ID, correlationId } }); RetryPolicy.Retry(() => { using (var channel = _conn.CreateChannel()) { var properties = channel.CreateBasicProperties(); properties.Persistent = true; properties.DeliveryMode = 2; properties.ContentType = Serializer.ContentType; properties.MessageId = messageId; properties.Type = messageTypeName; properties.Timestamp = new AmqpTimestamp(DateTime2UnixTime.ToUnixTime(messageTimestamp)); if (!string.IsNullOrEmpty(correlationId) && !string.IsNullOrEmpty(replyTo)) { properties.CorrelationId = correlationId; properties.ReplyTo = replyTo; } channel.BasicPublish(exchange: string.Empty, routingKey: routingKey, mandatory: true, basicProperties: properties, body: body); channel.Close(); } }, cancelOnFailed: (retryCount, retryException) => { if (retryCount == 0) { _logger.Error($"Message [{messageTypeName}] \"{Serializer.GetString(body)}\" send to queue \"{queueName}\" failed.", retryException); } return(false); }, retryCondition: ex => IOHelper.IsIOError(ex) || RabbitMQExceptionHelper.IsChannelError(ex), maxRetryCount: 1, retryTimeInterval: 1000); if (_debugEnabled) { _logger.Info($"Message [{messageTypeName}] \"{Serializer.GetString(body)}\" send to queue \"{queueName}\" successful."); } } catch (Exception ex) { var realEx = ex is TargetInvocationException ? ex.InnerException : ex; _logger.Error($"Message [{ messageTypeName}] \"{Serializer.GetString(body)}\" send to queue \"{queueName}\" failed.", realEx); throw new MessageSendFailedException(envelopedMessage, string.Empty, realEx); } }
/// <summary> /// 重发到交换器 /// </summary> /// <param name="exchangeName">交换器名</param> /// <param name="messageId">消息ID</param> /// <param name="messageTypeName">消息类型名</param> /// <param name="messageTimestamp">消息时间戳</param> /// <param name="messageBody">消息体</param> /// <param name="routingKey">路由键</param> /// <param name="correlationId">关联ID</param> /// <param name="replyTo">响应队列名</param> public void RedeliverToExchange(string exchangeName, string messageId, string messageTypeName, DateTime messageTimestamp, string messageBody, string routingKey, string correlationId = "", string replyTo = "") { if (string.IsNullOrEmpty(messageId)) { throw new ArgumentNullException("messageId", "must not empty"); } if (string.IsNullOrEmpty(messageTypeName)) { throw new ArgumentNullException("messageTypeName", "must not empty"); } if (messageTimestamp == DateTime.MinValue) { throw new ArgumentNullException("messageTimestamp", "must not empty"); } if (string.IsNullOrEmpty(messageBody)) { throw new ArgumentNullException("messageBody", "must not empty"); } var body = Serializer.GetBytes(messageBody); var envelopedMessage = new EnvelopedMessage(messageId, messageTypeName, messageTimestamp, messageBody, routingKey, correlationId, replyTo); try { RetryPolicy.Retry(() => { using (var channel = _conn.CreateChannel()) { var properties = channel.CreateBasicProperties(); properties.Persistent = true; properties.DeliveryMode = 2; properties.ContentType = Serializer.ContentType; properties.MessageId = messageId; properties.Type = messageTypeName; properties.Timestamp = new AmqpTimestamp(DateTime2UnixTime.ToUnixTime(messageTimestamp)); if (!string.IsNullOrEmpty(correlationId) && !string.IsNullOrEmpty(replyTo)) { properties.CorrelationId = correlationId; properties.ReplyTo = replyTo; } channel.BasicPublish(exchange: exchangeName ?? string.Empty, routingKey: routingKey ?? string.Empty, mandatory: true, basicProperties: properties, body: body); channel.Close(); } }, cancelOnFailed: (retryCount, retryException) => { if (retryCount == 0) { _logger.Error($"Message [{messageTypeName}] \"{Serializer.GetString(body)}\" send to exchange \"{exchangeName}\", routing key={routingKey} failed.", retryException); } return(false); }, retryCondition: ex => IOHelper.IsIOError(ex) || RabbitMQExceptionHelper.IsChannelError(ex), maxRetryCount: 1, retryTimeInterval: 1000); _logger.Info($"Message [{messageTypeName}] \"{Serializer.GetString(body)}\" send to exchange \"{exchangeName}\", routing key={routingKey} successful."); } catch (Exception ex) { var realEx = ex is TargetInvocationException ? ex.InnerException : ex; _logger.Error($"Message [{ messageTypeName}] \"{Serializer.GetString(body)}\" send to exchange \"{exchangeName}\", routing key={routingKey} failed.", realEx); throw new MessageSendFailedException(envelopedMessage, exchangeName, realEx); } }