public void ShouldReturnExpectedHash() { var service = new SignatureService("TEST"); var response = service.CreateSignature("CHALLENGE", "http://URL.com/foo", Enumerable.Empty<SignatureFactor>()); response.SignatureHash.Should().Be("kuKRmO5ds6wyiI15C7XuUdaa4oXCR0SjsLGLu911pFIYme+8JRaoLj6n7RjKqASYcAPMAg7dlat7jQDlzLkNQg=="); response.SignatureSource.Should().Be("CHALLENGE|TEST|URL.COM/FOO"); }
public void ShouldReturnExpectedHash_WithFactors() { var service = new SignatureService("TEST"); var response = service.CreateSignature("CHALLENGE", "http://URL.com/foo", new[] { new SignatureFactor("TestFactor", "TestValue"), new SignatureFactor("SecondTest", "SecondValue") }); response.SignatureHash.Should().Be("1kLQk1bHuIShUZTqwyQGoI0gToacPK/LGmGREZa3WT4QV0CPVbOqUu91TWP5x2LpXLFR4G6e29C60KSztGnJ2A=="); response.SignatureSource.Should().Be("SecondTest^SecondValue|TestFactor^TestValue|CHALLENGE|TEST|URL.COM/FOO"); }
public void Sign_SignsTheGivenPayload() { string signature = new SignatureService { Key = "secret-key", Hasher = new FakeHasher() }.Sign("my-payload"); Assert.AreEqual("my-payload-signed-with-secret-key|my-payload", signature); }
public void ShouldReturnEquivalentHashes_WhenFactorsAreInDifferentOrder() { var service = new SignatureService("TEST"); var factor1 = new SignatureFactor("TestFactor", "TestValue"); var factor2 = new SignatureFactor("SecondTest", "SecondValue"); var response = service.CreateSignature("CHALLENGE", "http://URL.com/foo", new[] { factor1, factor2 }); var response2 = service.CreateSignature("CHALLENGE", "http://URL.com/foo", new[] { factor2, factor1 }); response.SignatureHash.Should().Be(response2.SignatureHash); }
public Fiscalization(X509Certificate2 certificate) { if (certificate == null) { throw new ArgumentNullException("Certificate"); } ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; _fiscalService = new FiscalizationServiceProvider(); _fiscalService.Url = SERVICE_URL_TEST; _certificate = certificate; _signatureService = new SignatureService(); }
public void Sign_Launch_String_Success() { // Setup var payloadString = "test string value"; var secretKey = "supersecretexample"; var expectedSignatureResult = "CTDn+k8xvw8qkO3ZCoDZ9xI0ZzSjfeZqW5WngBmJbEc="; // Hardcoded from a previous run // Run var signatureService = new SignatureService(); var signature = signatureService.Sign(secretKey, payloadString); // Assert Assert.IsNotNull(signature); Assert.AreEqual(signature, expectedSignatureResult); }
public void LoadKeysTest() { //Clear keys from other tests SignatureService.PublicKey = null; SignatureService.PrivateKey = null; Assert.IsNull(SignatureService.PublicKey); Assert.IsNull(SignatureService.PrivateKey); //Load Keys SignatureService.LoadPrivateKey("Team1/StockServer"); SignatureService.LoadPublicKey("Team1/StockServer"); //Prepare a MarketDay var stock1 = new ValuatedStock() { Symbol = "STK1", Name = "Stock 1", Open = 1, High = 2, Low = 3, Close = 4, Volume = 5 }; var stock2 = new ValuatedStock() { Symbol = "STK2", Name = "Stock 2", Open = 6, High = 7, Low = 8, Close = 9, Volume = 10 }; ValuatedStock[] stocks = { stock1, stock2 }; var marketDay = new MarketDay("testDay", stocks); //Sign marketDay string signature = SigServe.GetSignature(marketDay); //Verify signature var isVerified = SigServe.VerifySignature(marketDay, signature); Assert.IsTrue(isVerified); }
public void BankTransferNotificationTest() { var apiKey = new ApiKey { Key = "00706602-bcb6-48e1-939b-b3f02626f2e0", Secret = "zXqWzZMCaa7F7GiT64Vnd7Yy0CoqaaHpUySxHfSfE9AF8QBtToo0WYO5y-BTwl0L" }; var signatureService = new SignatureService { ApiKey = apiKey }; string json = "{\"data\":{\"amount\":20078,\"currency\":\"EUR\",\"customer\":{\"email\":\"[email protected]\",\"first_name\":\"Lukáš\",\"last_name\":\"Tester\"},\"external_id\":\"1390\",\"id\":477738,\"idempotency_key\":null,\"metadata\":null,\"object\":\"checkout\",\"payment\":null,\"redirect_url\":\"https://localhost\",\"status\":\"processing\"},\"external_id\":\"1390\",\"nonce\":\"TXRYWklDTjdCZHBQTno2Nw==\",\"object\":\"webhook\",\"signature\":\"9b63299479d97da9ac8bf5fb49d7767fbfffe2a44af1c5397f933e17c75ca56a\",\"type\":\"bank_transfer.in_transit\"}"; var notification = JsonSerializer.Deserialize <BaseNotification>(json); var checkout = notification.TryParse <Checkout>(); Assert.True(notification.ExternalId == checkout.ExternalId); Assert.True(notification.Signature == notification.CalculateSignature(signatureService)); }
public void PaymentNotificationTest() { var apiKey = new ApiKey { Key = "00706602-bcb6-48e1-939b-b3f02626f2e0", Secret = "zXqWzZMCaa7F7GiT64Vnd7Yy0CoqaaHpUySxHfSfE9AF8QBtToo0WYO5y-BTwl0L" }; var signatureService = new SignatureService { ApiKey = apiKey }; string json = "{\"data\":{\"amount\":1499,\"currency\":\"EUR\",\"customer\":{\"email\":\"[email protected]\",\"first_name\":\"Lukáš\",\"last_name\":\"Tester\"},\"external_id\":\"5333\",\"id\":477760,\"idempotency_key\":null,\"metadata\":null,\"object\":\"checkout\",\"payment\":{\"created_at\":1587455451,\"failure_reason\":\"\",\"fee\":65,\"net\":1434,\"object\":\"payment\",\"payment_method\":\"PayU\",\"status\":\"successful\"},\"redirect_url\":\"https://localhost\",\"status\":\"succeeded\"},\"external_id\":\"5333\",\"nonce\":\"Z0FidXlCSVUxcUxsbEVwag\",\"object\":\"webhook\",\"signature\":\"43a0ac2b9005ba1b4305cf00f7ac3d84db7c461dd84f00e58868565dd4f71efe\",\"type\":\"checkout.succeeded\"}"; var notification = JsonSerializer.Deserialize <BaseNotification>(json); var checkout = notification.TryParse <Checkout>(); Assert.True(notification.ExternalId == checkout.ExternalId); Assert.True(notification.Signature == notification.CalculateSignature(signatureService)); }
protected override Task <JObject> SignAsync(IVerifyData payload, JObject proof, ProofOptions options) { var verifyData = payload as StringArray ?? throw new ArgumentException("Invalid data type"); if (KeyPair?.SecretKey == null) { throw new Exception("Private key not found."); } var proofValue = SignatureService.Sign(new SignRequest(KeyPair, verifyData.Data)); proof["proofValue"] = Convert.ToBase64String(proofValue); proof["type"] = "BbsBlsSignature2020"; return(Task.FromResult(proof)); }
[Route("sso/user/delete")] // Request from sso to delete user self from sso to all apps public IHttpActionResult DeleteViaSSO([FromBody, Required] LoginRequestPayload requestPayload) { using (var _db = new DatabaseContext()) { try { // Throws ExceptionService.InvalidModelPayloadException ControllerHelpers.ValidateModelAndPayload(ModelState, requestPayload); // Throws ExceptionService.InvalidGuidException var userSSOID = ControllerHelpers.ParseAndCheckId(requestPayload.SSOUserId); // Check valid signature var _ssoServiceAuth = new SignatureService(); var validSignature = _ssoServiceAuth.IsValidClientRequest(userSSOID.ToString(), requestPayload.Email, requestPayload.Timestamp, requestPayload.Signature); if (!validSignature) { return(Content(HttpStatusCode.Unauthorized, "Invalid Token signature.")); } var _userManagementManager = new UserManagementManager(_db); // Throw exception if user does not exist var user = _userManagementManager.GetUser(userSSOID); if (user == null) { return(Content(HttpStatusCode.OK, "User does not exist")); } _userManagementManager.DeleteUser(userSSOID); _db.SaveChanges(); return(Ok("User was deleted")); } catch (Exception e) when(e is InvalidGuidException || e is InvalidModelPayloadException) { return(Content(HttpStatusCode.BadRequest, e.Message)); } catch (Exception e) { if (e is DbUpdateException || e is DbEntityValidationException) { _db.RevertDatabaseChanges(_db); } return(Content(HttpStatusCode.InternalServerError, e.Message)); } } }
public async Task <IHttpActionResult> Delete([FromBody] ExternalUserDeleteRequestModel request) { if (!ModelState.IsValid || request == null) { return(Content((HttpStatusCode)412, ModelState)); } using (var _db = new DatabaseContext()) { IApplicationService _applicationService = new ApplicationService(_db); SignatureService _signatureService = new SignatureService(); Application app = _applicationService.GetApplication(Guid.Parse(request.appId)); var incomingPayload = new Dictionary <string, string>(); incomingPayload.Add("appId", request.appId); incomingPayload.Add("ssoUserId", request.ssoUserId.ToString()); incomingPayload.Add("email", request.email); incomingPayload.Add("timestamp", request.timestamp.ToString()); if (!(_signatureService.Sign(app.SharedSecretKey, incomingPayload) == request.signature)) { return(Content(HttpStatusCode.Unauthorized, "Signature not valid!")); } try { UserManager um = new UserManager(_db); User user = await um.DeleteUser(_db, request.ssoUserId); return(Ok(user)); } catch (Exception ex) { if (ex is FailedDeleteException) { return(Content(HttpStatusCode.BadRequest, "Some applications failed to delete")); } if (ex is DbEntityValidationException) { return(Content(HttpStatusCode.InternalServerError, "Database error")); } return(Content(HttpStatusCode.InternalServerError, "Service Unavailable")); } } }
public void ExecutePacket(AsyncConnection connection, ByteBuffer packet) { uint RequestedRootID = packet.ReadUInt(); // 0x50500000 string cnx_type_1 = packet.ReadString(); // * string cnx_type_2 = packet.ReadString(); // timesource packet.ReadString(); // String.Empty packet.ReadString(); // String.Empty string cnx_type_3 = packet.ReadString(); // Application_TimeRequester packet.ReadString(); // String.Empty string objectId = packet.ReadString(); SignatureService.RequestServerSignature(connection, cnx_type_2); }
protected override Task VerifyAsync(IVerifyData payload, JToken proof, JToken verificationMethod, ProofOptions options) { var verifyData = payload as StringArray ?? throw new ArgumentException("Invalid data type"); var blsVerificationMethod = new Bls12381G2Key2020(verificationMethod as JObject); var key = new BlsKeyPair(Multibase.Base58.Decode(blsVerificationMethod.PublicKeyBase58)); var signature = Helpers.FromBase64String(proof["proofValue"]?.ToString() ?? throw new Exception("Proof value not found")); var valid = SignatureService.Verify(new VerifyRequest(key, signature, verifyData.Data)); if (!valid) { throw new Exception("Invalid signature"); } return(Task.CompletedTask); }
public void Sign_Launch_String_Different_Keys() { // Setup var payloadString = "test string value"; var secretKey1 = "supersecretexample"; var secretKey2 = "supersecretexample2"; // Run var signatureService = new SignatureService(); var signature1 = signatureService.Sign(secretKey1, payloadString); var signature2 = signatureService.Sign(secretKey2, payloadString); // Assert Assert.IsNotNull(signature1); Assert.IsNotNull(signature2); Assert.AreNotEqual(signature1, signature2); }
public async void GetCheckout() { var clientService = new ClientService(new ApiKey { Key = Constants.KEY, Secret = Constants.SECRET, Host = Constants.HOST }); var apiKey = new ApiKey { Key = Constants.KEY, Secret = Constants.SECRET }; var signatureService = new SignatureService { ApiKey = apiKey }; var response = await clientService.GetCheckout(new GetCheckoutRequest { Id = 480047 }); Assert.True(response != null); Assert.True(response.Signature == response.CalculateSignature(signatureService)); }
public async void GetCheckouts() { var clientService = new ClientService(new ApiKey { Key = Constants.KEY, Secret = Constants.SECRET, Host = Constants.HOST }); var apiKey = new ApiKey { Key = Constants.KEY, Secret = Constants.SECRET }; var signatureService = new SignatureService { ApiKey = apiKey }; var response = await clientService.GetCheckouts(new GetCheckoutListRequest { Limit = 50, Offset = 0 }); Assert.True(response != null); Assert.True(response.All(a => a.Signature == a.CalculateSignature(signatureService))); }
public void Create_SignatureWithData_NewSignature() { var newSignature = new DataPlus.Entities.Models.Signature { Id = Guid.NewGuid(), Name = "Signature 6", Description = "Signature 6 Description" }; var repositoryWrapper = new Mock <IWrapperRepository>(); repositoryWrapper.Setup(x => x.Signature.GetAll()).Returns(_signatureList.AsQueryable); var signatureService = new SignatureService(repositoryWrapper.Object, _logger); var numberOfSignatures = signatureService.GetAll().Count; signatureService.Create(newSignature); }
public void GetById_SendAndIdToGetAnSignature_SignatureFilteredById() { var repositoryWrapper = new Mock <IWrapperRepository>(); var signatureId = _signatureList.First().Id; repositoryWrapper.Setup(x => x.Signature.GetById(signatureId)).Returns(new DataPlus.Entities.Models.Signature { Id = signatureId, Name = "Signature 1", Description = "Signature 1 Description" }); var signatureService = new SignatureService(repositoryWrapper.Object, _logger); var signature = signatureService.GetById(signatureId); Assert.True(signature != null); Assert.True(signature.Name == "Signature 1"); Assert.True(signature.Description == "Signature 1 Description"); }
public void ValidSignatureTest() { var key = SignatureService.GenerateKeys(1024); SignatureService.PublicKey = (RsaKeyParameters)(key.Public); SignatureService.PrivateKey = (RsaKeyParameters)(key.Private); var sigServe = new SignatureService(); var stock1 = new ValuatedStock(); var stock2 = new ValuatedStock(); ValuatedStock[] stocks = { stock1, stock2 }; var date = "1990-02-29"; var marketDay = new MarketDay(date, stocks); var marketDaySig = sigServe.GetSignature(marketDay); var stockPriceUpdate = new StockPriceUpdate(marketDay) { StockListSignature = marketDaySig }; var isOriginalValid = sigServe.VerifySignature(marketDay, marketDaySig); Assert.IsTrue(isOriginalValid); var serializedMessage = stockPriceUpdate.Encode(); var deserializedMessage = MessageFactory.GetMessage(serializedMessage, false) as StockPriceUpdate; MarketDay deserializedDay = sigServ.Deserialize <MarketDay>(Convert.FromBase64String(deserializedMessage.SerializedStockList)); var StocksList_original = sigServ.Deserialize <MarketDay>(Convert.FromBase64String(stockPriceUpdate.SerializedStockList)); var StocksList_deserialized = sigServ.Deserialize <MarketDay>(Convert.FromBase64String(deserializedMessage.SerializedStockList)); var isDeserializedValid = sigServe.VerifySignature(StocksList_deserialized, deserializedMessage.StockListSignature); Assert.IsTrue(isDeserializedValid); Assert.AreEqual(StocksList_original.TradedCompanies.Count, StocksList_deserialized.TradedCompanies.Count); Assert.AreEqual(StocksList_original.Date, StocksList_deserialized.Date); Assert.IsTrue(sigServe.VerifySignature(StocksList_deserialized, deserializedMessage.StockListSignature)); }
public void Sign_Launch_Dict_Success() { // Setup var launchPayload = new Dictionary <string, string>(); launchPayload.Add("ssoUserId", "example"); launchPayload.Add("email", "example2"); launchPayload.Add("timestamp", "example3"); var secretKey = "supersecretexample"; var expectedSignatureResult = "bGqhkWq4Nia3jU7TYj/2i2ewG79ZtkLXwLrDy+mFSVc="; // Hardcoded from a previous run // Run var signatureService = new SignatureService(); var signature = signatureService.Sign(secretKey, launchPayload); // Assert Assert.IsNotNull(signature); Assert.AreEqual(expectedSignatureResult, signature); }
public override Envelope Prepare() { Log.Debug($"{nameof(Prepare)} (enter)"); var sigServ = new SignatureService(); var message = MessageFactory.GetMessage <StockPriceUpdate>(Config.GetInt(Config.STOCK_SERVER_PROCESS_NUM), 0) as StockPriceUpdate; message.ConversationID = Conversation.Id; message.SerializedStockList = Convert.ToBase64String(sigServ.Serialize(DayData)); message.StockListSignature = sigServ.GetSignature(DayData); var env = new Envelope(message) { To = this.To }; Log.Debug($"{nameof(Prepare)} (exit)"); return(env); }
public void Update_SignatureWithAllData_SignatureUpdated() { var signatureId = _signatureList.First().Id; var repositoryWrapper = new Mock <IWrapperRepository>(); repositoryWrapper.Setup(x => x.Signature.GetAll()).Returns(_signatureList.AsQueryable); repositoryWrapper.Setup(x => x.Signature.GetById(signatureId)).Returns(_signatureList.First(s => s.Id == signatureId)); SignatureService signatureService = new SignatureService(repositoryWrapper.Object, _logger); var signature = signatureService.GetById(signatureId); signature.Name = signature.Name + "_modified"; signatureService.Update(signature); var updatedSignature = signatureService.GetById(signature.Id); Assert.Contains("_modified", updatedSignature.Name); }
/// <summary> /// Onboard an endpoint using the simple onboarding procedure and the given parameters. /// </summary> /// <param name="onboardParameters">The onboarding parameters.</param> /// <param name="privateKey">The private key.</param> /// <returns>-</returns> /// <exception cref="OnboardException">Will be thrown if the onboarding was not successful.</exception> public OnboardResponse Onboard(OnboardParameters onboardParameters, string privateKey) { var onboardingRequest = new OnboardRequest { ExternalId = onboardParameters.Uuid, ApplicationId = onboardParameters.ApplicationId, CertificationVersionId = onboardParameters.CertificationVersionId, GatewayId = onboardParameters.GatewayId, CertificateType = onboardParameters.CertificationType, TimeZone = UtcDataService.TimeZone, UtcTimestamp = UtcDataService.Now }; var requestBody = JsonConvert.SerializeObject(onboardingRequest); var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(_environment.SecuredOnboardingUrl()), Content = new StringContent(requestBody, Encoding.UTF8, "application/json") }; httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", onboardParameters.RegistrationCode); httpRequestMessage.Headers.Add("X-Agrirouter-ApplicationId", onboardParameters.ApplicationId); httpRequestMessage.Headers.Add("X-Agrirouter-Signature", SignatureService.XAgrirouterSignature(requestBody, privateKey)); var httpResponseMessage = _httpClient.SendAsync(httpRequestMessage).Result; if (!httpResponseMessage.IsSuccessStatusCode) { throw new OnboardException(httpResponseMessage.StatusCode, httpResponseMessage.Content.ReadAsStringAsync().Result); } var result = httpResponseMessage.Content.ReadAsStringAsync().Result; var onboardingResponse = JsonConvert.DeserializeObject(result, typeof(OnboardResponse)); return(onboardingResponse as OnboardResponse); }
public void Sign_Launch_Dict_Different_Keys() { // Setup var launchPayload = new Dictionary <string, string>(); launchPayload.Add("ssoUserId", "example"); launchPayload.Add("email", "example2"); launchPayload.Add("timestamp", "example3"); var secretKey1 = "supersecretexample"; var secretKey2 = "supersecretexample2"; // Run var signatureService = new SignatureService(); var signature1 = signatureService.Sign(secretKey1, launchPayload); var signature2 = signatureService.Sign(secretKey2, launchPayload); // Assert Assert.IsNotNull(signature1); Assert.IsNotNull(signature2); Assert.AreNotEqual(signature1, signature2); }
public void SignValid() { //Arrange var sigService = new SignatureService(); string ssoID = "9BC5F4AD-569B-44DA-8FCE-AF02DA88985F"; string email = "*****@*****.**"; string timestamp = "1556419593286"; var payload = new Dictionary <string, string>() { { "ssoUserId", ssoID }, { "email", email }, { "timestamp", timestamp } }; //Act string signedPayload = sigService.Sign(payload); //Assert Assert.IsNotNull(signedPayload); }
public IHttpActionResult DeleteUser(SsoPayload payload) { if (!SignatureService.IsValidClientRequest( payload.SSOUserId, payload.Email, long.Parse(payload.Timestamp), payload.Signature )) { return(Unauthorized()); } if (payload.SSOUserId == null) { return(BadRequest("No SSO user id passed.")); } // Find userid using sso id UserManager userManager = new UserManager(); SessionManager sm = new SessionManager(); SsoManager ssoManager = new SsoManager(); ssoManager.DeleteUserBySsoId(new Guid(payload.SSOUserId)); return(Ok()); }
/// <summary> /// Deletes User from database via SSO. /// </summary> /// <param name="ssoID"></param> /// <param name="email"></param> /// <param name="timestamp"></param> /// <param name="signature"></param> public void DeleteUserFromSSO(Guid ssoID, string email, long timestamp, string signature) { //Validate Request var signatureService = new SignatureService(); bool validRequest = signatureService.IsValid(ssoID, email, timestamp, signature); if (!validRequest) { throw new InvalidRequestSignature("Request Signature is not valid."); } //Check user's existence User user = userService.GetSSOUser(ssoID); if (user == null) { throw new UserDoesNotExistException("User does not exist"); } //Remove user userService.RemoveUser(user); }
public void SSOLogout(Guid ssoID, string email, long timestamp, string signature) { //Validate Request var signatureService = new SignatureService(); bool validRequest = signatureService.IsValid(ssoID, email, timestamp, signature); if (!validRequest) { throw new InvalidRequestSignature("Request Signature is not valid."); } //Check user's existence if (!userManager.SSOUserExists(ssoID)) { throw new UserDoesNotExistException("User does not exist"); } //invalide all tokens User user = userManager.GetSSOUser(ssoID); tokenManager.InvalideAllTokens(user.userID); }
public void Login_ExistingUser_Success() { var existing_user = ut.CreateSSOUserInDb(); var existing_username = existing_user.Username; var existing_ssoID = existing_user.Id; var timestamp = 12312312; var _ssoAuth = new SignatureService(); MockLoginPayload mock_payload = new MockLoginPayload { email = existing_username, ssoUserId = existing_ssoID, timestamp = timestamp }; var signature = mock_payload.Signature(); using (var _db = ut.CreateDataBaseContext()) { _ssoLoginManager = new KFC_SSO_Manager(_db); var response = _ssoLoginManager.LoginFromSSO(existing_username, existing_ssoID, timestamp, signature); Assert.IsNotNull(response); } }
public override Envelope Prepare() { Log.Debug($"{nameof(Prepare)} (enter)"); var message = MessageFactory.GetMessage <UpdateLeaderBoardMessage>(Config.GetInt(Config.BROKER_PROCESS_NUM), 0) as UpdateLeaderBoardMessage; message.ConversationID = Conversation.Id; var leaders = new List <LeaderboardRecord>(); try { foreach (var portfolio in PortfolioManager.Portfolios) { var record = LeaderboardManager.GetLeaderboardRecord(portfolio.Value); leaders.Add(record); } } catch (Exception e) { Log.Error(e); } leaders.Sort((a, b) => a.TotalAssetValue.CompareTo(b.TotalAssetValue)); var sigServ = new SignatureService(); message.SerializedRecords = Convert.ToBase64String(sigServ.Serialize(leaders)); var env = new Envelope(message) { To = this.To }; Log.Debug($"{nameof(Prepare)} (exit)"); return(env); }
public void InvalidSignatureTest() { var key = SignatureService.GenerateKeys(1024); SignatureService.PublicKey = (RsaKeyParameters)(key.Public); SignatureService.PrivateKey = (RsaKeyParameters)(key.Private); var sigServe = new SignatureService(); var stock1 = new ValuatedStock(); var stock2 = new ValuatedStock(); ValuatedStock[] stocks = { stock1, stock2 }; var date = "1990-02-29"; var marketDay = new MarketDay(date, stocks); var marketDaySig = sigServe.GetSignature(marketDay); var stockPriceUpdate = new StockPriceUpdate(marketDay) { StockListSignature = marketDaySig }; var isOriginalValid = sigServe.VerifySignature(marketDay, marketDaySig); Assert.IsTrue(isOriginalValid); var serializedMessage = stockPriceUpdate.Encode(); var deserializedMessage = MessageFactory.GetMessage(serializedMessage, false) as StockPriceUpdate; //"currupt" signature deserializedMessage.StockListSignature = deserializedMessage.StockListSignature.Replace(deserializedMessage.StockListSignature.Substring(0, 5), "fffff"); MarketDay deserializedDay = sigServ.Deserialize <MarketDay>(Convert.FromBase64String(deserializedMessage.SerializedStockList)); var isDeserializedValid = sigServe.VerifySignature(deserializedDay, deserializedMessage.StockListSignature); Assert.IsFalse(isDeserializedValid); }
public async Task <HttpResponseMessage> DeleteUserFromApps(Guid id) { HttpClient client = new HttpClient(); ISignatureService _signatureService = new SignatureService(); // NEED A BETTER PLACE TO HOLD THIS... string appID = "B1CC61FD-6902-4796-BC05-D5E477FE91C8"; ResponseDTO <UserAccountDTO> user = _userManagementService.GetUserByUserId(id); var payload = new Dictionary <string, string>(); payload.Add("appId", appID); payload.Add("ssoUserId", user.Data.SsoId.ToString()); payload.Add("email", user.Data.Username); payload.Add("timestamp", DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString()); var signature = _signatureService.Sign(payload); payload.Add("signature", signature); var stringPayload = JsonConvert.SerializeObject(payload); var jsonPayload = new StringContent(stringPayload, Encoding.UTF8, "application/json"); var request = await client.PostAsync("http://localhost:61348/api/users/appdeleteuser", jsonPayload); return(request); }
private void bntRecuperarArquivoAssinado_Click(object sender, EventArgs e) { SignatureService service = new SignatureService(); var respStatus = service.BatchSignatureTIDsStatus(new SignatureStatusReqType() { TransactionId = Int32.Parse(txtTransacaoDocumento.Text) }); foreach (var doc in respStatus.DocumentSignatureStatus) { var ret = DownloadSignedFile(doc.TransactionId); if (ret.StatusCode == 100) txtLogDocumento.Text += ret.StatusDetail + "\r\n"; } }
private void btnSolicitar_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtDestinoTexto.Text)) { MessageBox.Show("Informe o e-mail de destino da solicitação de assinatura", "ERRO", MessageBoxButtons.OK); return; } var req = new SignatureSimpleDocumentReqType() { TestMode = true, DataToBeSigned = txtAssinarTexto.Text, MobileUser = new MobileUserType() { UniqueIdentifier = txtDestinoTexto.Text }, MessagingMode = MessagingModeType.asynchClientServer }; SignatureService service = new SignatureService(); var resp = service.SignatureSimpleDocument(req); txtLogTexto.Text = string.Format("Servidor retornou {0}\r\n", resp.Status.StatusMessage); txtTransacaoTexto.Text = resp.TransactionId.ToString(); }
private void bntRecuperarTextoAssinado_Click(object sender, EventArgs e) { SignatureService service = new SignatureService(); SignatureStatusRespType respStatus = null; txtLogTexto.Text += "Consultando situacao da assinatura...\r\n"; respStatus = service.StatusQuery(new SignatureStatusReqType() { TransactionId = long.Parse(txtTransacaoTexto.Text) }); if (respStatus.Status.StatusMessage != "TRANSACTION_IN_PROGRESS") { txtLogTexto.Text += "Salvando assinatura...\r\n"; var signedText = string.Format(@"..\..\Signed-{0}.p7s", txtTransacaoTexto.Text); File.WriteAllBytes(signedText, respStatus.Signature); txtLogTexto.Text += "Assinatura salva como " + signedText + ".\r\n"; } else { txtLogTexto.Text += "Assinatura pendente com usuário...\r\n"; } }
public ActionSignatureFilterImpl(GZCDCPay.Services.SignatureService signatureService, ILogger <ActionSignatureFilterImpl> logger) { this.signatureService = signatureService; this.logger = logger; }
private void btnArquivo_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtDestinoDocumento.Text)) { MessageBox.Show("Informe o e-mail de destino da solicitação de assinatura", "ERRO", MessageBoxButtons.OK); return; } if (!File.Exists(txtCaminhoArquivo.Text)) { MessageBox.Show("Informe um arquivo que exista no sistema de arquivos", "ERRO", MessageBoxButtons.OK); return; } var fileExtension = Path.GetExtension(txtCaminhoArquivo.Text); if (!fileExtension.ToUpper().Equals(".PDF")) { MessageBox.Show("Informe um arquivo no formato .PDF", "ERRO", MessageBoxButtons.OK); return; } var fileName = Path.GetFileName(txtCaminhoArquivo.Text); List<HashDocumentInfoType> documents = new List<HashDocumentInfoType>(); var docUpl = UploadFile(fileName, File.ReadAllBytes(txtCaminhoArquivo.Text)); documents.Add(docUpl); var reqAssinatura = new BatchSignatureComplexDocumentReqType() { MobileUser = new MobileUserType() { UniqueIdentifier = txtDestinoDocumento.Text }, MessagingMode = MessagingModeType.asynchClientServer, DataToBeDisplayed = string.Format(txtMensagemDocumento.Text, docUpl.DocumentName), SignatureStandard = SignatureStandardType.adobepdf, SignatureStandardSpecified = true, DocumentsToBeSigned = documents.ToArray(), TestMode = true }; SignatureService service = new SignatureService(); var retSolicitacao = service.BatchSignatureComplexDocument(reqAssinatura); txtLogDocumento.Text = string.Format("Servidor retornou {0}\r\n", retSolicitacao.Status.StatusMessage); txtTransacaoDocumento.Text = retSolicitacao.TransactionId.ToString(); }