public static UserProfile AuthenticateUser(string uname, string pass) { string UserPassword; UserProfile userinfo = GetUserInfo(uname, out UserPassword); return userinfo; bool userIsBlock = IsInBlockList(uname); if (userinfo != null && !userIsBlock) { CryptoEngine Cryp = new CryptoEngine(); string DecryptPass = Cryp.decrypt(userinfo.UserID, UserPassword); if (DecryptPass == pass) return userinfo; } else { AddRankInBlockList(uname); if (userIsBlock) { string excep = " کاربر گرامي به علت رعايت نکات امنيتي و جلوگيري از حدس زدن کلمه عبور ، account شما بصورت موقت تا 2 ساعت ديگر مسدود شده است"; excep += "لطفا مجددا سعي نفرماييد."; throw new Exception(excep); } } return null; }
public ActionResult ConfirmEmail(string token) { if (token == null) { ViewBag.Heading = "Invalid url"; ViewBag.ErrorMessage = "Request page not found"; return(View("Error")); } var activated = UserRepository.ActivateAccount(CryptoEngine.Decrypt(token).Tolong()); if (activated) { return(View("ConfirmEmail")); } else { ViewBag.Heading = "Invalid url"; ViewBag.ErrorMessage = "Request page not found"; return(View("Error")); } }
public ActionResult <Response> Post([FromBody] User user) { try { var fetched_user = appDbContext.Users.SingleOrDefaultAsync(p => p.Email == user.Email); if (fetched_user.Result != null && user.Password == CryptoEngine.Decrypt(fetched_user.Result.Password, "sblw-3hn8-sqoy19")) { HttpContext.Session.SetString("is_login", "true"); HttpContext.Session.SetString("userid", fetched_user.Result.Id.ToString()); return(new Response(null, 200, "Login Successfully")); } else { return(new Response(null, 200, "Login Failed")); } } catch (Exception ex) { logger.LogError(ex, user.ToString()); return(new Response(null, 404, ex.Message)); } }
public async Task <ActionResult> Get(string picEnyc) { var id = Convert.ToInt32(CryptoEngine.DecryptString(picEnyc)); var attachmentList = await _documentAppService.GetAllBusinessDocumentAttachments(id, null, null); if (attachmentList.Items.Count > 0) { var attachment = attachmentList.Items.First(); var contentType = string.Empty; var fileExt = attachment.FileExt.ToLower(); switch (fileExt) { case ".jpg": case ".jpeg": case ".png": contentType = "image/png"; break; } return(PhysicalFile(attachment.FilePath, contentType)); } return(null); }
private void CreateSession() { StreamReader privateKeyStream = System.IO.File.OpenText(Environment.GetEnvironmentVariable("YOTI_KEY_FILE_PATH")); var key = CryptoEngine.LoadRsaKey(privateKeyStream); string clientSdkId = Environment.GetEnvironmentVariable("YOTI_CLIENT_SDK_ID"); string host = Environment.GetEnvironmentVariable("BASE_URL"); if (string.IsNullOrEmpty(host)) { throw new ArgumentNullException("Ensure the BASE_URL environment variable is specified"); } string requestJson; using (StreamReader r = System.IO.File.OpenText("Request.json")) { requestJson = r.ReadToEnd(); } byte[] byteContent = Encoding.UTF8.GetBytes(requestJson); Uri docScanUri = new UriBuilder(scheme: "https", host: host, port: 443, pathValue: "/idverify/v1").Uri; Request docScanRequest = new Yoti.Auth.Web.RequestBuilder() .WithKeyPair(key) .WithHttpMethod(HttpMethod.Post) .WithBaseUri(docScanUri) .WithEndpoint("/sessions") .WithQueryParam("sdkId", clientSdkId) .WithContent(byteContent) .Build(); HttpResponseMessage = docScanRequest.Execute(_httpClient).Result; PageContent = HttpResponseMessage.Content.ReadAsStringAsync().Result; }
public void CheckOfflineXP() { string offlineXP0 = PlayerPrefs.GetString(XP_COIN_SAVE_OFFLINE, ""); string offlineXP = ""; if (offlineXP0 != "") { offlineXP = CryptoEngine.Decrypt(offlineXP0, XP_ENCRYPTION_KEY); } if (offlineXP != "") { int offlineXPInt = Int32.Parse(offlineXP); PlayfabController.Instance.Add_XP_Offline(offlineXPInt, () => { PlayerPrefs.DeleteKey(XP_COIN_SAVE_OFFLINE); //Crashlytics.Log("XP_System|CheckOfflineXP()-> PlayfabController.Instance.Add_XP_Offline() : offline xp data added to the server sucessfully!!!"); }); } }
public void OfflineXPSave(int amount) { string xpDataOffline0 = PlayerPrefs.GetString(XP_COIN_SAVE_OFFLINE, ""); int xpDataInt = 0; string xpDataOffline = ""; if (xpDataOffline0 != "") { xpDataOffline = CryptoEngine.Decrypt(xpDataOffline0, XP_ENCRYPTION_KEY); Debug.Log(XP_ENCRYPTION_KEY); xpDataInt = Int32.Parse(xpDataOffline); } xpDataInt += amount; string xpDataOffline1 = xpDataInt.ToString(); string xpDataEncrypted = CryptoEngine.Encrypt(xpDataOffline1, XP_ENCRYPTION_KEY); PlayerPrefs.SetString(XP_COIN_SAVE_OFFLINE, xpDataEncrypted); Debug.Log("XP_POINT_SAVE_OFFLINE: " + PlayerPrefs.GetString(XP_COIN_SAVE_OFFLINE, "")); }
public async Task <EditPersonalDetailViewModel> LoadPersonalDetail(string userIdEnyc) { var userId = Convert.ToInt64(CryptoEngine.DecryptString(userIdEnyc)); var user = await _userAppService.GetAsync(new EntityDto <long>(userId)); var genderMasterId = (await _lookupAppService.GetAllLookUpMaster(null, "Gender")).Items.FirstOrDefault().Id; var genderSelectListItems = (await _lookupAppService.GetLookDetailComboboxItems(genderMasterId)).Items .Select(p => p.ToSelectListItem()) .ToList(); genderSelectListItems.Find(x => x.Value == user.Gender.ToString()).Selected = true; var personalDetailLKDId = (await _lookupAppService.GetAllLookDetail(null, LookUpDetailConst.PersonalDetail)).Items.FirstOrDefault().Id; var businessDocumentList = (await _documentAppService.GetAllBusinessDocuments(null, personalDetailLKDId, null)).Items.ToList(); foreach (var businessDoc in businessDocumentList) { if (businessDoc.BusinessEntityLKDId == personalDetailLKDId) { var photo = new List <BusinessDocumentAttachmentDto>(); photo.Add(_documentAppService.GetAllBusinessDocumentAttachments(null, businessDoc.Id, (int)userId).Result.Items.FirstOrDefault()); businessDoc.BusinessDocumentAttachmentDto = photo; } } var documentModel = new DocumentUploaderViewModel() { BusinessEntityId = userId, DocumentList = businessDocumentList }; return(new EditPersonalDetailViewModel { User = user, Gender = genderSelectListItems, ProfilePhoto = documentModel }); }
/// <summary> /// Adds the Wulka credentials internal. /// </summary> /// <param name="inst">The inst.</param> /// <param name="context">The p MS context.</param> /// <param name="credentials">The credentials.</param> protected virtual void AddWulkaCredentialsInternal(object inst, WulkaContext context, CredentialsBase credentials) { if (credentials != null) { switch (credentials.CredentialType) { case CredentialsTypeEnum.UserNamePassword: { var cred = credentials as UserNamePasswordCredentials; context.Add(WulkaContextKey.UserName, cred.UserName); context.Add(WulkaContextKey.PasswordEnc, CryptoEngine.Encrypt(cred.Password)); GetClt(inst).Endpoint.Behaviors.Add(new UserNameEndpointBehavior(new UserNamePasswordMessageInspector(cred.UserName, cred.Password))); break; } case CredentialsTypeEnum.UserNameSession: { var creds = credentials as UserNameSessionCredentials; context.Add(WulkaContextKey.UserName, creds.UserName); context.Add(WulkaContextKey.SessionId, creds.Session); GetClt(inst).Endpoint.Behaviors.Add(new UserNameEndpointBehavior(new UserNameSessionMessageInspector(creds.UserName, creds.Session))); break; } case CredentialsTypeEnum.Extended: { var crede = credentials as ExtendedCredentials; context.Add(WulkaContextKey.UserName, crede.UserName); context.Add(WulkaContextKey.SessionId, crede.Session); context.Add(WulkaContextKey.ServiceCode, crede.ServiceCode); GetClt(inst).Endpoint.Behaviors.Add(new UserNameEndpointBehavior(new ExtendedMessageInspector(crede.UserName, crede.FirstName, crede.LastName, crede.Session, crede.ServiceCode))); break; } } } }
public static PBCertificate SignCertificate(string name, PBKeyPair masterKeyPair, PBKeyPair keyPair) { var dsa = new CryptoEngine().ECLoad(masterKeyPair.PublicKey.PublicKey, masterKeyPair.PrivateKey); var cert = new PBCertificate { Name = name, PublicKey = keyPair.PublicKey.PublicKey }; /* Issue certificate Id */ cert.Id = masterKeyPair.IssuedCerts++; if (cert.Id > masterKeyPair.IssuedCerts) { throw new OverflowException("Ran out of issueable certificates"); } /* Prepare sign buffer */ var pubKey = keyPair.PublicKey.PublicKey.ToByteArray(); byte[] signBuff = new byte[pubKey.Length + sizeof(int)]; pubKey.CopyTo(signBuff, 0); for (int i = 0; i < sizeof(int); ++i) { signBuff[pubKey.Length + i] = (byte)((cert.Id >> (8 * i)) & 0xff); } var byteCert = dsa.SignData(signBuff, HashAlgorithmName.SHA256); cert.Signature = ByteString.CopyFrom(byteCert, 0, byteCert.Length); return(cert); }
private void btnActualizarClave_Click(object sender, EventArgs e) { try { IUsuariosDAL usuariosDAL = new UsuariosImplDAL(); CryptoEngine cryptoEngine = new CryptoEngine(); DialogResult dialogResult = MessageBox.Show("Seguro que desea cambiar su contrasena?", "Confirmación", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { usuarios.Contrasena = cryptoEngine.Encrypt(txtNuevaClave.Text); usuariosDAL.Update(usuarios); showInfo("Su clave de ingreso fue actualizada!"); } else if (dialogResult == DialogResult.No) { MessageBox.Show("Operacion Cancelada"); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } }
public IActionResult AddPhoto(Photos NewPhoto) { // int? y=HttpContext.Session.GetInt32("userid"); // if (y==null){ // return RedirectToAction("Index"); // } // bool Exists=dbContext.users.Any(e=>e.UserId==(int)y); // if(Exists==false){ // return RedirectToAction("Index"); // } if (ModelState.IsValid) { CryptoEngine Encrypter = new CryptoEngine(); NewPhoto.Desc = Encrypter.Encrypt(NewPhoto.Desc); NewPhoto.PhotoPath = Encrypter.Encrypt(NewPhoto.PhotoPath); // NewPhoto.CreatorId=Encrypter.Encrypt((string)NewPhoto.CreatorId); dbContext.photos.Add(NewPhoto); dbContext.SaveChanges(); return(RedirectToAction("Success")); } else { // ViewBag.UserId=(int)y; ViewBag.UserId = 5; List <Photos> Allphoto = dbContext.photos.ToList(); foreach (var photo in Allphoto) { CryptoEngine Encrypter = new CryptoEngine(); photo.Desc = Encrypter.Decrypt(photo.Desc); photo.PhotoPath = Encrypter.Decrypt(photo.PhotoPath); } ViewBag.AllPhotos = Allphoto; return(View("Success")); } }
public CDNContents(DirectoryInfo contentDir, CryptoEngine ce, SeedDatabase seedDb, Ticket ticket, bool verifyTmdHashes = true, bool ignoreMissingContents = false) { Load(contentDir, ce, seedDb, verifyTmdHashes, ignoreMissingContents); this.Cryptor.LoadTitleKeyFromTicket(ticket); }
public IActionResult Success() { // Get; Chilkat.PublicKey pubKey = new Chilkat.PublicKey(); bool success = pubKey.LoadFromFile("qa_data/pem/rsa_public.pem"); Chilkat.Jwt jwt = new Chilkat.Jwt(); string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"; // First verify the signature. bool sigVerified = jwt.VerifyJwtPk(token, pubKey); Console.WriteLine("verified: " + Convert.ToString(sigVerified)); int leeway = 60; bool bTimeValid = jwt.IsTimeValid(token, leeway); Console.WriteLine("time constraints valid: " + Convert.ToString(bTimeValid)); // Now let's recover the original claims JSON (the payload). string payload = jwt.GetPayload(token); // The payload will likely be in compact form: Console.WriteLine(payload); // We can format for human viewing by loading it into Chilkat's JSON object // and emit. Chilkat.JsonObject json = new Chilkat.JsonObject(); success = json.Load(payload); json.EmitCompact = false; Console.WriteLine(json.Emit()); // We can recover the original JOSE header in the same way: string joseHeader = jwt.GetHeader(token); // The payload will likely be in compact form: Console.WriteLine(joseHeader); // We can format for human viewing by loading it into Chilkat's JSON object // and emit. success = json.Load(joseHeader); json.EmitCompact = false; Console.WriteLine(json.Emit()); // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // JwtDecode Test1=new JwtDecode(); // var x=Test1.GetName("eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJJU1MiLCJzY29wZSI6Imh0dHBzOi8vbGFyaW0uZG5zY2UuZG91YW5lL2NpZWxzZXJ2aWNlL3dzIiwiYXVkIjoiaHR0cHM6Ly9kb3VhbmUuZmluYW5jZXMuZ291di5mci9vYXV0aDIvdjEiLCJpYXQiOiJcL0RhdGUoMTQ2ODM2MjU5Mzc4NClcLyJ9"); // // var x= Test1.TestJwtSecurityTokenHandler("CfDJ8JJa5feBk79Hq8LMUg4HHXfoWI4CgZu7vOhujmhfwtEi7rYOFiVzoUBGec1HXm2aOD69Q8AEqARSHvCmyUJAw_opdjsSfIhJS3v-Dbe0MsLw8QvdMMOuNeqEZvB93lH03TM62plyHreR5_D_G7kkvJvg5vaMUOd_GgZMRFkLMlrrcrPM8l2jOVOgD1r4WIEr0oCm9KB_T0Bt5vZ37CnPJJt7r6_yVM5yuAZU3aI92S5EYodHHhVe_OjRDqg1nALC2a2KzHbGnBKfO-7FbyocHU0QRdkl5F5VBRJVsHHNMOZJ3jUhtfflSggP_b5Imk0qNcs39rEUUC8ajLUv3zaFxaCTX6yyj-kqYg2JKYFSw7OXQZl_XiNlB2mY9cdb1xjjpbLM4SxWzB8k1rMMkXETK1ZLFpu9DUiDgoKmTqICaduGdETRjvBsVA4fa2H2ztmNWCEL7huxL41rXjYb4jXSosJ6wLpjFp2j9f1oLymvPVKeeZ_aKaxFHIJF_dUnG-nIuPUtCSAexfp4NLiWaR3ctWvQ4NKeRv-UwaBoSrSt_gSJ3QAqafrmu-vTdwIek6xPb9AWTUAC7TWCgIHgz3pQqJKnPteVWgXXsPSizg2FlcWc5kYTa0PV2kf8g7JYKHPbYPkbjDKUAiYoOG4AkFdV5z6febxVZiC4XQZLM3tZHCBUdTaFHJOwUSOX8aWna-BJBA"); // // var x= Test1.TestJwtSecurityTokenHandler(); // System.Console.WriteLine(x); // var jwt = "eyJhbGciOiJQUzM4NCIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4.cu22eBqkYDKgIlTpzDXGvaFfz6WGoz7fUDcfT0kkOy42miAh2qyBzk1xEsnk2IpN6-tPid6VrklHkqsGqDqHCdP6O8TTB5dDDItllVo6_1OLPpcbUrhiUSMxbbXUvdvWXzg-UD8biiReQFlfz28zGWVsdiNAUf8ZnyPEgVFn442ZdNqiVJRmBqrYRXe8P_ijQ7p8Vdz0TTrxUeT3lm8d9shnr2lfJT8ImUjvAA2Xez2Mlp8cBE5awDzT0qI0n6uiP1aCN_2_jLAeQTlqRHtfa64QQSUmFAAjVKPbByi7xho0uTOcbH510a6GYmJUAfmWjwZ6oD4ifKo8DYM-X72Eaw"; // var handler = new JwtSecurityTokenHandler(); // var token = handler.ReadJwtToken(jwt); // System.Console.WriteLine(token); System.Console.WriteLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); // int? y=HttpContext.Session.GetInt32("userid"); CryptoEngine Encrypter = new CryptoEngine(); // if (y==null){ // return RedirectToAction("Index"); // } // bool Exists=dbContext.users.Any(e=>e.UserId==(int)y); // if(Exists==false){ // return RedirectToAction("Index"); // } // ViewBag.UserId=(int)y; ViewBag.UserId = 5; List <Photos> Allphoto = dbContext.photos.ToList(); foreach (var photo in Allphoto) { photo.Desc = Encrypter.Decrypt(photo.Desc); photo.PhotoPath = Encrypter.Decrypt(photo.PhotoPath); } ViewBag.AllPhotos = Allphoto; return(View()); }
public NCCH(FileStream ncchStream, CryptoEngine ce = null, SeedDatabase seedDb = null) { this.NCCHMemoryMappedFile = Tools.LoadFileMapped(ncchStream); Load(ce, seedDb); }
private void btnModificaUsuario_Click(object sender, EventArgs e) { try { String nombre = this.txtNombreA.Text; String apellido = this.txtApellido1A.Text; String cedula = txtCedulaA.Text; String contrasena = aux.Encrypt(txtContrasenaA.Text); String correo = txtCorreoA.Text; CryptoEngine cryptoEngine = new CryptoEngine(); // Valida que los campos requeridos tengan valores (Nombre, Apellido y/o Cedula) if (nombre.Length <= 0 || apellido.Length <= 0 || cedula.Length <= 0 || correo.Length <= 0 || contrasena.Length <= 0) { this.errorLbl.Visible = true; } //Valida que el campo de Cedula lleve solo numeros else if (Regex.IsMatch(cedula, @"^\d+$") == false) { this.lblErrorCed.Visible = true; this.lblErrorApellido.Visible = false; this.lblErrorNombre.Visible = false; this.lblErrorCorreo.Visible = false; } //Valida que el nombre solo lleve letras else if (Regex.IsMatch(nombre, @"[a-zA-Z]+") == false) { this.lblErrorCed.Visible = false; this.lblErrorApellido.Visible = false; this.lblErrorNombre.Visible = true; this.lblErrorCorreo.Visible = false; } //Valida que el apellido solo lleve letras else if (Regex.IsMatch(apellido, @"[a-zA-Z]+") == false) { this.lblErrorCed.Visible = false; this.lblErrorApellido.Visible = false; this.lblErrorNombre.Visible = true; this.lblErrorCorreo.Visible = false; } else if (!validarCorreo()) { this.lblErrorCed.Visible = false; this.lblErrorApellido.Visible = false; this.lblErrorNombre.Visible = false; this.lblErrorCorreo.Visible = true; } // Si estan esas validaciones, se crea el objeto a insertar en la Base de Datos else { this.errorLbl.Visible = false; this.lblErrorCed.Visible = false; this.lblErrorNombre.Visible = false; this.lblErrorApellido.Visible = false; this.lblErrorCorreo.Visible = false; //Usuario = new Usuarios(); Usuario.Nombre = txtNombreA.Text; Usuario.Apellido = txtApellido1A.Text; Usuario.Telefono = txtTelefonoA.Text; Usuario.Cedula = int.Parse(txtCedulaA.Text); Usuario.Correo = txtCorreoA.Text; Usuario.Direccion = txtDireccionA.Text; Usuario.RolUsuario = (int)cmbBoxRolA.SelectedValue; Usuario.RolUsuarios = (RolUsuarios)cmbBoxRolA.SelectedItem; Usuario.Contrasena = aux.Encrypt(txtContrasenaA.Text); //Si la contrasena en el txtContrasenaA es igual a la del usuario en bd /*if (aux.Decrypt(txtContrasenaA.Text).Equals(aux.Decrypt(usuariosDAL.Getcorreo(Usuario.Correo).Contrasena))) * { * //mandarla como esta en el cuadro, ahi ya esta encriptada. * * Usuario.Contrasena = txtContrasenaA.Text; * } * else if (txtContrasenaA.Text.Equals(aux.Decrypt(usuariosDAL.Getcorreo(Usuario.Correo).Contrasena))) * { * Usuario.Contrasena = aux.Encrypt(txtContrasenaA.Text); * }else * { * //Si no, significa que cambio. Entonces aplicamos encripcion y la guardamos. * Usuario.Contrasena = aux.Encrypt(txtContrasenaA.Text); * }*/ usuariosDAL.Update(Usuario); string detalleBitacora = "Se actualizaron los datos del usuario: " + Usuario.Nombre + " " + Usuario.Apellido; bitacora.DetalleBitacora = detalleBitacora; bitacora.IdUsuario = ValoresAplicacion.idUsuario; bitacoraDAL.Add(bitacora); MessageBox.Show("Usuario actualizado"); this.Hide(); } } catch (Exception ex) { MessageBox.Show("Ha ocurrido un error. Revise que la cédula y el correo no estén siendo usados por otro usuario"); } }
private void btnAgregaUsuario_Click(object sender, EventArgs e) { try { String nombre = this.txtNombre.Text; String apellido = this.txtApellido1.Text; String cedula = txtCedula.Text; String contrasena = aux.Encrypt(txtContrasena.Text); String correo = txtCorreo.Text; CryptoEngine cryptoEngine = new CryptoEngine(); // Valida que los campos requeridos tengan valores (nombre, apellido, contraseña, cédula y correo) if (nombre.Length <= 0 || apellido.Length <= 0 || cedula.Length <= 0 || correo.Length <= 0 || contrasena.Length <= 0) { this.errorLbl.Visible = true; } //Valida que el campo de Cedula lleve solo numeros else if (Regex.IsMatch(cedula, @"^\d+$") == false) { this.lblErrorCed.Visible = true; } //Valida que el nombre solo lleve letras else if (Regex.IsMatch(nombre, @"[a-zA-Z]+") == false) { this.lblErrorNombre.Visible = true; } //Valida que el apellido solo lleve letras else if (Regex.IsMatch(apellido, @"[a-zA-Z]+") == false) { this.lblErrorApellido.Visible = true; } else if (!validarCorreo()) { this.lblErrorCorreo.Visible = true; } // Si estan esas validaciones, se crea el objeto a insertar en la Base de Datos else { this.errorLbl.Visible = false; this.lblErrorCed.Visible = false; this.lblErrorNombre.Visible = false; this.lblErrorApellido.Visible = false; this.lblErrorCorreo.Visible = false; Usuario = new Usuarios(); Usuario.Nombre = txtNombre.Text; Usuario.Apellido = txtApellido1.Text; Usuario.Telefono = txtTelefono.Text; Usuario.Cedula = int.Parse(txtCedula.Text); Usuario.Correo = txtCorreo.Text; Usuario.Direccion = txtDireccion.Text; Usuario.RolUsuario = (int)cmbBoxRol.SelectedValue; Usuario.RolUsuarios = (RolUsuarios)cmbBoxRol.SelectedItem; Usuario.Contrasena = cryptoEngine.Encrypt(txtContrasena.Text); Usuario.FechaCreacion = DateTime.Now; Usuario.EstadoUsuario = 1; // Estado default al agregar un usuario es 1 de Activo usuarioDAL.Add(Usuario); string detalleBitacora = "Se insertó el usuario: " + Usuario.Nombre + " " + Usuario.Apellido; bitacora.DetalleBitacora = detalleBitacora; bitacora.IdUsuario = ValoresAplicacion.idUsuario; bitacoraDAL.Add(bitacora); MessageBox.Show("Usuario agregado"); this.Hide(); } } catch (Exception ex) { MessageBox.Show("Ha ocurrido un error. Revise que la cédula y el correo no estén siendo usados por otro usuario"); } }
private static void Main(string[] args) { ushort port = 8080; if (args.Length == 1) { try { port = (ushort)int.Parse(args[0]); } catch (Exception e) { Console.WriteLine("Invalid port number " + e); return; } } /* Something might happen. Just go on... */ while (true) { try { /* Load certificate */ CryptoEngine.GetInstance().loadCertificate(Config <string> .GetInstance()["Certificate"]); /* Add preconfigured partners */ foreach (var partner in Config <string[]> .GetInstance()["PARTNERS"]) { if (partner == string.Empty) { continue; } PartnersEngine.AddPartner(partner); } Console.WriteLine("Node " + CryptoEngine.GetInstance().Certificate.Cert.Id + " Running on port " + port); /* Request joining the network and load current DB from network */ PartnersEngine.PartnerJoinRequest(new JSON.PartnerSyncRequestJoin { Address = Config <string> .GetInstance()["PUBLIC_ADDRESS"] }); var server = new AsyncHTTPServer(port); server.AddHandler("/testQuery", new TestQueryHandler()); server.AddHandler("/createUser", new CreateUserHandler()); server.AddHandler("/createQueue", new CreateQueueHandler()); server.AddHandler("/partnerSync", new PartnerSyncHandler()); server.AddHandler("/login", new LoginHandler()); server.AddHandler("/queue", new QueueHandler()); server.Start(); } catch (HttpListenerException e) { Console.WriteLine("External port diallowed. Please run as Administrator (" + e.Message + ")"); Console.WriteLine("\tnetsh http add urlacl url=http://+:" + port + "/ user=\"" + Environment.UserName + "\""); } catch (Exception e) { Console.WriteLine(e); Console.WriteLine(e.Message); } } }
public JsonResult GetRequestsHistory([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel, String RequestId) { string userkey = ConfigurationManager.AppSettings["userkey"]; string uid = ConfigurationManager.AppSettings["uid"]; string LoginUser = (string)Session["LoginSAPID"]; string _access_key = ConfigurationManager.AppSettings["Salt"]; try { Employer.Employer employer = new Employer.Employer(); string dRequestId = CryptoEngine.DecryptString(RequestId, _access_key); string request_ID = dRequestId.Replace(' ', '+'); DataTable dt = employer.FetchAssignmentHistory(dRequestId, userkey, uid); dt.TableName = "RequestsHistory"; dt.Columns.ToString(); List <RequestsHistory> requestsHistory = new List <RequestsHistory>(); int startRec = requestModel.Start; int pageSize = requestModel.Length; List <RequestsHistory> requestCount = (from DataRow dr in dt.Rows select new RequestsHistory() { RequestID = dr["RequestID"].ToString() }).ToList(); requestsHistory = (from DataRow dr in dt.Rows orderby dr["AssignDate"] descending select new RequestsHistory() { RequestID = dr["RequestID"].ToString(), HistoryID = dr["HistoryID"].ToString(), Comment = dr["Comment"].ToString(), Assignee = dr["Assignee"].ToString(), Assignor = dr["Assignor"].ToString(), AssignDate = Convert.ToDateTime(dr["AssignDate"]).ToString("dd-MMM-yyyy hh:mm"), AssignStatus = dr["AssignStatus"].ToString() }).Skip(startRec).Take(pageSize).ToList(); var totalCount = requestCount.Count(); var filteredCount = requestsHistory.Count(); if (requestModel.Search.Value != string.Empty) { var value = requestModel.Search.Value.Trim(); requestCount = (from DataRow dr in dt.Rows where dr["RequestID"].ToString().Contains(value) || dr["Assignee"].ToString().Contains(value) || dr["Assignor"].ToString().Contains(value) || Convert.ToDateTime(dr["AssignDate"]).ToString("dd-MMM-yyyy hh:mm").Contains(value) || dr["Assignee"].ToString().Contains(value) || dr["AssignStatus"].ToString().Contains(value) select new RequestsHistory() { RequestID = dr["RequestID"].ToString() }).ToList(); requestsHistory = (from DataRow dr in dt.Rows orderby dr["AssignDate"] descending where dr["RequestID"].ToString().Contains(value) || dr["Assignee"].ToString().Contains(value) || dr["Assignor"].ToString().Contains(value) || Convert.ToDateTime(dr["AssignDate"]).ToString("dd-MMM-yyyy hh:mm").Contains(value) || dr["Assignee"].ToString().Contains(value) || dr["AssignStatus"].ToString().Contains(value) select new RequestsHistory() { RequestID = dr["RequestID"].ToString(), HistoryID = dr["HistoryID"].ToString(), Comment = dr["Comment"].ToString(), Assignee = dr["Assignee"].ToString(), Assignor = dr["Assignor"].ToString(), AssignDate = Convert.ToDateTime(dr["AssignDate"]).ToString("dd-MMM-yyyy hh:mm"), AssignStatus = dr["AssignStatus"].ToString() }).Skip(startRec).Take(pageSize).ToList(); totalCount = requestCount.Count(); filteredCount = requestsHistory.Count(); } var sortedColumns = requestModel.Columns.GetSortedColumns(); var orderByString = String.Empty; foreach (var column in sortedColumns) { orderByString += orderByString != String.Empty ? "," : ""; orderByString += (column.Data) + (column.SortDirection == Column.OrderDirection.Ascendant ? " asc" : " desc"); } var data = requestsHistory.Select(emList => new { RequestID = emList.RequestID, HistoryID = emList.HistoryID, Comment = emList.Comment, Assignee = emList.Assignee, Assignor = emList.Assignor, AssignDate = emList.AssignDate, AssignStatus = emList.AssignStatus }).OrderBy(orderByString == string.Empty ? "ID asc" : orderByString).ToList(); return(Json(new DataTablesResponse(requestModel.Draw, data, totalCount, totalCount), JsonRequestBehavior.AllowGet)); } catch (Exception ex) { LogError logerror = new LogError(); logerror.ErrorLog("", LoginUser, "", "Requests/GetRequests", "Requests", "GetRequests", "FetchIncidents Error", ex.Message.ToString(), 0); return(Json(new { data = "Error has occured" }, JsonRequestBehavior.AllowGet)); } }
public async Task <IViewComponentResult> InvokeAsync(ViewComponentVModel model) { if (!model.SearchModel.UserId.HasValue && !string.IsNullOrWhiteSpace(model.SearchModel.UserIdEnyc)) { model.SearchModel.UserId = (!string.IsNullOrWhiteSpace(model.SearchModel.UserIdEnyc)) ? (int?)Convert.ToInt32(CryptoEngine.DecryptString(model.SearchModel.UserIdEnyc)) : null; } var photoList = _photoTrackingAppService.GetAllPhotoTrackingPagedResult(model.SearchModel, model.BusinessEntityId); var result = new PhotoTrackingViewModel() { DocumentList = photoList, DocumentType = (model.SearchModel != null) ? model.SearchModel.DocumentType : EnumDocumentType.FrontPose }; ViewBag.IsAdminLoggedIn = _userManager.IsAdminUser(AbpSession.UserId.Value); string view = string.IsNullOrEmpty(model.ViewName) ? "_Default" : model.ViewName; return(await Task.FromResult((IViewComponentResult)View(view, result))); }
public JsonResult GetBatchDetails([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel, String batchId, String addressId) { string LoginUser = (string)Session["LoginSAPID"]; string userkey = ConfigurationManager.AppSettings["userkey"]; string uid = ConfigurationManager.AppSettings["uid"]; string CompanyName = (string)Session["CompanyName"]; string WebUserID = (string)Session["WebUserID"]; string EMPLOYER_ID = (string)Session["EMPLOYER_ID"]; string _access_key = ConfigurationManager.AppSettings["Salt"]; try { Employer.Employer employer = new Employer.Employer(); string dBatchId = CryptoEngine.DecryptString(batchId, _access_key); string dAddressId = CryptoEngine.DecryptString(addressId, _access_key); DataTable dt = employer.FetchPINsBatch(CompanyName, EMPLOYER_ID, dBatchId, dAddressId, userkey, uid); dt.TableName = "PinsBatch"; dt.Columns.ToString(); List <CompanyEmployee> pins = new List <CompanyEmployee>(); int startRec = requestModel.Start; int pageSize = requestModel.Length; List <CompanyEmployee> pinCount = (from DataRow dr in dt.Rows select new CompanyEmployee() { PIN = dr["P_I_N"].ToString(), }).ToList(); pins = (from DataRow dr in dt.Rows select new CompanyEmployee() { PIN = dr["P_I_N"].ToString(), FirstName = dr["First Name"].ToString(), LastName = dr["Last Name"].ToString(), MiddleName = dr["Middle Names"].ToString() }).Skip(startRec).Take(pageSize).ToList(); var totalCount = pinCount.Count(); var filteredCount = pins.Count(); if (requestModel.Search.Value != string.Empty) { var value = requestModel.Search.Value.ToLower().Trim(); pinCount = (from DataRow dr in dt.Rows where dr["P_I_N"].ToString().ToLower().Contains(value) || dr["First Name"].ToString().ToLower().Contains(value) || dr["Last Name"].ToString().ToLower().Contains(value) || dr["Middle Names"].ToString().ToLower().Contains(value) select new CompanyEmployee() { PIN = dr["Category ID"].ToString(), }).ToList(); pins = (from DataRow dr in dt.Rows where dr["P_I_N"].ToString().ToLower().Contains(value) || dr["First Name"].ToString().ToLower().Contains(value) || dr["Last Name"].ToString().ToLower().Contains(value) || dr["Middle Names"].ToString().ToLower().Contains(value) select new CompanyEmployee() { PIN = dr["P_I_N"].ToString(), FirstName = dr["First Name"].ToString(), LastName = dr["Last Name"].ToString(), MiddleName = dr["Middle Names"].ToString() }).Skip(startRec).Take(pageSize).ToList(); totalCount = pinCount.Count(); filteredCount = pins.Count(); } var sortedColumns = requestModel.Columns.GetSortedColumns(); var orderByString = String.Empty; foreach (var column in sortedColumns) { orderByString += orderByString != String.Empty ? "," : ""; orderByString += (column.Data) + (column.SortDirection == Column.OrderDirection.Ascendant ? " asc" : " desc"); } var data = pins.Select(emList => new { PIN = emList.PIN, FirstName = emList.FirstName, LastName = emList.LastName, MiddleName = emList.MiddleName }).ToList(); return(Json(new DataTablesResponse(requestModel.Draw, data, totalCount, totalCount), JsonRequestBehavior.AllowGet)); } catch (Exception ex) { LogError logerror = new LogError(); logerror.ErrorLog("", LoginUser, "", "StatementOptions/GetBatchDetails", "StatementOptions", "GetBatchDetails", "FetchPINsBatch Error", ex.Message.ToString(), 0); return(Json(new { data = "Error has occured" }, JsonRequestBehavior.AllowGet)); } }
public virtual int sceNpDrmRenameCheck(PspString fileName) { CryptoEngine crypto = new CryptoEngine(); int result = 0; if (!NpDrmKeyStatus) { result = SceKernelErrors.ERROR_NPDRM_NO_K_LICENSEE_SET; } else { try { string pcfilename = Modules.IoFileMgrForUserModule.getDeviceFilePath(fileName.String); SeekableRandomFile file = new SeekableRandomFile(pcfilename, "r"); string[] name = pcfilename.Split("/", true); string fName = name[name.Length - 1]; for (int i = 0; i < name.Length; i++) { if (name[i].ToUpper().Contains("EDAT")) { fName = name[i]; } } // The file must contain a valid PSPEDAT header. if (file.Length() < 0x80) { // Test if we're using already decrypted DLC. // Discard the error in this situatuion. if (!DisableDLCStatus) { Console.WriteLine("sceNpDrmRenameCheck: invalid file size"); result = SceKernelErrors.ERROR_NPDRM_INVALID_FILE; } file.Dispose(); } else { // Setup the buffers. sbyte[] inBuf = new sbyte[0x80]; sbyte[] srcData = new sbyte[0x30]; sbyte[] srcHash = new sbyte[0x10]; // Read the header. file.readFully(inBuf); file.Dispose(); // The data seed is stored at offset 0x10 of the PSPEDAT header. Array.Copy(inBuf, 0x10, srcData, 0, 0x30); // The hash to compare is stored at offset 0x40 of the PSPEDAT header. Array.Copy(inBuf, 0x40, srcHash, 0, 0x10); // If the CryptoEngine fails to find a match, then the file has been renamed. if (!crypto.PGDEngine.CheckEDATRenameKey(fName.GetBytes(), srcHash, srcData)) { if (!DisableDLCStatus) { result = SceKernelErrors.ERROR_NPDRM_NO_FILENAME_MATCH; Console.WriteLine("sceNpDrmRenameCheck: the file has been renamed"); } } } } catch (FileNotFoundException e) { result = SceKernelErrors.ERROR_NPDRM_INVALID_FILE; //if (log.DebugEnabled) { Console.WriteLine(string.Format("sceNpDrmRenameCheck: file '{0}' not found: {1}", fileName.String, e.ToString())); } } catch (Exception e) { Console.WriteLine("sceNpDrmRenameCheck", e); } } return(result); }
public PBPFileSectorDevice(RandomAccessFile fileAccess) : base(fileAccess) { try { int magic = endianSwap32(fileAccess.readInt()); int version = endianSwap32(fileAccess.readInt()); offsetParamSFO = endianSwap32(fileAccess.readInt()); offsetIcon0 = endianSwap32(fileAccess.readInt()); offsetIcon1 = endianSwap32(fileAccess.readInt()); offsetPic0 = endianSwap32(fileAccess.readInt()); offsetPic1 = endianSwap32(fileAccess.readInt()); offsetSnd0 = endianSwap32(fileAccess.readInt()); offsetPspData = endianSwap32(fileAccess.readInt()); offsetPsarData = endianSwap32(fileAccess.readInt()); if (magic != 0x50425000) { throw new IOException(string.Format("Invalid PBP header 0x{0:X8}", magic)); } if (version != 0x00010000 && version != 0x00000100 && version != 0x00010001) { throw new IOException(string.Format("Invalid PBP version 0x{0:X8}", version)); } fileAccess.seek(offsetPsarData); sbyte[] header = new sbyte[256]; int readSize = fileAccess.read(header); if (readSize != header.Length) { int psarDataLength = (int)(fileAccess.Length() - offsetPsarData); if (psarDataLength != 0 && psarDataLength != 16) { throw new IOException(string.Format("Invalid PBP header")); } } else if (header[0] == (sbyte)'N' && header[1] == (sbyte)'P' && header[2] == (sbyte)'U' && header[3] == (sbyte)'M' && header[4] == (sbyte)'D' && header[5] == (sbyte)'I' && header[6] == (sbyte)'M' && header[7] == (sbyte)'G') { CryptoEngine cryptoEngine = new CryptoEngine(); amctrl = cryptoEngine.AMCTRLEngine; AMCTRL.BBMac_Ctx macContext = new AMCTRL.BBMac_Ctx(); AMCTRL.BBCipher_Ctx cipherContext = new AMCTRL.BBCipher_Ctx(); // getKey amctrl.hleDrmBBMacInit(macContext, 3); amctrl.hleDrmBBMacUpdate(macContext, header, 0xC0); sbyte[] macKeyC0 = new sbyte[16]; Array.Copy(header, 0xC0, macKeyC0, 0, macKeyC0.Length); vkey = amctrl.GetKeyFromBBMac(macContext, macKeyC0); // decrypt NP header sbyte[] cipherData = new sbyte[0x60]; Array.Copy(header, 0x40, cipherData, 0, cipherData.Length); Array.Copy(header, 0xA0, hkey, 0, hkey.Length); amctrl.hleDrmBBCipherInit(cipherContext, 1, 2, hkey, vkey); amctrl.hleDrmBBCipherUpdate(cipherContext, cipherData, cipherData.Length); amctrl.hleDrmBBCipherFinal(cipherContext); int lbaStart = Utilities.readUnaligned32(cipherData, 0x14); int lbaEnd = Utilities.readUnaligned32(cipherData, 0x24); numSectors = lbaEnd + 1; lbaSize = numSectors - lbaStart; blockLBAs = Utilities.readUnaligned32(header, 0x0C); blockSize = blockLBAs * ISectorDevice_Fields.sectorLength; numBlocks = (lbaSize + blockLBAs - 1) / blockLBAs; blockBuffer = new sbyte[blockSize]; tempBuffer = new sbyte[blockSize]; table = new TableInfo[numBlocks]; int tableOffset = Utilities.readUnaligned32(cipherData, 0x2C); fileAccess.seek(offsetPsarData + tableOffset); sbyte[] tableBytes = new sbyte[numBlocks * 32]; readSize = fileAccess.read(tableBytes); if (readSize != tableBytes.Length) { Console.WriteLine(string.Format("Could not read table with size {0:D} (readSize={1:D})", tableBytes.Length, readSize)); } IntBuffer tableInts = ByteBuffer.wrap(tableBytes).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); for (int i = 0; i < numBlocks; i++) { int p0 = tableInts.get(); int p1 = tableInts.get(); int p2 = tableInts.get(); int p3 = tableInts.get(); int p4 = tableInts.get(); int p5 = tableInts.get(); int p6 = tableInts.get(); int p7 = tableInts.get(); int k0 = p0 ^ p1; int k1 = p1 ^ p2; int k2 = p0 ^ p3; int k3 = p2 ^ p3; TableInfo tableInfo = new TableInfo(); Array.Copy(tableBytes, i * 32, tableInfo.mac, 0, tableInfo.mac.Length); tableInfo.offset = p4 ^ k3; tableInfo.size = p5 ^ k1; tableInfo.flags = p6 ^ k2; tableInfo.unknown = p7 ^ k0; table[i] = tableInfo; } currentBlock = -1; } } catch (IOException e) { Console.WriteLine("Reading PBP", e); } }
public ActionResult ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = UserRepository.Get(model.Email); if (user == null) { ModelState.AddModelError("", "The user does not exist."); return(View()); } else if (!(UserRepository.IsActive(model.Email))) { ModelState.AddModelError("", "The user is not confirmed."); return(View()); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = UserManager.GeneratePasswordResetTokenAsync(user.UserID.ToString()).Result; var callbackUrl = Url.Action("ResetPassword", "Account", new { token = CryptoEngine.Encrypt(user.UserID.ToStringSafe()) }, protocol: Request.Url.Scheme); MailHelper.MailSend(new MailMessageHelper { Body = "Please reset your password by copy past link in browser : " + callbackUrl, Subject = "Reset Password", To = user.Email }); return(RedirectToAction("ForgotPasswordConfirmation", "Account")); } // If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult Register(RegisterViewModel model, HttpPostedFileBase imagefile) { if (ModelState.IsValid) { // TODO : Check for file upload filter. VTSUSER objUser = new VTSUSER(); objUser.Address = model.Address; objUser.City = model.City; objUser.CreatedOn = DateTime.Now; if (!string.IsNullOrEmpty(model.DOB)) { try { objUser.DOB = Convert.ToDateTime(model.DOB); } catch { ModelState.AddModelError("DOB", "Invalid date of birth"); return(View(model)); } } objUser.Email = model.Email; objUser.FirstName = model.FirstName; objUser.IsActive = false; objUser.IsAdmin = false; objUser.LastName = model.LastName; objUser.Password = model.Password; objUser.Phone = model.Phone; objUser.Photo = model.Photo; objUser.Pincode = model.Pin; objUser.Sex = Convert.ToBoolean(model.Sex.ToGenderConversion()); objUser.State = model.State; objUser.Photo = UploadFileDeleteExisting(imagefile, objUser.Email.GetName()); if (UserRepository.Get(objUser.Email) != null) { AddErrors("Email already exists"); return(View(model)); } var createdUser = UserRepository.Create(objUser); if (createdUser != null) { // Send an email with this link var callbackUrl = Url.Action("ConfirmEmail", "Account", new { token = CryptoEngine.Encrypt(createdUser.UserID.ToString()) }, protocol: Request.Url.Scheme); MailHelper.MailSend (new MailMessageHelper { Body = "Please confirm your email by copy past link in browser : " + callbackUrl + "", Subject = "Confirmation Mail", To = createdUser.Email }); return(RedirectToAction("RegistrationComplete", "Account")); } else { AddErrors(VTSConstants.Error); } } // If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult AddComisionUser(ComisionViewModel model) { List <SelectListItem> regionesTemp; using (SaludOcupacionalEntities db = new SaludOcupacionalEntities()) { regionesTemp = (from d in db.Region orderby d.numeroRegion select new SelectListItem { Value = d.idRegion.ToString(), Text = d.nombreRegion, }).ToList(); } model.listaDeRegiones = new SelectList(regionesTemp, "Value", "Text"); if (!ModelState.IsValid) { return(View(model)); } using (var db = new SaludOcupacionalEntities()) { // Revisa si el centro de trabajo existe en el sistema CentroDeTrabajo oCentroDeTrabajo = db.CentroDeTrabajo.Find(model.idCentroDeTrabajo); if (oCentroDeTrabajo == null) { ModelState.AddModelError("nombreCentroDeTrabajo", "El Centro de Trabajo no Existe"); return(View(model)); } // Revisa si el centro de trabajo ya tiene una comisión asignada. Sólo puede haber una comisión por centro de trabajo int valido = (from d in db.Comision join ct in db.CentroDeTrabajo on d.idCentroDeTrabajo equals ct.idCentroDeTrabajo where ct.idCentroDeTrabajo == model.idCentroDeTrabajo select d.idCentroDeTrabajo).Count(); if (valido != 0) { ModelState.AddModelError("nombreCentroDeTrabajo", "El Centro de Trabajo ya está asignado a otra comisión"); return(View(model)); } /* Crea el nombre de la comisión de manera predeterminada. Ej: "comisionhatillo" para el centro de trabajo "Hatillo" * Quita los espacios en blanco*/ string nombreComision = String.Concat(oCentroDeTrabajo.nombreCentroDeTrabajo.Where(c => !Char.IsWhiteSpace(c))); nombreComision = "comision" + nombreComision; /* Revisa si el nombre de la comisión ya existe. Esto es para cuentas duplicadas, centros de trabajo que se llamen igual * pero pertenezcan a diferentes regiones, lo cual es válido*/ var usernameExists = db.Cuenta.Any(x => x.nombre == nombreComision); if (usernameExists) { // En caso de repetirse, añade el número de región. Ej "comisionsanrafael2" para San Rafael de Alajuela nombreComision = nombreComision + oCentroDeTrabajo.Region.numeroRegion.ToString(); } // Quita mayúsculas y guiones del nombre nombreComision = nombreComision.ToLower(); nombreComision = Regex.Replace(nombreComision.Normalize(NormalizationForm.FormD), @"[^a-zA-z0-9 ]+", ""); // La contraseña se genera mediante una función de C#, que recibe la cantidad de caracteres y el número de caracteres no alfanuméricos string contrasena = Membership.GeneratePassword(10, 1); ViewBag.nombre = nombreComision; ViewBag.contra = contrasena; // Se encripta la contraseña contrasena = CryptoEngine.Encrypt(contrasena); Cuenta oCuenta = new Cuenta(); oCuenta.nombre = nombreComision; oCuenta.contrasena = contrasena; oCuenta.rol = 1; // Rol 1 significa "usuario" db.Cuenta.Add(oCuenta); Comision oComision = new Comision(); oComision.idCentroDeTrabajo = model.idCentroDeTrabajo; oComision.idCuenta = oCuenta.idCuenta; db.Comision.Add(oComision); db.SaveChanges(); } return(View(model)); }
public CDNContents(DirectoryInfo contentDir, CryptoEngine ce, SeedDatabase seedDb, byte[] titleKey, bool verifyTmdHashes = true, bool ignoreMissingContents = false) { Load(contentDir, ce, seedDb, verifyTmdHashes, ignoreMissingContents); this.Cryptor.SetNormalKey((int)Keyslot.DecryptedTitleKey, titleKey); }
public void Serve(HttpListenerRequest request, HttpListenerResponse response, Url url) { var partnerSyncRequest = JSONSerializer <PartnerSyncMessage> .Deserialize(request.InputStream); var jsonResponse = new BooleanResponse { Success = false }; /* Validate incoming certificate */ try { if (!CryptoEngine.GetInstance().verifyCertificate(partnerSyncRequest.key, partnerSyncRequest.certId, partnerSyncRequest.cert) .VerifyData(partnerSyncRequest.data, partnerSyncRequest.signature, HashAlgorithmName.SHA256)) { throw new CryptographicException("Data verification failed"); } /* Parse action */ var partnerSyncRequestData = JSONSerializer <PartnerSyncMessageData> .Deserialize(partnerSyncRequest.data); /* Figure out which message type need to be handled */ switch (partnerSyncRequestData.MessageType) { case PartnerSyncMessageType.PARTNER_JOIN: { /* Parse join request */ var partnerJoinRequest = JSONSerializer <PartnerSyncRequestJoin> .Deserialize(partnerSyncRequestData.Data); /* Add to partners */ PartnersEngine.AddPartner(partnerJoinRequest.Address); /* Create a DB Dump object */ var partnerDBDump = new PartnerSyncResponseDBDump { Partners = PartnersEngine.Partners.ToArray() }; /* Dump te DB */ var dbFile = File.Open(Config <string> .GetInstance()["DB_Filename"], FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using (var reader = new BinaryReader(dbFile)) { /* Hopefully DB will not be larger than 2GB */ partnerDBDump.DBDump = reader.ReadBytes((int)dbFile.Length); } JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(partnerDBDump), response.OutputStream); break; } case PartnerSyncMessageType.USER_CREATE: { /* Parse register request */ var userRegisterRequest = JSONSerializer <PartnerSyncUserCreate> .Deserialize(partnerSyncRequestData.Data); /* Update here */ UserEngine.RegisterUser(partnerSyncRequest.certId, userRegisterRequest.Id, Encoding.ASCII.GetBytes(userRegisterRequest.Key)); jsonResponse.Success = true; jsonResponse.Message = "Success"; JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(jsonResponse), response.OutputStream); break; } case PartnerSyncMessageType.QUEUE_CREATE: { /* Parse queue create request */ var queueCreateRequest = JSONSerializer <PartnerSyncQueueCreate> .Deserialize(partnerSyncRequestData.Data); QueueEngine.CreateQueue(queueCreateRequest.UID, queueCreateRequest.NodeId, queueCreateRequest.QueueName, queueCreateRequest.Readers); jsonResponse.Success = true; jsonResponse.Message = "Success"; JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(jsonResponse), response.OutputStream); break; } case PartnerSyncMessageType.QUEUE_WRITE: { /* Parse queue write request */ var queueWriteRequest = JSONSerializer <PartnerSyncQueueWrite> .Deserialize(partnerSyncRequestData.Data); /* Try to correct timezone issues */ Config <long> .GetInstance()["TIMEZONE_CORRECTION"] = queueWriteRequest.Timestamp.ToFileTimeUtc() - DateTime.UtcNow.ToFileTimeUtc(); /* Add to buffered queue */ if (QueueEngine.WriteBufferedQueue(queueWriteRequest.UID, queueWriteRequest.NodeId, queueWriteRequest.QueueName, queueWriteRequest.Data, queueWriteRequest.Timestamp)) { jsonResponse.Success = true; jsonResponse.Message = "Success"; } else { jsonResponse.Success = false; jsonResponse.Message = "Not enough space in queue"; } JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(jsonResponse), response.OutputStream); break; } case PartnerSyncMessageType.QUEUE_COMMIT: { /* Parse queue commit request */ var queueCommitRequest = JSONSerializer <PartnerSyncRequestCommit> .Deserialize(partnerSyncRequestData.Data); QueueEngine.CommitQueue(queueCommitRequest.UID, queueCommitRequest.NodeId, queueCommitRequest.ReaderId, queueCommitRequest.ReaderNodeId, queueCommitRequest.QueueName); jsonResponse.Success = true; jsonResponse.Message = "Success"; JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(jsonResponse), response.OutputStream); break; } default: { jsonResponse.Message = "Invalid Message ID"; break; } } } catch (CryptographicException e) { Console.WriteLine(e); jsonResponse.Message = e.Message; JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(jsonResponse), response.OutputStream); } }
public static AsymmetricCipherKeyPair Get() { using StreamReader stream = File.OpenText("test-key.pem"); return(CryptoEngine.LoadRsaKey(stream)); }
public DocScanClient(string sdkId, StreamReader privateKeyStream, HttpClient httpClient = null, Uri apiUri = null) : this(sdkId, CryptoEngine.LoadRsaKey(privateKeyStream), httpClient, apiUri) { }
public ActionResult Login(LoginModels _login) { int userroleid = 0; int useridlogin = 0; string niklogin = ""; if (ModelState.IsValid) //validating the user inputs { //bool isExist = false; string username = _login.UserName.Trim(); string password = CryptoEngine.Encrypt(_login.Password.Trim()); //string password = _login.Password.Trim(); List <LoginModels> LogList = ppicdb.ListMenu(username, password); if (LogList.Count == 0) { ViewBag.ErrorMsg = "Please enter the valid credentials!..."; return(View()); } userroleid = Convert.ToInt32(LogList[0].UserRoleId); if (userroleid > 0) { List <MenuModels> LogListMenu = ppicdb.ListMenu(userroleid); FormsAuthentication.SetAuthCookie(LogList[0].UserName, false); // set the formauthentication cookie Session["LoginCredentials"] = LogList[0]; // Bind the _logincredentials details to "LoginCredentials" session Session["MenuMaster"] = LogListMenu; //Bind the _menus list to MenuMaster session Session["UserName"] = LogList[0].UserName; Session["codeMMR"] = ""; Session["TypePrint"] = ""; useridlogin = Convert.ToInt32(LogList[0].UserId); if (useridlogin > 0) { Session["UserIDLogin"] = useridlogin; } niklogin = LogList[0].CustCode; if (niklogin != "") { Session["UserNIKLogin"] = niklogin; List <Customers> LogNIkEmp = ppicdb.ListUserExternal(niklogin); Session["UserIDEmployee"] = LogNIkEmp[0].CustCode; Session["UserNameEmployee"] = LogNIkEmp[0].CustName; } if (userroleid == 5) { return(RedirectToAction("ImgCasting", "PPIC")); } else { return(RedirectToAction("Index", "PPIC")); } } else { ViewBag.ErrorMsg = "Please enter the valid credentials!..."; return(View()); } } return(View()); }