Exemple #1
0
        public string GetToken(string v)
        {
            ApiResult apiResult;
            var       jsonStr = "";
            var       decrypt = AesUtility.Decrypt(v);

            try
            {
                var model       = decrypt.FromJson <GetTokenModel.Input>();
                var checkResult = model.IsValid <string>();
                if (checkResult.ErrorCode != EnumItem.Get(Ref.ErrorCode._000).FinalValue)
                {
                    jsonStr = ReturnJsonString(checkResult);
                    return(jsonStr);
                }
                var service = new SecurityService();

                apiResult = service.Execute(model);

                jsonStr = ReturnJsonString(apiResult);
            }
            catch (Exception ex)
            {
                LogRecord.Create()
                .SetMessage(ex.Message)
                .Error()
                ;
            }

            return(jsonStr);
        }
Exemple #2
0
        public static Configuration Load()
        {
            try
            {
                string configContent = File.ReadAllText(CONFIG_FILE);

                //解密
                var data = AesUtility.DecryptString(configContent, ClientId);

                Configuration config = JsonUtility.Deserialize <Configuration>(data);
                config.isDefault = false;
                return(config);
            }
            catch (Exception e)
            {
                if (!(e is FileNotFoundException))
                {
                    Console.WriteLine(e);
                }
                return(new Configuration
                {
                    index = 0,
                    isDefault = true,
                    ApiAddress = "http://api.lovewinne.com/",
                    configs = new List <Server>()
                    {
                        GetDefaultServer()
                    }
                });
            }
        }
        public void GetTokenTest()
        {
            var v = "";

            var models = new GetTokenModel.Input();

            models.OpMid     = "aaaa1bbbb2cccc3dddd4eeee5ffff6ee";
            models.CardNo    = "7413159981000227";
            models.CallTime  = DateTime.Now.ToString("yyyyMMddhhmmss");
            models.MachineID = "Machine0001";
            models.Mask      = models.GetInMask();

            v = JsonConvert.SerializeObject(models);

            var controller = new SecurityController();

            var result = controller.GetToken(AesUtility.Encrypt(v));

            result = result.AesDecrypt();

            var resultObj = result.FromJson <ApiResult>();

            if (resultObj.ErrorCode == "000")
            {
                Assert.IsTrue(true, "errorCode為000");
            }

            Assert.IsFalse(true, resultObj.ErrorMessage);
        }
        /// <summary>
        /// OP取得登入資訊
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        public string QueryByOpMid(string v)
        {
            ApiResult apiResult;
            var       jsonStr = "";
            var       decrypt = AesUtility.Decrypt(v);

            try
            {
                var model = decrypt.FromJson <OpMidModel.Input>();

                var service = new LoveMemberService();

                apiResult = service.Execute(model);

                jsonStr = JsonConvert.SerializeObject(apiResult);
                jsonStr = jsonStr.AesEncrypt();
            }
            catch (Exception ex)
            {
                LogRecord.Create()
                .SetMessage(ex.Message)
                .Error()
                ;
            }

            return(jsonStr);
        }
Exemple #5
0
        public void DecryptString()
        {
            var encrypted       = AesUtility.EncryptStringToBytes_Aes(originalText, Key, IV);
            var decryptedString = AesUtility.DecryptStringFromBytes_Aes(encrypted, Key, IV);

            Assert.AreEqual(originalText, decryptedString);
        }
Exemple #6
0
        public static void Save(Configuration config)
        {
            if (config.index >= config.configs.Count)
            {
                config.index = config.configs.Count - 1;
            }
            if (config.index < 0)
            {
                config.index = 0;
            }
            config.isDefault = false;
            try
            {
                string jsonString = JsonUtility.Serialize(config);

                //加密
                var data = AesUtility.EncryptString(jsonString, ClientId);

                using (StreamWriter sw = new StreamWriter(File.Open(CONFIG_FILE, FileMode.Create)))
                {
                    sw.Write(data);
                    sw.Flush();
                }
            }
            catch (IOException e)
            {
                Console.Error.WriteLine(e);
            }
        }
Exemple #7
0
        public void GenerateLogReport()
        {
            var logs          = _logger.GetLogs();
            var formattedLogs = string.Join(Environment.NewLine, logs.Select(log => log.ToString()));
            var encryptedLogs = AesUtility.EncryptStringToBase64String(formattedLogs, TrainerLogicModule.ModuleDataPrivatesDictionary["Key"], TrainerLogicModule.ModuleDataPrivatesDictionary["Iv"]);

            radRichTextEditorErrorLog.Text = encryptedLogs;
        }
Exemple #8
0
 private void DecryptLogReport()
 {
     try
     {
         var decryptedLogs = AesUtility.DecryptStringFromBase64String(radRichTextEditorErrorLog.Text, TrainerLogicModule.ModuleDataPrivatesDictionary["Key"], TrainerLogicModule.ModuleDataPrivatesDictionary["Iv"]);
         radRichTextEditorErrorLog.Text = decryptedLogs;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Could not decrypt or display the error log.");
     }
 }
Exemple #9
0
        public List <string> DecryptAndLoadLogicModuleSource(string key, string iv, string version)
        {
            List <string> decryptedModules = new List <string>();

#if DEBUG
            // Load source files without dealing with decryption.

            var path = Path.Combine(Environment.CurrentDirectory, "..", "..", "Trainer\\TrainerLogic");

            if (!Directory.Exists(path))
            {
                throw new Exception("Path does not exist: " + path);
            }

            foreach (var filename in _targetSourceCodeFileNames)
            {
                var filePath = Path.Combine(path, filename + ".cs");
                if (!File.Exists(filePath))
                {
                    throw new Exception("File could not be located: " + filePath);
                }

                var contents = File.ReadAllText(filePath);

                if (string.IsNullOrWhiteSpace(contents))
                {
                    throw new Exception($"File does not contain any data: '{filename}'");
                }

                contents = ProcessModuleSource(contents, version);

                decryptedModules.Add(contents);
            }
#endif

#if !DEBUG
            // Decrypt each encrypted source code file.

            foreach (var encryptedModuleData in TrainerLogicModule.EncryptedModuleDataDictionary)
            {
                var decryptedModule = AesUtility.DecryptStringFromBase64String(encryptedModuleData.Value, key, iv);
                decryptedModule = ProcessModuleSource(decryptedModule, version);

                decryptedModules.Add(decryptedModule);
            }
#endif

            return(decryptedModules);
        }
Exemple #10
0
 public void GetKey(SuccessCallback scb, ErrorCallback ecb)
 {
     Send(
         "/key",
         ReceiveMode.SingleString,
         sw => sw.Write("token=" + HttpUtility.UrlEncode(token)),
         data => {
         aes = new AesUtility(data);
         scb(data);
     },
         null,
         ecb,
         null
         );
 }
Exemple #11
0
        protected bool HandleAuthToken(string token, string empAccount, out ArticleAjaxAuthData authData)
        {
            bool isValidToken = true;

            authData = null;

            if (string.IsNullOrEmpty(token))
            {
                isValidToken = false;
            }

            // decrypt token
            if (isValidToken)
            {
                try
                {
                    string aesKeyOfBP = ConfigurationManager.AppSettings["AesKeyOfBP"];
                    string basicIV    = ConfigurationManager.AppSettings["AesIV"];
                    string authJson   = AesUtility.Decrypt(token, aesKeyOfBP, basicIV);
                    authData = JsonConvert.DeserializeObject <ArticleAjaxAuthData>(authJson);
                }
                catch (Exception ex)
                {
                    logger.Error("", ex);
                    isValidToken = false;
                }
            }

            // check account
            if (isValidToken)
            {
                if (empAccount != authData.EmpAccount)
                {
                    isValidToken = false;
                }
            }

            // check postDate
            if (isValidToken)
            {
                if ((DateTime.Now - authData.PostDate).TotalHours >= 24)
                {
                    isValidToken = false;
                }
            }

            return(isValidToken);
        }
Exemple #12
0
 public void Logout(SuccessCallback scb, ErrorCallback ecb)
 {
     Send(
         "/logout",
         ReceiveMode.SingleString,
         sw => sw.Write("token=" + HttpUtility.UrlEncode(token)),
         data => {
         aes      = null;
         token    = null;
         LoggedIn = false;
         RootUrl  = DefaultRootUrl;
         scb(data);
     },
         null,
         ecb,
         null
         );
 }
        public void EncryptAndDecrypt()
        {
            var inputList = new List <string>();

            inputList.Add("test123456789");
            inputList.Add("abcdefg");
            inputList.Add(Guid.NewGuid().ToString("N") + DateTime.Now.ToString("yyyyMMddhhmmss"));
            inputList.Add(Guid.NewGuid().ToString("N") + DateTime.Now.ToString("yyyyMMddhhmmss"));


            foreach (var item in inputList)
            {
                var encrypt  = AesUtility.Encrypt(item);
                var decrypt  = AesUtility.Decrypt(encrypt);
                var actual   = item;
                var expected = decrypt;
                Assert.AreEqual(expected, actual);
            }
        }
Exemple #14
0
        public async Task EncryptLogicModuleSource()
        {
            var path = Path.Combine(Environment.CurrentDirectory, "..", "..", "Trainer\\TrainerLogic");

            if (!Directory.Exists(path))
            {
                await _logger.Log("Path does not exist: " + path, LogLevel.Error);

                return;
            }

            using (var aesAlgo = new AesCryptoServiceProvider())
            {
                aesAlgo.Padding = PaddingMode.PKCS7;
                aesAlgo.KeySize = 256;

                var key = Convert.ToBase64String(aesAlgo.Key);
                var iv  = Convert.ToBase64String(aesAlgo.IV);

                File.WriteAllText(Path.Combine(path, "key.data"), key);
                File.WriteAllText(Path.Combine(path, "iv.data"), iv);

                var encryptedData = new StringBuilder();

                encryptedData.AppendLine($"{{ \"Iv\", \"{iv}\" }},");
                encryptedData.AppendLine($"{{ \"Key\", \"{key}\" }},{Environment.NewLine}");

                foreach (var filename in _targetSourceCodeFileNames)
                {
                    var filePath = Path.Combine(path, filename + ".cs");
                    if (!File.Exists(filePath))
                    {
                        await _logger.Log("File could not be located: " + filePath, LogLevel.Error);

                        return;
                    }

                    var contents = File.ReadAllText(filePath);

                    if (string.IsNullOrWhiteSpace(contents))
                    {
                        await _logger.Log($"File does not contain any data: '{filename}'", LogLevel.Error);

                        return;
                    }

                    var encryptedBytes = AesUtility.EncryptStringToBytes(contents, aesAlgo.Key, aesAlgo.IV);

                    if (encryptedBytes == null)
                    {
                        await _logger.Log($"Could not encrypt data for {filename}", LogLevel.Error);

                        return;
                    }

                    var base64EncryptedData = Convert.ToBase64String(encryptedBytes);
                    File.WriteAllText(filePath.Replace(".cs", ".data"), base64EncryptedData);

                    await _logger.Log($"File '{filename}' has been successfully encrypted and saved.");

                    encryptedData.AppendLine($"{{ \"{filename}\", \"{base64EncryptedData}\" }},");
                }

                await _logger.Log(encryptedData.ToString());
            }
        }
Exemple #15
0
 public void SetKey(string key)
 {
     aes = new AesUtility(key);
 }
        protected bool HandlePreviewToken()
        {
            bool result = false;

            if (qsPreview == null)
            {
                return(false);
            }

            if (qsPreview == "1")
            {
                // redirect to back-stage to get authorization
                string websiteUrl = ConfigurationManager.AppSettings["WebsiteUrl"];
                string backendSsoAuthenticatorUrl = ConfigurationManager.AppSettings["BackendSsoAuthenticatorUrl"];

                if (string.IsNullOrEmpty(backendSsoAuthenticatorUrl))
                {
                    logger.Error("Invalid AppSettings/BackendSsoAuthenticatorUrl");
                    return(false);
                }

                string valueInToken = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string token        = AesUtility.Encrypt(valueInToken, aesKeyOfFP, basicIV);
                string location     = websiteUrl + "/" + Request.AppRelativeCurrentExecutionFilePath.Replace("~/", "");
                string url          = StringUtility.SetParaValueInUrl(backendSsoAuthenticatorUrl, "token", Server.UrlEncode(token));
                url = StringUtility.SetParaValueInUrl(url, "location", Server.UrlEncode(location));
                url = AppendCurrentQueryString(url);
                Response.Redirect(url);
            }
            else
            {
                try
                {
                    // decrypt token
                    string         valueInToken   = AesUtility.Decrypt(qsPreview, aesKeyOfBP, basicIV);
                    PreviewArticle previewArticle = JsonConvert.DeserializeObject <PreviewArticle>(valueInToken);

                    if (!string.IsNullOrEmpty(previewArticle.EmpAccount))
                    {
                        if (DateTime.Now <= previewArticle.ValidTime)
                        {
                            articleData.ArticleId = new Guid(previewArticle.ArticleId);
                            result        = true;
                            isPreviewMode = true;

                            logger.DebugFormat("{0} previews {1} (id:[{2}])(lang:{3}).",
                                               previewArticle.EmpAccount,
                                               Request.AppRelativeCurrentExecutionFilePath,
                                               previewArticle.ArticleId,
                                               qsLangNo);
                        }
                        else
                        {
                            logger.InfoFormat("{0} previews {1} but exceed valid time.", previewArticle.EmpAccount, Request.AppRelativeCurrentExecutionFilePath);
                        }
                    }
                    else
                    {
                        logger.InfoFormat("user previews {0} but not logged in.", Request.AppRelativeCurrentExecutionFilePath);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("", ex);
                }
            }

            return(result);
        }
Exemple #17
0
        public void EncryptString()
        {
            var encrypted = AesUtility.EncryptStringToBytes_Aes(originalText, Key, IV);

            Assert.AreNotEqual(originalText, encrypted.ToString());
        }
Exemple #18
0
 public void SetKey(string key)
 {
     aes = new AesUtility(key);
 }
Exemple #19
0
 public void Logout(SuccessCallback scb, ErrorCallback ecb)
 {
     Send(
         "/logout",
         ReceiveMode.SingleString,
         sw => sw.Write("token=" + HttpUtility.UrlEncode(token)),
         data => {
             aes = null;
             token = null;
             LoggedIn = false;
             RootUrl = DefaultRootUrl;
             scb(data);
         },
         null,
         ecb,
         null
     );
 }
Exemple #20
0
 public void GetKey(SuccessCallback scb, ErrorCallback ecb)
 {
     Send(
         "/key",
         ReceiveMode.SingleString,
         sw => sw.Write("token=" + HttpUtility.UrlEncode(token)),
         data => {
             aes = new AesUtility(data);
             scb(data);
         },
         null,
         ecb,
         null
     );
 }