Exemplo n.º 1
0
 public static RawTag GetRawTag(string file)
 {
     using (TlvReader reader = new TlvReader(new FileStream(Path.Combine(TestSetup.LocalPath, file), FileMode.Open)))
     {
         return(reader.ReadTag());
     }
 }
Exemplo n.º 2
0
 public void TestReadTagShort()
 {
     using (TlvReader reader = new TlvReader(new MemoryStream(new byte[] { 0x21, 0x4, 0x0, 0x1, 0x2, 0x3 })))
     {
         TlvTag tag = reader.ReadTag();
         Assert.AreEqual(new RawTag(0x1, false, true, new byte[] { 0x0, 0x1, 0x2, 0x3 }), tag, "Reader should output correct tag");
     }
 }
Exemplo n.º 3
0
        private static ExtendResponsePayload GetExtendResponsePayload(string path)
        {
            byte[] bytes = File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, path));

            using (TlvReader reader = new TlvReader(new MemoryStream(bytes)))
            {
                ExtendResponsePdu pdu = new ExtendResponsePdu(reader.ReadTag());
                return(pdu.Payloads[0] as ExtendResponsePayload);
            }
        }
Exemplo n.º 4
0
        public void PduTest()
        {
            byte[] bytes = File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637));

            using (TlvReader tlvReader = new TlvReader(new MemoryStream(bytes)))
            {
                AggregationResponsePdu pdu = new AggregationResponsePdu(tlvReader.ReadTag());
                Assert.IsNotNull(pdu.Header, "Unexpected PDU header");
                Assert.AreEqual(3, pdu.GetChildren().Length, "Unexpected childen count.");
            }
        }
Exemplo n.º 5
0
 public void TestReadDataWithInvalidLength()
 {
     using (TlvReader reader = new TlvReader(new MemoryStream(new byte[] { 0x21, 0x2 })))
     {
         TlvException ex = Assert.Throws <TlvException>(delegate
         {
             reader.ReadTag();
         });
         Assert.That(ex.Message, Does.StartWith("Could not read TLV data with expected length"));
     }
 }
 /// <summary>
 /// Get all child tags from byte array
 /// </summary>
 /// <param name="bytes">byte array containing tags</param>
 /// <returns></returns>
 private static IEnumerable <RawTag> GetChildren(byte[] bytes)
 {
     using (TlvReader tlvReader = new TlvReader(new MemoryStream(bytes)))
     {
         while (tlvReader.BaseStream.Position < tlvReader.BaseStream.Length)
         {
             RawTag raw = tlvReader.ReadTag();
             yield return(raw);
         }
     }
 }
Exemplo n.º 7
0
        public void TestReadTooShortTag()
        {
            using (TlvReader reader = new TlvReader(new MemoryStream(new byte[] { 0x21 })))
            {
                TlvException ex = Assert.Throws <TlvException>(delegate
                {
                    reader.ReadTag();
                });

                Assert.That(ex.Message, Does.StartWith("Premature end of input data"));
            }
        }
Exemplo n.º 8
0
        public void PduMacValidationTest()
        {
            byte[] bytes = File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregatorConfigResponsePdu));

            ImprintTag mac;

            using (TlvReader tlvReader = new TlvReader(new MemoryStream(bytes)))
            {
                mac = new AggregationResponsePdu(tlvReader.ReadTag()).Mac;
            }

            Assert.IsTrue(Pdu.ValidateMac(bytes, mac, Util.EncodeNullTerminatedUtf8String(TestConstants.ServicePass)), "MAC should be valid");
        }
Exemplo n.º 9
0
 public void TestReadTagLongWithShortType()
 {
     byte[] data = new byte[260];
     data[0] = 0xe0;
     data[1] = 0x1;
     data[2] = 0x1;
     data[3] = 0x0;
     Array.Copy(new byte[256], 0, data, 4, 256);
     using (TlvReader reader = new TlvReader(new MemoryStream(data)))
     {
         Assert.AreEqual(new RawTag(0x1, true, true, new byte[256]), reader.ReadTag(), "Reader should output correct byte array");
     }
 }
Exemplo n.º 10
0
        public void PduMacValidationWith0x0IntStaticInvalidTest()
        {
            byte[] bytes = File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregatorConfigResponsePdu_0x0_Int));

            AggregationResponsePdu pdu;

            using (TlvReader tlvReader = new TlvReader(new MemoryStream(bytes)))
            {
                pdu = new AggregationResponsePdu(tlvReader.ReadTag());
            }

            // 0x0 value representing an integer is converted to an empty TLV, thus MAC check will fail.
            byte[] pduBytes = pdu.Encode();
            Assert.IsFalse(Pdu.ValidateMac(pduBytes, pdu.Mac, Util.EncodeNullTerminatedUtf8String(TestConstants.ServicePass)), "MAC should be invalid");
        }
Exemplo n.º 11
0
        /// <summary>
        ///     Create KSI signature instance from stream.
        /// </summary>
        /// <param name="stream">signature data stream</param>
        /// <param name="hash">Signed hash</param>
        /// <returns>KSI signature</returns>
        public IKsiSignature Create(Stream stream, DataHash hash = null)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            using (TlvReader reader = new TlvReader(stream))
            {
                try
                {
                    Logger.Debug("Creating KSI signature from stream.");
                    KsiSignature signature = CreateAndVerify(reader.ReadTag(), null);
                    Logger.Debug("Creating KSI signature from stream successful.");

                    return(signature);
                }
                catch (TlvException e)
                {
                    Logger.Warn("Creating KSI signature from stream failed: {0}", e);
                    throw;
                }
            }
        }
        /// <summary>
        /// Parse KSI service response.
        /// </summary>
        /// <param name="data">Response byte array</param>
        /// <param name="requestId">Request ID</param>
        /// <returns></returns>
        public PduPayload Parse(byte[] data, ulong?requestId = null)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            RawTag    rawTag    = null;
            Pdu       pdu       = null;
            LegacyPdu legacyPdu = null;

            try
            {
                using (TlvReader reader = new TlvReader(new MemoryStream(data)))
                {
                    rawTag = new RawTag(reader.ReadTag());
                }

                if (rawTag.Type == GetPduTagType(false))
                {
                    if (_pduVersion == PduVersion.v1)
                    {
                        throw new KsiServiceUnexpectedResponseFormatException("Received PDU v2 response to PDU v1 request. Configure the SDK to use PDU v2 format.");
                    }

                    pdu = GetPdu(rawTag);
                }
                else if (rawTag.Type == GetPduTagType(true))
                {
                    if (_pduVersion == PduVersion.v2)
                    {
                        if (!IsLegacyRequestSupported())
                        {
                            throw new KsiServiceUnexpectedResponseFormatException("Received PDU v1 response to PDU v2 request.");
                        }

                        throw new KsiServiceUnexpectedResponseFormatException("Received PDU v1 response to PDU v2 request. Configure the SDK to use PDU v1 format.");
                    }

                    legacyPdu = GetLegacyPdu(rawTag);
                }
                else
                {
                    throw new KsiServiceException("Unknown response PDU tag type: " + rawTag.Type.ToString("X"));
                }

                if (legacyPdu != null)
                {
                    return(GetLegacyResponsePayload(legacyPdu, requestId));
                }
                else
                {
                    CheckAggregatorConfigChange(pdu);
                    CheckExtenderConfigChange(pdu);

                    return(GetResponsePayload(data, pdu, requestId));
                }
            }
            catch (TlvException e)
            {
                KsiException ksiException = new KsiServiceException("Could not parse response message: " + Base16.Encode(data), e);
                if (requestId.HasValue)
                {
                    Logger.Warn("Request failed (request id: {0}): {1}", requestId, ksiException);
                }
                else
                {
                    Logger.Warn("Request failed: {0}", ksiException);
                }
                throw ksiException;
            }
            catch (KsiException e)
            {
                if (requestId.HasValue)
                {
                    Logger.Warn("Request failed (request id: {0}){1}{2}{1}PDU:{1}{3}", requestId, Environment.NewLine, e, legacyPdu ?? pdu ?? (ITlvTag)rawTag);
                }
                else
                {
                    Logger.Warn("Request failed.{0}{1}{0}PDU:{0}{2}", Environment.NewLine, e, legacyPdu ?? pdu ?? (ITlvTag)rawTag);
                }

                throw;
            }
        }
Exemplo n.º 13
0
 public void TestReadTagShortWithLongType()
 {
     using (TlvReader reader = new TlvReader(new MemoryStream(new byte[] { 0xa0, 0x33, 0x0, 0x4, 0x0, 0x1, 0x2, 0x3 })))
     {
         Assert.AreEqual(new RawTag(0x33, false, true, new byte[] { 0x0, 0x1, 0x2, 0x3 }), reader.ReadTag(), "Reader should output correct byte array");
     }
 }
        /// <summary>
        /// Finds all asyncResults matching response payloads in given PDU and marks them as completed.
        /// </summary>
        /// <param name="pduBytes">PDU bytes</param>
        /// <returns></returns>
        private bool ProcessPdu(byte[] pduBytes)
        {
            bool isPayloadFound = false;

            using (TlvReader reader = new TlvReader(new MemoryStream(pduBytes)))
            {
                // iterate over all payloads in PDU
                foreach (KsiServiceResponsePayloadInfo payloadInfo in GetResponsePayloadInfos(reader.ReadTag()))
                {
                    isPayloadFound = true;
                    bool asyncResultFound = false;

                    foreach (TcpKsiServiceAsyncResult asyncResult in GetAsyncResults(payloadInfo))
                    {
                        asyncResultFound = true;

                        if (!asyncResult.IsCompleted)
                        {
                            asyncResult.ResultStream = new MemoryStream(pduBytes);
                            Logger.Debug("Response payload received. Request type: {0}; Response payload type: {1}; (request id: {2}).", asyncResult.ServiceRequestType,
                                         payloadInfo.ResponsePayloadType, asyncResult.RequestId);
                            asyncResult.SetComplete();
                        }
                        else
                        {
                            Logger.Debug("AsyncResult already marked as Completed. Request type: {0}; Response payload type: {1}; (request id: {2}).",
                                         asyncResult.ServiceRequestType, payloadInfo.ResponsePayloadType, asyncResult.RequestId);
                        }

                        _asyncResults.Remove(asyncResult);
                    }

                    if (!asyncResultFound)
                    {
                        Logger.Warn("No request data found corresponding to the respose payload. Response info: {0}; Response TLV: {1}", payloadInfo, Base16.Encode(pduBytes));
                    }
                }
            }

            return(isPayloadFound);
        }