/// <summary> /// 调用非对称加密方式对序列号进行验证 /// </summary> /// <param name="serialNumber">正确的序列号</param> /// <returns>如果成功返回True,否则为False</returns> public RegisterResult Register(string serialNumber) { var result = new RegisterResult(); var hardNumber = HardwareInfoHelper.GetCpuId(); try { var str2 = EncodeHelper.DesDecrypt(serialNumber); if (!string.IsNullOrEmpty(str2)) { var encrytedString = str2.Split('|')[0]; var time = Convert.ToDateTime(EncodeHelper.DesDecrypt(str2.Split('|')[1])); var flag2 = RsaSecurityHelper.Validate(hardNumber, encrytedString); var flag = time.AddDays(1.0) > DateTime.Now; result.IsValid = flag2 && flag; result.ValideTo = time; return(result); } } catch { // ignored } return(result); }
public ActionResult GetAuthCode(string telphone = "", string act = "") { if (!Regex.IsMatch(telphone, @"^1[3-9]+\d{9}$")) { result.msg = "手机号码格式不正确!"; return(Json(result)); } PinStore store = PinStoreBLL.SingleModel.GetStoreByPhone(telphone); if (store != null && act == "") { result.msg = "用户名已存在,请登陆"; return(Json(result)); } SendMsgHelper sendMsgHelper = new SendMsgHelper(); string authCode = RedisUtil.Get <string>(telphone); if (string.IsNullOrEmpty(authCode)) { authCode = EncodeHelper.CreateRandomCode(4); } bool sendResult = sendMsgHelper.AliSend(telphone, "{\"code\":\"" + authCode + "\",\"product\":\" " + Enum.GetName(typeof(SendTypeEnum), 11) + "\"}", "小未科技", 401); if (sendResult) { RedisUtil.Set <string>(telphone, authCode, TimeSpan.FromMinutes(5)); result.code = 1; result.msg = "验证码发送成功!"; } else { result.msg = "验证码发送失败,请稍后再试!"; } return(Json(result)); }
/// <summary> /// Get the Xml Needed to make the request. /// </summary> /// <returns></returns> public override byte[] GetXml() { AutoGen.ChargeAndShipOrderRequest retVal = new AutoGen.ChargeAndShipOrderRequest(); retVal.googleordernumber = GoogleOrderNumber; if (Amount > decimal.MinValue && _currency != null) { retVal.amount = new AutoGen.Money(); retVal.amount.currency = _currency; retVal.amount.Value = Amount; } retVal.sendemail = SendEmail; retVal.sendemailSpecified = true; //Both of these items can't be set at the same time. //TODO do we validate that one of the two items are set? var shippingInfo = ItemShippingInformation.ToArray(); if (shippingInfo != null && shippingInfo.Length > 0) { retVal.itemshippinginformationlist = shippingInfo; } var trackingData = TrackingDataList.ToArray(); if (trackingData != null && trackingData.Length > 0) { retVal.trackingdatalist = trackingData; } return(EncodeHelper.Serialize(retVal)); }
public void GetElementValue_NotFound() { byte[] B = EncodeHelper.Serialize(CreateNewOrderNotification()); String Xml = EncodeHelper.Utf8BytesToString(B); Assert.AreEqual("", EncodeHelper.GetElementValue(Xml, "wacky-element")); }
private void ValidateUserLoginRequest(UserSignInRequest request) { ValidationException exception = new ValidationException(); if (request == null) { exception.Add(new ValidationError("common.invalidRequest")); } if (string.IsNullOrWhiteSpace(request.Email)) { exception.Add(new ValidationError("registration.signin.validation.emailRequired")); } if (string.IsNullOrWhiteSpace(request.Pwd)) { exception.Add(new ValidationError("registration.signin.validation.pwdRequired")); } IUserRepository userRepository = IoC.Container.Resolve <IUserRepository>(); User userProfile = userRepository.GetByEmail(request.Email); if (userProfile == null || EncodeHelper.EncodePassword(request.Pwd) != userProfile.Password) { exception.Add(new ValidationError("registration.signin.validation.invalidEmailOrPwd")); } exception.ThrowIfError(); }
protected void SaveLastLoginInfo() { string pwd = this.txtPassword.Text; if (string.IsNullOrWhiteSpace(pwd)) { return; } if (!checkBox1.Checked) { pwd = string.Empty; } pwd = EncodeHelper.Base64Encode(EncodeHelper.Base64Encode(pwd)); PharmacyClientConfig.Config.LastPwd = pwd; string login = this.txtName.Text; if (string.IsNullOrWhiteSpace(login)) { return; } PharmacyClientConfig.Config.LastAccount = login; PharmacyClientConfig.Config.Pswcheck = this.checkBox1.Checked; ConfigHelper <PharmacyClientConfig> .SaveConfig(); }
public void CartSignatureTests() { string xml = "<test />"; string sign = "wnHXcU/1//4SbpVEb88WaIB9td4="; Assert.AreEqual(sign, EncodeHelper.GetCartSignature(xml, "12345")); }
/// <summary>Send the Message to Google Checkout</summary> public virtual GCheckoutResponse Send() { CheckSendPreConditions(); var sendXml = GetXml(); Log.Xml("send-" + Guid.NewGuid() + ".xml", EncodeHelper.Utf8BytesToString(sendXml)); string responseXml = HttpHelper.SendMessage(sendXml, GetPostUrl(), MerchantID, MerchantKey); return ParseResponse(responseXml); }
public void Save() { try { if (Default == null || Default.Count <= 0) { return; } List <JobInfoSyncData> list = Tools.CloneByJson <List <JobInfoSyncData> >(Default); foreach (JobInfoSyncData job in list) { job.createtmp = EncodeHelper.EncodeBase64(job.createtmp); job.targetsql = EncodeHelper.EncodeBase64(job.targetsql); job.sourcesql = EncodeHelper.EncodeBase64(job.sourcesql); job.sourcedbstring = EncodeAndDecode.Encode(job.sourcedbstring); job.targetdbstring = EncodeAndDecode.Encode(job.targetdbstring); job.xmlconfig = EncodeHelper.EncodeBase64(job.xmlconfig); } File.WriteAllText(path, JsonConvert.DeserializeObject(JsonConvert.SerializeObject(list)).ToString()); } catch (Exception ex) { Log4netUtil.Error("定时同步任务配置保存失败,请检查,原因:" + ex.Message, ex); } }
private void btn_login_Click(object sender, EventArgs e) { userName = textBox_UserName.Text.Trim(); password = textBox_Password.Text.Trim(); if (ValidationService.CheckNull(userName) || ValidationService.CheckNull(password)) { XtraMessageBox.Show("用户名或密码不能为空!"); return; } //CheckAdminUser(); UserInfo userInfo = new UserInfo(); userInfo.UserName = userName; userInfo.Password = EncodeHelper.DesEncrypt(password); if (userName == "admin" && password == "admin") //if (MongoHelper.GetInstance().CheckUserLogin(userInfo)) { this.Hide(); FrmStartup spScreen = new FrmStartup(); Program.SetMainForm(spScreen); Program.ShowMainForm(); //Thread.Sleep(5000); //Program.SetMainForm(new FrmMain()); //Program.ShowMainForm(); if (checkBoxRemember.Checked == true) { string string64 = EncodeHelper.DesEncrypt(userName + "|" + password); parsedData["GeneralConfiguration"]["LoginInfo"] = string64; fileIniData.WriteFile(iniFilePath, parsedData); } else { parsedData["GeneralConfiguration"]["LoginInfo"] = ""; fileIniData.WriteFile(iniFilePath, parsedData); } if (radioGroup1.SelectedIndex == 0) { parsedData["GeneralConfiguration"]["Index"] = "0"; fileIniData.WriteFile(iniFilePath, parsedData); } else if (radioGroup1.SelectedIndex == 1) { parsedData["GeneralConfiguration"]["Index"] = "1"; fileIniData.WriteFile(iniFilePath, parsedData); } else if (radioGroup1.SelectedIndex == 2) { parsedData["GeneralConfiguration"]["Index"] = "2"; fileIniData.WriteFile(iniFilePath, parsedData); } this.Close(); } else { XtraMessageBox.Show("用户名或密码错误!"); return; } }
public Dictionary <string, string> DecodeMailSubject(string code) { return(new Dictionary <string, string>() { ["mailSubject"] = EncodeHelper.DecodeMailSubject(code) }); }
private AutoGen.CancelOrderRequest ParseCancelOrderRequest(byte[] Xml) { Type T = typeof(AutoGen.CancelOrderRequest); string Xml2 = EncodeHelper.Utf8BytesToString(Xml); return((AutoGen.CancelOrderRequest)EncodeHelper.Deserialize(Xml2, T)); }
public void ChargeOrderRequest() { ChargeOrderRequest Req; AutoGen.ChargeOrderRequest D; // Test the first constructor. Req = new ChargeOrderRequest(MERCHANT_ID, MERCHANT_KEY, "Sandbox", ORDER_NUMBER); D = (AutoGen.ChargeOrderRequest)EncodeHelper.Deserialize(Req.GetXml()); Assert.AreEqual(ORDER_NUMBER, D.googleordernumber); Assert.AreEqual(null, D.amount); // Test the second constructor. Req = new ChargeOrderRequest(MERCHANT_ID, MERCHANT_KEY, "Sandbox", ORDER_NUMBER, "GBP", 10.2m); D = (AutoGen.ChargeOrderRequest)EncodeHelper.Deserialize(Req.GetXml()); Assert.AreEqual(ORDER_NUMBER, D.googleordernumber); Assert.AreEqual("GBP", D.amount.currency); Assert.AreEqual(10.2m, D.amount.Value); Req = new ChargeOrderRequest(ORDER_NUMBER); D = (AutoGen.ChargeOrderRequest)EncodeHelper.Deserialize(Req.GetXml()); Assert.AreEqual(Req.GoogleOrderNumber, D.googleordernumber); Req = new ChargeOrderRequest(ORDER_NUMBER, "USD", 12.975m); D = (AutoGen.ChargeOrderRequest)EncodeHelper.Deserialize(Req.GetXml()); Assert.AreEqual(Req.GoogleOrderNumber, D.googleordernumber); Assert.AreEqual(Req.Amount, 12.98m); }
public void SendBuyerMessageRequestTests() { SendBuyerMessageRequest req = new SendBuyerMessageRequest(ORDER_NUMBER, MESSAGE, true); AutoGen.SendBuyerMessageRequest post = EncodeHelper.Deserialize(req.GetXml()) as AutoGen.SendBuyerMessageRequest; Assert.AreEqual(req.GoogleOrderNumber, post.googleordernumber); Assert.AreEqual(req.Message, post.message); Assert.AreEqual(req.SendEmail, true); req = new SendBuyerMessageRequest(MERCHANT_ID, MERCHANT_KEY, "Sandbox", ORDER_NUMBER, MESSAGE, true); post = EncodeHelper.Deserialize(req.GetXml()) as AutoGen.SendBuyerMessageRequest; Assert.AreEqual(req.GoogleOrderNumber, post.googleordernumber); Assert.AreEqual(req.Message, post.message); Assert.AreEqual(req.SendEmail, post.sendemail); req = new SendBuyerMessageRequest(ORDER_NUMBER, MESSAGE); post = EncodeHelper.Deserialize(req.GetXml()) as AutoGen.SendBuyerMessageRequest; Assert.AreEqual(req.GoogleOrderNumber, post.googleordernumber); Assert.AreEqual(req.Message, post.message); Assert.AreEqual(req.SendEmail, post.sendemail); req = new SendBuyerMessageRequest(MERCHANT_ID, MERCHANT_KEY, "Sandbox", ORDER_NUMBER, MESSAGE); post = EncodeHelper.Deserialize(req.GetXml()) as AutoGen.SendBuyerMessageRequest; Assert.AreEqual(req.GoogleOrderNumber, post.googleordernumber); Assert.AreEqual(req.Message, post.message); Assert.AreEqual(req.SendEmail, post.sendemail, "Send Email"); }
public void TestGB2312ToUTF8_非中文() { string testString = "English"; string str = EncodeHelper.GB2312ToUTF8(testString); Assert.AreEqual("English", str); }
// Methods public static void InitialCharge() { //http://code.google.com/apis/checkout/developer/Google_Checkout_Beta_Subscriptions.html //using an initial charge with a recurring charge using a different item. CheckoutShoppingCartRequest cartRequest = new CheckoutShoppingCartRequest("123456", "merchantkey", EnvironmentType.Sandbox, "USD", 120); //if you are using a web page and it has the Google Checkout button, you would use this syntax. //= GCheckoutButton1.CreateRequest() ShoppingCartItem initialItem = new ShoppingCartItem(); ShoppingCartItem recurrentItem = new ShoppingCartItem(); initialItem.Price = decimal.Zero; initialItem.Quantity = 1; initialItem.Name = "Item that shows in cart"; initialItem.Description = "This is the item that shows in the cart"; recurrentItem.Price = 2M; recurrentItem.Quantity = 1; recurrentItem.Name = "Item that is charged every month"; recurrentItem.Description = "Description for item that is charged every month"; Subscription subscription = new Subscription(); subscription.Period = GCheckout.AutoGen.DatePeriod.MONTHLY; subscription.Type = SubscriptionType.merchant; SubscriptionPayment payment = new SubscriptionPayment(); payment.MaximumCharge = 120M; payment.Times = 12; subscription.AddSubscriptionPayment(payment); //You must set the item that will be charged for every month. subscription.RecurrentItem = recurrentItem; //you must set the subscription for the item initialItem.Subscription = subscription; cartRequest.AddItem(initialItem); Debug.WriteLine(EncodeHelper.Utf8BytesToString(cartRequest.GetXml())); //Send the request to Google //GCheckout.Util.GCheckoutResponse resp = cartRequest.Send(); //Uncommment this line or perform additional actions //if (resp.IsGood) { //Response.Redirect(resp.RedirectUrl, True) //} //else{ //Response.Write("Resp.ResponseXml = " & Resp.ResponseXml & "<br>"); //Response.Write("Resp.RedirectUrl = " & Resp.RedirectUrl & "<br>"); //Response.Write("Resp.IsGood = " & Resp.IsGood & "<br>"); //Response.Write("Resp.ErrorMessage = " & Resp.ErrorMessage & "<br>"); //} }
public void TestGB2312ToUTF8_中文() { string testString = "中文文本测试"; string str = EncodeHelper.GB2312ToUTF8(testString); Assert.AreEqual("中文文本测试", str); }
private void btnDo_Click(object sender, EventArgs e) { // 取邮箱地址 // 取邮箱用户名密码 // 取要拷贝的路径 AppConfig config = new AppConfig("ZSJob//App.config"); string OApop3Server = config.AppConfigGet("OApop3Server"); Int32 OApop3ServerPort = Convert.ToInt32(config.AppConfigGet("OApop3ServerPort")); string OAUsername = config.AppConfigGet("OAUsername"); string OAUserPwd = config.AppConfigGet("OAUserPwd"); string EmailSubject = config.AppConfigGet("EmailSubject"); string EmailAddress = config.AppConfigGet("EmailAddress"); // 加密 //string encryptPwd = EncodeHelper.Base64Encrypt(OAUserPwd); // 解密 string decryptPwd = EncodeHelper.Base64Decrypt(OAUserPwd); string OutPath = config.AppConfigGet("OutPath"); try { ReceiveMail(OApop3Server, OApop3ServerPort, OAUsername, decryptPwd, OutPath, EmailSubject, EmailAddress); } catch (Exception ex) { LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(AMSDownloadForm)); MessageDxUtil.ShowError(ex.Message); } }
protected void LoadLastLoginInfo() { string login = PharmacyClientConfig.Config.LastAccount; if (!string.IsNullOrWhiteSpace(login)) { this.txtName.Text = login; } string pwd = PharmacyClientConfig.Config.LastPwd; if (!string.IsNullOrWhiteSpace(pwd)) { try { pwd = EncodeHelper.Base64Decode(EncodeHelper.Base64Decode(pwd)); } catch (Exception ex) { pwd = string.Empty; } this.txtPassword.Text = pwd; } bool b = PharmacyClientConfig.Config.Pswcheck; this.checkBox1.Checked = b; }
public GroupFullResult CreateGroup(string vaultId, string groupName, string userId) { var parms = new Dictionary <string, object> { { "name", groupName }, { "policy", EncodeHelper.EncodeToBase64("[{\"Activities\": \"CRUD\", \"Resources\": [\"Vault::.*\", \"Vault::" + vaultId + "\", \"Vault::" + vaultId + "::Schema::.*\", \"Vault::" + vaultId + "::Document::.*\", \"Vault::" + vaultId + "::Blob::.*\", \"Vault::" + vaultId + "::Search::.*\"]}]") }, { "user_ids", userId } }; try { var result = WebHelper.MultipartFormDataPost <GroupFullResult>(BaseUrl + "groups", parms, this.apiKey); return(result); } catch (WebException exception) { if (exception.Status == WebExceptionStatus.ProtocolError) { return(this.GetGroupByName(groupName)); } else { throw; } } }
public void StringToUtf8BytesAndBack() { string Orig = "abc€Œ™©®åëñöÿ!\"#$%&'()*+,-./שּׁзγəˆỊ₪€₧ﻷ"; Assert.AreEqual(Orig, EncodeHelper.Utf8BytesToString(EncodeHelper.StringToUtf8Bytes(Orig))); }
/// <summary> /// Get the Xml For the message /// </summary> /// <returns></returns> public override byte[] GetXml() { var retVal = new AutoGen.OrderSummaryRequest(); retVal.ordernumbers = GoogleOrderNumbers.ToArray(); return(EncodeHelper.Serialize(retVal)); }
private void ProcessRiskInformationNotification(string xmlData) { var riskInformationNotification = (RiskInformationNotification)EncodeHelper.Deserialize(xmlData, typeof(RiskInformationNotification)); var riskSb = new StringBuilder(); riskSb.Append("Risk Information: "); riskSb.Append("googleordernumber: "); riskSb.Append(riskInformationNotification.googleordernumber); riskSb.Append(", avsresponse: "); riskSb.Append(riskInformationNotification.riskinformation.avsresponse); riskSb.Append(", ipaddress: "); riskSb.Append(riskInformationNotification.riskinformation.ipaddress); riskSb.Append(", partialccnumber: "); riskSb.Append(riskInformationNotification.riskinformation.partialccnumber); string message = riskSb.ToString(); LogMessage(message); Order order = GetMerchantOrderByGoogleOrderId(riskInformationNotification.googleordernumber); if (order != null) { //add a note order.OrderNotes.Add(new OrderNote() { Note = message, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); } }
/// <summary> /// Return the Xml data needed to be posted to the server. /// </summary> /// <returns></returns> public override byte[] GetXml() { AutoGen.NotificationDataTokenRequest retVal = new GCheckout.AutoGen.NotificationDataTokenRequest(); retVal.starttime = _beginDate; return(EncodeHelper.Serialize(retVal)); }
public async Task <IActionResult> Register([FromBody] RegisterRequest request) { var user = new ShopUser { UserName = request.Username, Email = request.Username }; var result = await _userManager.CreateAsync(user, request.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); await _userManager.AddToRoleAsync(user, UserRole.User.ToString()); var code = EncodeHelper.Base64Encode(await _userManager.GenerateEmailConfirmationTokenAsync(user)); var confirmationLink = UrlExtensions.EmailConfirmationLink(user.Id, code, _configuration["RedirectDomain"]); await _emailSender.SendConfirmationEmailAsync(request.Username, confirmationLink); _logger.LogInformation($"Confirmation email was sent to user: {user.Name}"); return(StatusCode((int)HttpStatusCode.NoContent)); } var errorResponse = new ErrorResponse(ErrorReasons.BadRequest, result.Errors.Select(e => e.Description).FirstOrDefault()); return(StatusCode((int)HttpStatusCode.BadRequest, errorResponse)); }
public void Init() { try { string setting = File.ReadAllText(path); List <JobInfoCloudHis> list = JsonConvert.DeserializeObject <List <JobInfoCloudHis> >(setting); if (list == null || list.Count <= 0) { return; } foreach (JobInfoCloudHis job in list) { job.createtmp = EncodeHelper.DecodeBase64(job.createtmp); job.targetsql = EncodeHelper.DecodeBase64(job.targetsql); job.targetdbstring = EncodeAndDecode.Decode(job.targetdbstring); job.requestxml = EncodeHelper.DecodeBase64(job.requestxml); job.SettingInterface = this; job.CreatJob(); _Default.Add(job); } } catch (Exception ex) { Log4netUtil.Error("加载定时同步任务配置失败,请检查,原因:" + ex.Message, ex); } }
/// <summary> /// Get the Xml for the message /// </summary> /// <returns></returns> public override byte[] GetXml() { AutoGen.NotificationDataRequest retVal = new GCheckout.AutoGen.NotificationDataRequest(); retVal.continuetoken = _token; return(EncodeHelper.Serialize(retVal)); }
public override bool Insert(UserInfo obj, DbTransaction trans = null) { UserInfo info = (UserInfo)obj; info.Password = EncodeHelper.DesEncrypt(Const.defaultPwd); return(base.Insert(obj, trans)); }
/// <summary>Method that is called to produce the Xml message /// that can be posted to Google Checkout.</summary> public override byte[] GetXml() { AutoGen.CancelItemsRequest retVal = new GCheckout.AutoGen.CancelItemsRequest(); retVal.googleordernumber = GoogleOrderNumber; if (_sendEmailSpecified) { retVal.sendemail = SendEmail; retVal.sendemailSpecified = true; } if (_comment != null && _comment.Length > 0) { retVal.comment = _comment; } if (_reason != null && _reason.Length > 0) { retVal.reason = _reason; } retVal.itemids = Items; return(EncodeHelper.Serialize(retVal)); }
/// <summary> /// 处理接收到的消息体数据 /// </summary> private void OnProcessReceiveMessage() { try { this.IsProcessReceiveMessage = true; byte[] dataValueBytes = EncodeHelper.DecodeMessage(ref this.dataValueBytesCache); if (dataValueBytes == null) { this.IsProcessReceiveMessage = false; } else { //根据接收到的消息体数据转成一个具体的对应类型,然后才能对接收到的消息体数据做处理 SocketMessage tmpSocketMessage = EncodeHelper.DecodeMessage(dataValueBytes); LogMessage.Instance.SetLogMessage( string.Format("接收到客户端对象 [ {0} ] 发送过来的消息 [ {1} ]~", this.ClientSocket.RemoteEndPoint.ToString(), tmpSocketMessage.DataValue.ToString())); //处理完数据需要将处理好的数据回调给上层(通过委托的方式实现) this.ReceiveMessageComplete?.Invoke(this, tmpSocketMessage); //回调之后需要使用尾递归 this.OnProcessReceiveMessage(); } } catch (Exception exception) { Console.WriteLine(exception.Message + " " + exception.StackTrace); } }