private byte[] GeneratePayload(Dictionary <string, string> values) { byte[] rawData = null; using (MemoryStream mem = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(mem)) { foreach (var entry in values) { string key = entry.Key.Trim(); string val = entry.Value.Trim(); if (!KeepEmptyFields && val == "") { continue; } WriteUTF(writer, key); WriteUTF(writer, val); } } rawData = mem.ToArray(); } if (privateKey == null || privateKey.Length == 0) { return(rawData); } byte[] signData = rawData; if (extraSignData != null) { signData = new byte[rawData.Length + extraSignData.Length]; rawData.CopyTo(signData, 0); extraSignData.CopyTo(signData, rawData.Length); } byte[] sig = CryptoHandler.SignDetached(signData, privateKey); string sigStr = Convert.ToBase64String(sig); using (MemoryStream mem = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(mem)) { WriteUTF(writer, SIG_KEY); WriteUTF(writer, sigStr); writer.Write(rawData); } return(mem.ToArray()); } }
private Dictionary <string, string> ParseInflatedPayload(byte[] payload) { Dictionary <string, string> res = new Dictionary <string, string>(); using (var mem = new MemoryStream(payload)) using (var reader = new BinaryReader(mem)) { while (reader.BaseStream.Length - reader.BaseStream.Position > 4) { long initPos = reader.BaseStream.Position; string key = ReadUTF(reader); string val = ReadUTF(reader); if (key == SIG_VALID_KEY) { continue; } if (initPos == 0 && key == SIG_KEY && publicKey != null && publicKey.Length != 0) { long prePos = reader.BaseStream.Position; byte[] msg = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position)); reader.BaseStream.Position = prePos; byte[] sig = Convert.FromBase64String(val); if (extraSignData != null) { int preLen = msg.Length; Array.Resize(ref msg, preLen + extraSignData.Length); extraSignData.CopyTo(msg, preLen); } res.Add(SIG_VALID_KEY, CryptoHandler.VerifyDetached(sig, msg, publicKey).ToString()); } res.Add(key, val); } if (reader.BaseStream.Position < reader.BaseStream.Length) { throw new NdefHandlerException("Leftover data after reading"); } } return(res); }