Example #1
0
        //*************************************************************************************
        //test :if poco have attribute setting and have any exception when serializeObject? no
        public static void Main4()
        {
            string result = "";
            string err = null;
            EskmsPOCO poco = new EskmsPOCO()
            {
                Input_KeyLabel = "2ICH3F000032A",
                Input_KeyVersion = "00",
                Input_UID = "04873ABA8D2C80",
                Input_Enc_RanB = "4EF61041ABE8B0EF8B32A627B19D83AA"
            };
            poco.CheckLength(true,out err);
            result = JsonConvert.SerializeObject(poco);
            Console.WriteLine("POCO => json String:" + result);

            Console.ReadLine();
        }
Example #2
0
        /// <summary>
        /// Run 3 Pass Authenticate Flow by Byte Array(length:25)
        /// </summary>
        /// <param name="inputData">challenge Data and parameters</param>
        /// <returns>RanB||E(RanA||RanBRol8)||E(iv,RanARol8)||RanAStartIndex</returns>
        private static byte[] DoAuthenticate(byte[] inputData)
        {
            byte[] result = null;
            if (inputData.Length != 25)
                return result;                        //ha ha
            string keyLabel = "2ICH3F0000" + inputData[0].ToString() + "A";                 //byte[0]
            string KeyVersion = inputData[1].ToString();                                    //byte[1]
            string uid = BitConverter.ToString(inputData, 2, 7).Replace("-", "");           //byte[2~8]
            string enc_RanB = BitConverter.ToString(inputData, 9, 16).Replace("-", "");     //byte[9~24]
            EskmsPOCO response = null;
            EskmsPOCO request = new EskmsPOCO()
            {
                Input_KeyLabel = keyLabel,
                Input_KeyVersion = KeyVersion,
                Input_UID = uid,
                Input_Enc_RanB = enc_RanB
            };
            #region Authenticate Object Old
            //IiBonAuthenticate iBonAuth = null;
            //try
            //{
            //    iBonAuth = new iBonAuthenticate()
            //    {
            //        Input_KeyLabel = keyLabel,
            //        Input_KeyVersion = KeyVersion,
            //        Input_UID = uid,
            //        Input_Enc_RanB = enc_RanB,
            //    };
            //    //run
            //    iBonAuth.StartAuthenticate(true);
            //}
            //catch (Exception ex)
            //{
            //    log.Error("[iBonAuthenticate] Error:" + ex);
            //    return new byte[5] { 0x45, 0x72, 0x72, 0x6F, 0x72 };//return "Error"
            //}
            #endregion
            response = GetResponse(request);
            if (response != null)
            {
                result = new byte[response.Output_RanB.Length +
                                     response.Output_Enc_RanAandRanBRol8.Length +
                                     response.Output_Enc_IVandRanARol8.Length + 4];
                byte[] randAStartIndexBytes = BitConverter.GetBytes(response.Output_RandAStartIndex);//4 bytes
                Buffer.BlockCopy(response.Output_RanB, 0, result, 0, response.Output_RanB.Length);//Copy Random B in Result
                Buffer.BlockCopy(response.Output_Enc_RanAandRanBRol8, 0, result, response.Output_RanB.Length, response.Output_Enc_RanAandRanBRol8.Length);//Copy E(RanA || RanBRol8) in Result
                Buffer.BlockCopy(response.Output_Enc_IVandRanARol8, 0, result, response.Output_RanB.Length + response.Output_Enc_RanAandRanBRol8.Length, response.Output_Enc_IVandRanARol8.Length);//Copy E(iv,RanARol8) in Result
                Buffer.BlockCopy(randAStartIndexBytes, 0, result, response.Output_RanB.Length + response.Output_Enc_RanAandRanBRol8.Length + response.Output_Enc_IVandRanARol8.Length, randAStartIndexBytes.Length);//Copy Random A Start Index (4 Bytes)
                log.Debug("RanB:" + BitConverter.ToString(response.Output_RanB).Replace("-", ""));
                log.Debug("E(RanA || RanBRol8):" + BitConverter.ToString(response.Output_Enc_RanAandRanBRol8).Replace("-", ""));
                log.Debug("E(iv,RanARol8):" + BitConverter.ToString(response.Output_Enc_IVandRanARol8).Replace("-", ""));
                log.Debug("Random A Start Index:" + response.Output_RandAStartIndex);
                log.Debug("Session Key:" + BitConverter.ToString(response.Output_SessionKey).Replace("-", ""));
            }

            return result;
        }
Example #3
0
        /// <summary>
        /// 連線後端AP並取得output data
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static EskmsPOCO GetResponse(EskmsPOCO request)
        {
            string requestStr = null;
            byte[] requestBytes = null;
            string responseStr = null;
            byte[] responseBytes = null;
            string ip = null;
            int port = -1;
            int sendTimeout = -1;
            int receiveTimeout = -1;
            string serverConfig = null;
            string[] configs = null;
            EskmsPOCO response = null;
            //*********************************
            //取得連線後台的WebConfig設定資料
            serverConfig = ConfigGetter.GetValue(ServiceName);
            log.Debug(m => { m.Invoke(ServiceName + ":" + serverConfig); });
            if (serverConfig != null)
            {
                configs = serverConfig.Split(':');
                ip = configs[0];
                port = Convert.ToInt32(configs[1]);
                sendTimeout = Convert.ToInt32(configs[2]);
                receiveTimeout = Convert.ToInt32(configs[3]);
            }
            else
            {
                log.Error("要連結的目的地設定資料不存在:" + ServiceName);
                return null;
            }
            //*********************************
            try
            {
                using (SocketClient.Domain.SocketClient connectToAP = new SocketClient.Domain.SocketClient(ip, port, sendTimeout, receiveTimeout))
                {
                    log.Debug("開始連線後端服務:" + serverConfig);
                    if (connectToAP.ConnectToServer())
                    {
                        //UTF8(JSON(POCO))=>byte array and send to AP
                        requestStr = JsonConvert.SerializeObject(request);
                        log.Debug(m => m("[Authenticate]Request JsonString({0}): {1}", ServiceName, requestStr));
                        requestBytes = Encoding.UTF8.GetBytes(requestStr);//Center AP used UTF8
                        responseBytes = connectToAP.SendAndReceive(requestBytes);
                        if (responseBytes != null)
                        {
                            responseStr = Encoding.UTF8.GetString(responseBytes);
                            response = JsonConvert.DeserializeObject<EskmsPOCO>(responseStr);
                            //Byte[] 會被JSON轉成Base64格式
                            log.Debug(m => {
                                m.Invoke("[Authenticate]Response JsonString:\n RanB:{0}, E(RanA,RanBRol8):{1}, E(IV,RanARol8):{2}, RandAIndex:{3}, SessionKey:{4}",
                                    BitConverter.ToString(response.Output_RanB).Replace("-", ""),
                                    BitConverter.ToString(response.Output_Enc_RanAandRanBRol8).Replace("-", ""),
                                    BitConverter.ToString(response.Output_Enc_IVandRanARol8).Replace("-", ""),
                                    response.Output_RandAStartIndex.ToString(),
                                    BitConverter.ToString(response.Output_SessionKey).Replace("-", "")); });
                        }
                        else
                        {
                            //Byte[] 會被JSON轉成Base64格式
                            log.Debug(m => { m.Invoke("[Authenticate]Response JsonString: null"); });
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                log.Error("後台連線異常:" + ex.Message);
            }
            return response;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="absClientRequestHandler"></param>
        public void Handle(AbsClientRequestHandler absClientRequestHandler)
        {
            #region variable
            byte[] receiveBuffer = null;
            int readCount = 0;
            string requestJsonStr = null;
            string outputCmd = null;
            iBonAuthenticate iBonAuthObj = null;
            EskmsPOCO request = null;
            EskmsPOCO response = null;
            string requestCheckErrMsg = null;
            string responseJsonStr = null;
            byte[] responseBytes = null;
            int sendCount = -1;
            #endregion

            try
            {
                receiveBuffer = new byte[0x1000];//4k
                readCount = absClientRequestHandler.ClientSocket.Receive(receiveBuffer, SocketFlags.None);
                if (readCount == 0) { return; }
                    //command 輸出狀態 TODO...
                else if (readCount == 6 && Encoding.UTF8.GetString(receiveBuffer, 0, readCount).ToLower().Contains("status"))
                {
                    outputCmd = "Hello";
                    receiveBuffer = Encoding.UTF8.GetBytes(outputCmd);
                    absClientRequestHandler.ClientSocket.Send(receiveBuffer);
                    return;
                }
                else
                {
                    log.Debug(m => m(">> {0}: {1}", this.GetType().Name, absClientRequestHandler.ClientNo));
                    //resize buffer
                    Array.Resize(ref receiveBuffer, readCount);
                    //casting jsonstring from buffer array
                    requestJsonStr = Encoding.UTF8.GetString(receiveBuffer);
                    log.Debug(m => m("[{0}]Request: {1}", this.GetType().Name, requestJsonStr));
                    request = JsonConvert.DeserializeObject<EskmsPOCO>(requestJsonStr);
                    //檢查Request資料長度(Attribute)
                    request.CheckLength(true, out requestCheckErrMsg);
                    //設定Authenticate參數
                    iBonAuthObj = new iBonAuthenticate()
                    {
                        Input_KeyLabel = request.Input_KeyLabel,
                        Input_KeyVersion = request.Input_KeyVersion,
                        Input_UID = request.Input_UID,
                        Input_Enc_RanB = request.Input_Enc_RanB
                    };
                    log.Debug(m => m("開始執行Authenticate"));
                    iBonAuthObj.StartAuthenticate(true);//會傳送數據到KMS並取回DiverseKey後做運算並將結果寫入Output屬性中

                    //回應資料設定
                    response = new EskmsPOCO()
                    {
                        Input_KeyLabel = request.Input_KeyLabel,
                        Input_KeyVersion = request.Input_KeyVersion,
                        Input_UID = request.Input_UID,
                        Input_Enc_RanB = request.Input_Enc_RanB,
                        Output_RanB = iBonAuthObj.Output_RanB,
                        Output_Enc_RanAandRanBRol8 = iBonAuthObj.Output_Enc_RanAandRanBRol8,
                        Output_Enc_IVandRanARol8 = iBonAuthObj.Output_Enc_IVandRanARol8,
                        Output_RandAStartIndex = iBonAuthObj.Output_RandAStartIndex,
                        Output_SessionKey= iBonAuthObj.Output_SessionKey
                    };
                    responseJsonStr = JsonConvert.SerializeObject(response);
                    responseBytes = Encoding.UTF8.GetBytes(responseJsonStr);
                    log.Debug(m => m("[{0}] Response:{1}", this.GetType().Name, responseJsonStr));
                    sendCount = absClientRequestHandler.ClientSocket.Send(responseBytes);
                    if (sendCount != responseBytes.Length)
                    {
                        log.Error(m => m("異常:送出資料(length:{0}不等於原始資料(length:{1}))", sendCount, responseBytes.Length));
                    }
                    log.Debug(m => m("[{0}] Response End", this.GetType().Name));
                }
            }
            catch (ArgumentOutOfRangeException ex)
            {
                log.Error(m => m("資料檢核失敗:{0}",ex.ToString()));
            }
            catch(JsonException ex)
            {
                log.Error(m => m("Request(JsonString) Parse Request(Object) Failed:{0}", ex.ToString()));
            }
            catch (Exception ex)
            {
                log.Error(m => m("[{0}] Error:{1} {2}", this.GetType().Name, ex.Message, ex.StackTrace));
            }
            finally
            {

                absClientRequestHandler.ServiceState = new State_Exit();
            }
        }