public static void WriteMessageStream(MemoryStream outStream, Message outMessage, string sessionKey, Aes aes, bool encrypt) { outMessage.ReplaceControlValue(Message.TimestampControlValueName, DateTime.Now.ToUniversalTime().ToString()); outMessage.ReplaceControlValue(Message.SessionKeyControlValueName, sessionKey); if (encrypt) { aes.GenerateIV(); StreamUtilities.WriteStringToMemoryStream(outStream, aes.IV.Length + "!"); outStream.Write(aes.IV, 0, aes.IV.Length); StreamUtilities.RunCryptoTransform(outMessage.Serialize(), aes.CreateEncryptor(), outStream, true); } else { outMessage.Serialize(outStream); } }
//private string timestampPrefix() //{ // return DateTime.Now.ToString("yyyyMMddHHmmssFFFFFFF"); //} private Message sendMessage(Message request, bool encryptMessage) { lock (request) { //TODO: learn how to use compile flags //request.ToFile(timestampPrefix() + "_request.xml"); //calibrate if (nextCalibrate == null || nextCalibrate < DateTime.Now) { request.ReplaceControlValue(Message.LibraryVersionControlValueName, InternalLibraryVersion.GetLibraryVersion().ToString()); nextCalibrate = DateTime.Now.Add(calibrateFrequency); } System.Net.WebClient webClient = new System.Net.WebClient(); if (accessKey != null) webClient.QueryString[Message.AccessKeyHeaderName] = accessKey; //set encryption is using... Aes aes = null; if (encryptionKey != null) { try { aes = StreamUtilities.GetAesCryptoTransform(encryptionKey, null); } catch (CryptographicException exception) { throw new Exceptions.CommunicationException("Encryption exception. Is the encryption key the right length?", exception); } } //message is all ready to go. MemoryStream outgoingStream = new MemoryStream(); Common.WriteMessageStream(outgoingStream, request, sessionKey, aes, encryptMessage); //TODO: fix these last-minute converstions to/from arrays byte[] responseBytes; try { responseBytes = webClient.UploadData(url, outgoingStream.ToArray()); } catch (System.Net.WebException exception) { throw new Exceptions.CommunicationException(exception.Message); } MemoryStream responseStream = StreamUtilities.ToMemoryStream(responseBytes); Message response = responseStream.ToMessage(aes); //update sessionKey if (response.controlValues.ContainsKey(Message.NewSessionKeyControlValueName)) sessionKey = response.controlValues[Message.NewSessionKeyControlValueName]; //response.ToFile(timestampPrefix() + "_response.xml"); return response; } }
public static Message CreatePing() { var result = new Message(); result.ReplaceControlValue(ControlActionControlValueName, PingActionControlValueName); return result; }