Summary description for Cryptography
 /// <summary>
 /// Checks the supplied <paramref name="keyHash"/> against all of the stored passwords to 
 /// see if the hash is valid.
 /// </summary>
 /// <param name="keyHash">The hex-encoded hash to validate</param>
 /// <param name="salt">The hex-encoded salt value</param>
 /// <param name="hashAlgorithm">The <see cref="Cryptography.HashAlgorithmType"/> used to generate the hash</param>
 /// <returns>
 /// <c>true</c> if the hash matches one of the stored password/key values;
 /// <c>false</c> if no match is found
 /// </returns>
 public bool IsValid(string keyHash, string salt, Cryptography.HashAlgorithmType hashAlgorithm)
 {
     // the key returned here will not actually be valid, but will indicate a match
     // (this is because the EncryptionAlgorithm will not be set properly)
     Key key;
     return IsValid(keyHash, salt, hashAlgorithm, Cryptography.SymmetricAlgorithmType.PlainText, out key);
 }
Example #2
0
        /// <summary>
        /// Creates a new instance of the Key class.
        /// </summary>
        /// <param name="password">The user-supplied password to use as the basis for the key</param>
        /// <param name="hashAlgorithm">The <see cref="Cryptography.HashAlgorithmType"/> used when hashing values</param>
        /// <param name="encryptionAlgorithm">The <see cref="Cryptography.SymmetricAlgorithmType"/> used when encrypting values</param>
        protected Key(string password, Cryptography.HashAlgorithmType hashAlgorithm, Cryptography.SymmetricAlgorithmType encryptionAlgorithm)
        {
            if (!String.IsNullOrEmpty(password))
            {
                this.password = password;
                this.hashAlgorithm = hashAlgorithm;
                this.encryptionAlgorithm = encryptionAlgorithm;

                byte[] saltBytes = Cryptography.GenerateBytes(8);
                this.salt = Cryptography.HexEncode(saltBytes);

                byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
                byte[] keyBasis = new byte[passwordBytes.Length + saltBytes.Length];
                Array.Copy(passwordBytes, 0, keyBasis, 0, passwordBytes.Length);
                Array.Copy(saltBytes, 0, keyBasis, passwordBytes.Length, saltBytes.Length);

                byte[] keyBytes = Cryptography.ComputeHash(keyBasis, hashAlgorithm);
                this.encryptionKey = keyBytes;

                byte[] keyHashBytes = Cryptography.ComputeHash(keyBytes, hashAlgorithm);
                this.keyHash = Cryptography.HexEncode(keyHashBytes);
            }
            else
                InitializeEmptyKey();
        }
 public Cryptography.GameCryptography HandleClientKeyPacket(string PublicKey, Cryptography.GameCryptography cryptographer)
 {
     byte[] key = _keyExchange.ComputeKey(OpenSSL.BigNumber.FromHexString(PublicKey));
     cryptographer.SetKey(Encoding.ASCII.GetBytes(PostProcessDHKey(key)));
     cryptographer.SetIvs(_clientIv, _serverIv);
     return cryptographer;
 }
	public Cryptography()
	{
		if (instance != null)
		{
			return;
		}
		else
		{
			instance = this;
		}
	}
        private static unsafe int FindApplicationPolicyCallback(Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData) {
            string eku = (string) pvCallbackData;
            if (eku.Length == 0)
                return CAPI.S_FALSE;
            IntPtr pCertContext = safeCertContextHandle.DangerousGetHandle();
            int cNumOIDs = 0;
            uint cbOIDs = 0;
            SafeLocalAllocHandle rghOIDs = SafeLocalAllocHandle.InvalidHandle;
            if (!CAPI.CertGetValidUsages(1, new IntPtr(&pCertContext), new IntPtr(&cNumOIDs), rghOIDs, new IntPtr(&cbOIDs))) 
                return CAPI.S_FALSE;

            rghOIDs = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbOIDs));
            if (!CAPI.CertGetValidUsages(1, new IntPtr(&pCertContext), new IntPtr(&cNumOIDs), rghOIDs, new IntPtr(&cbOIDs))) 
                return CAPI.S_FALSE;

            // -1 means the certificate is good for all usages.
            if (cNumOIDs == -1)
                return CAPI.S_OK;

            for (int index = 0; index < cNumOIDs; index++) {
                IntPtr pszOid = Marshal.ReadIntPtr(new IntPtr((long) rghOIDs.DangerousGetHandle() + index * Marshal.SizeOf(typeof(IntPtr))));
                string oidValue = Marshal.PtrToStringAnsi(pszOid);
                if (String.Compare(eku, oidValue, StringComparison.OrdinalIgnoreCase) == 0)
                    return CAPI.S_OK;
            }

            return CAPI.S_FALSE;
        }
 private static unsafe int FindIssuerDistinguishedNameCallback(Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData) {
     string rdn = CAPI.GetCertNameInfo(safeCertContextHandle, CAPI.CERT_NAME_ISSUER_FLAG, CAPI.CERT_NAME_RDN_TYPE);
     if (String.Compare(rdn, (string) pvCallbackData, StringComparison.OrdinalIgnoreCase) != 0)
         return CAPI.S_FALSE;
     return CAPI.S_OK;
 }
        private static unsafe int FindSubjectKeyIdentifierCallback(Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData) {
            SafeLocalAllocHandle ptr = SafeLocalAllocHandle.InvalidHandle;
            // We look for the Key Id extended property 
            // this will first look if there is a V3 SKI extension
            // and then if that fails, It will return the Key Id extended property.
            uint cbData = 0;
            if (!CAPI.CertGetCertificateContextProperty(safeCertContextHandle, 
                                                        CAPI.CERT_KEY_IDENTIFIER_PROP_ID, 
                                                        ptr, 
                                                        ref cbData))
                return CAPI.S_FALSE;

            ptr = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbData));
            if (!CAPI.CertGetCertificateContextProperty(safeCertContextHandle, 
                                                        CAPI.CERT_KEY_IDENTIFIER_PROP_ID, 
                                                        ptr, 
                                                        ref cbData))
                return CAPI.S_FALSE;

            byte[] subjectKeyIdentifier = (byte[]) pvCallbackData;
            if (subjectKeyIdentifier.Length != cbData)
                return CAPI.S_FALSE;

            byte[] hex = new byte[cbData];
            Marshal.Copy(ptr.DangerousGetHandle(), hex, 0, hex.Length);
            ptr.Dispose();

            for (uint index = 0; index < cbData; index++) {
                if (subjectKeyIdentifier[index] != hex[index])
                    return CAPI.S_FALSE;
            }

            return CAPI.S_OK;
        }
Example #8
0
        internal static string FindOidInfo(uint keyType, string keyValue, Cryptography.OidGroup oidGroup) {
            if (keyValue == null)
                throw new ArgumentNullException("keyValue");
            if (keyValue.Length == 0)
                return null;

            SafeLocalAllocHandle pvKey = SafeLocalAllocHandle.InvalidHandle;

            try {
                switch(keyType) {
                case CAPI.CRYPT_OID_INFO_OID_KEY:
                    pvKey = StringToAnsiPtr(keyValue);
                    break;

                case CAPI.CRYPT_OID_INFO_NAME_KEY:
                    pvKey = StringToUniPtr(keyValue);
                    break;

                default:
                    Debug.Assert(false);
                    break;
                }

                CAPI.CRYPT_OID_INFO pOidInfo = CAPI.CryptFindOIDInfo(keyType, pvKey, oidGroup);


                if (keyType == CAPI.CRYPT_OID_INFO_OID_KEY) {
                    return pOidInfo.pwszName;
                }
                else {
                    return pOidInfo.pszOID;
                }
            }
            finally {
                pvKey.Dispose();
            }
        }
Example #9
0
        public async Task <IActionResult> Put(int id, [FromBody] Manager entity)
        {
            Manager ObjectToBeUpdated = null;

            try
            {
                if (string.IsNullOrEmpty(entity.FirstName) || string.IsNullOrEmpty(entity.LastName) ||
                    string.IsNullOrEmpty(entity.Username) || string.IsNullOrEmpty(entity.Email) ||
                    entity.RoleID < 1)
                {
                    return(new BadRequestObjectResult(new Error(errorEnum.e_badRequest)));                   // This returns HTTP 404
                }
                //fetch object, assuming it exists
                ObjectToBeUpdated = await agent.Find <Manager>(id);

                if (ObjectToBeUpdated == null)
                {
                    return(new NotFoundObjectResult(entity));
                }

                if (!User.IsInRole("Administrator") || LoggedInUser().ID != id)
                {
                    return(new UnauthorizedResult());// return HTTP 401
                }
                ObjectToBeUpdated.FirstName      = entity.FirstName;
                ObjectToBeUpdated.LastName       = entity.LastName;
                ObjectToBeUpdated.OtherInfo      = entity.OtherInfo;
                ObjectToBeUpdated.PrimaryPhone   = entity.PrimaryPhone;
                ObjectToBeUpdated.SecondaryPhone = entity.SecondaryPhone;
                ObjectToBeUpdated.Username       = entity.Username;
                ObjectToBeUpdated.Email          = entity.Email;

                //admin can only change role
                if (User.IsInRole("Administrator"))
                {
                    ObjectToBeUpdated.RoleID = entity.RoleID;
                }

                //change password if needed
                if (!string.IsNullOrEmpty(entity.Password) && !Cryptography
                    .VerifyPassword(Encoding.UTF8.GetString(Convert.FromBase64String(entity.Password)),
                                    ObjectToBeUpdated.Salt, ObjectToBeUpdated.Password))
                {
                    ObjectToBeUpdated.Salt     = Cryptography.CreateSalt();
                    ObjectToBeUpdated.Password = Cryptography.GenerateSHA256Hash(Encoding.UTF8
                                                                                 .GetString(Convert.FromBase64String(entity.Password)), ObjectToBeUpdated.Salt);
                }//end if

                var x = await agent.Update <Manager>(id, entity);

                //remove info not relevant
                x.Salt     = string.Empty;
                x.Password = string.Empty;

                return(Ok(x));
            }
            catch (Exception ex)
            {
                return(await HandleExceptionAsync(ex));
            }
        }
Example #10
0
 public Guid GenerateIntallationId(string email, string password)
 {
     return(Guid.Parse(Cryptography.ToMd5(email + password)));
 }
Example #11
0
        public void AddQueryServer(QueryServerConnection Description, Cryptography.Key MasterSeed)
        {
            MasterQueryServerConnection Connection;
            Connection = (MasterQueryServerConnection) Description;
            Connection.MasterSeed = MasterSeed;

            QueryServers.Add(Connection);
        }
Example #12
0
        private void Test_Register(string testName, Growl.Connector.Application app, List<NotificationType> types, Cryptography.SymmetricAlgorithmType ea, Cryptography.HashAlgorithmType ha)
        {
            GrowlConnector g = new GrowlConnector(this.textBox2.Text);
            g.EncryptionAlgorithm = ea;
            g.KeyHashAlgorithm = ha;

            //string r = g.Register(app, types.ToArray());

            //WriteTestRequest(r);
        }
Example #13
0
 public byte[] GetMAC(Cryptography.Authentication Authentication, Cryptography.Key Key)
 {
     if (Authentication != Cryptography.Authentication.Unknown) {
         return Cryptography.GetMAC(Payload, Authentication, Key);
         }
     else {
         return null;
         }
 }
Example #14
0
 public BoundMessage(string PayloadIn, byte[] TicketIn,
              Cryptography.Authentication Authentication, Cryptography.Key Key)
 {
     BindMessage(PayloadIn, TicketIn, Authentication, Key);
 }
Example #15
0
 public BoundResponse(string PayloadIn, byte[] TicketIn,
              Cryptography.Authentication Authentication, Cryptography.Key Key)
     : base(PayloadIn, TicketIn, Authentication, Key)
 {
 }
Example #16
0
 // calculate hash based on block's properties
 public string CalculateHash()
 {
     return(Cryptography.GenerateSHA256String(this.index.ToString() + this.previousHash + this.timestamp + JsonConvert.SerializeObject(this.transactions)));
 }
Example #17
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            USUARIO user = new USUARIO();

            user.ID   = model.ID;
            user.PASS = model.Password;

            Cryptography c    = new Cryptography();
            string       pass = c.Encrypt(user.PASS);

            ////using (TruequeEntities db = new TruequeEntities())
            ////{
            user = db.USUARIOs.Where(a => a.ID.Equals(user.ID) && a.PASS.Equals(pass) && a.ACTIVO == true).FirstOrDefault();
            ////}


            if (user != null)
            {
                FormsAuthentication.SetAuthCookie(model.ID, false);

                ////var authTicket = new FormsAuthenticationTicket(1, user.ID, DateTime.Now, DateTime.Now.AddMinutes(20), false, user.MIEMBROS.FirstOrDefault().ROL.NOMBRE);
                var    authTicket      = new FormsAuthenticationTicket(1, user.ID.ToUpper(), DateTime.Now, DateTime.Now.AddDays(1), false, "Administrador");
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                var    authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                HttpContext.Response.Cookies.Add(authCookie);
                ////return RedirectToAction("Index", "Home");
                if (returnUrl != null)
                {
                    bool   us    = false;
                    string utest = ConfigurationManager.AppSettings["userTest"];
                    if (utest == null)
                    {
                        utest = "";
                    }
                    if (utest == "X")
                    {
                        us = true;
                    }

                    if (!us)
                    {
                        var checkUser = db.USUARIOLOGs.SingleOrDefault(x => x.USUARIO_ID == user.ID.ToUpper());

                        try
                        {
                            if (checkUser == null)
                            {
                                USUARIOLOG usuLog = new USUARIOLOG();
                                usuLog.USUARIO_ID = user.ID.ToUpper();
                                usuLog.POS        = 1;
                                usuLog.SESION     = System.Web.HttpContext.Current.Session.SessionID;
                                usuLog.NAVEGADOR  = Request.Browser.Type;
                                usuLog.UBICACION  = System.Environment.UserName + " - " + RegionInfo.CurrentRegion.DisplayName;
                                usuLog.FECHA      = DateTime.Now;
                                usuLog.LOGIN      = true;
                                db.USUARIOLOGs.Add(usuLog);
                                db.SaveChanges();
                                Session["userlog"] = usuLog;
                                return(Redirect(returnUrl));
                            }
                            else
                            {
                                return(RedirectToAction("validateLoginView", new { USUARIO_ID = user.ID.ToUpper(), returnUrl = returnUrl }));
                                ////checkUser.USUARIO_ID = user.ID;
                                ////checkUser.POS = 1;
                                ////checkUser.SESION = System.Web.HttpContext.Current.Session.SessionID;
                                ////checkUser.NAVEGADOR = Request.Browser.Type;
                                ////checkUser.UBICACION = RegionInfo.CurrentRegion.DisplayName;
                                ////checkUser.FECHA = DateTime.Now;
                                ////checkUser.LOGIN = true;
                                ////db.SaveChanges();
                                ////Session["userlog"] = checkUser;
                                ////return Redirect(returnUrl);
                            }
                        }
                        catch
                        {
                            //Hay que revisar las posibilidades de error
                        }
                    }

                    USUARIOLOG usuLog2 = new USUARIOLOG();
                    Session["userlog"] = new USUARIOLOG();

                    return(Redirect(returnUrl));
                }
                return(RedirectToAction("Index", "Home"));
            }

            else
            {
                ModelState.AddModelError("", "Usuario/contraseña incorrecta.");
                return(View(model));
            }
        }
Example #18
0
 protected void InitServerContext(Cryptography.Authentication AuthenticationIn)
 {
     Authentication = AuthenticationIn;
     MasterSeed = new Cryptography.Key (Authentication);
 }
Example #19
0
 public override void Run(DecryptOptions options)
 {
     System.Console.WriteLine(Cryptography.DecryptString(options.StringToDecrypt, _encryptionKey));
 }
Example #20
0
 public void AddQueryServer(QueryServerConnection Description, Cryptography.Key MasterSeed)
 {
     Context.AddQueryServer(Description, MasterSeed);
 }
Example #21
0
 public string HashPassword(string password)
 {
     return(Cryptography.Encrypt(password));
 }
Example #22
0
        static private void LoadUsuarios()
        {
            var numUsuarios = 50;
            var usuarios    = Context.UsuarioDbSet;
            var personas    = Context.PersonaDbSet;
            var personasLen = personas.Count();
            var permisos    = Context.PermisosUsuarioDbSet;

            var permisosLen = 10;

            for (int permiseIterator = 0; permiseIterator < permisosLen; permiseIterator++)
            {
                var nombre = Faker.Name.FullName() + Faker.Name.Suffix();
                if (!permisos.Any((p) => p.Nombre == nombre))
                {
                    var permiso = new PermisosUsuario()
                    {
                        Nombre                = nombre,
                        Descripcion           = "",
                        PermisoAdmin          = RandomGenerator.Next(100) < 5,
                        PermisoAdministrativo = RandomGenerator.Next(100) < 50,
                        PermisoAlumno         = RandomGenerator.Next(100) < 50,
                        PermisProfesor        = RandomGenerator.Next(100) < 50
                    };

                    permisos.Add(permiso);
                    Context.SaveChanges();
                }
                else
                {
                    permiseIterator--;
                }
            }

            var permisos2 = Context.PermisosUsuarioDbSet.ToList();

            permisosLen = permisos.Count() - 1;
            var personas2 = personas.ToList();

            personasLen = personas2.Count() - 1;

            for (int userIterator = 0; userIterator < numUsuarios; userIterator++)
            {
                var persona       = personas2.ElementAt(RandomGenerator.Next(personasLen));
                var dni           = persona.Dni;
                var personaNombre = persona.Nombre;
                if (!usuarios.Any((u) => u.Persona == dni && u.Username != personaNombre))
                {
                    var permiso  = permisos2.ElementAt(RandomGenerator.Next(permisosLen));
                    var fullname = persona.Nombre + " " + persona.Apellidos;
                    var usuario  = new Usuario()
                    {
                        Nombre          = permiso.Nombre,
                        Username        = personaNombre,
                        Contrasenya     = Cryptography.Encrypt(Generator.GeneratePassword(), personaNombre),
                        PermisosUsuario = permiso,
                        Persona         = dni,
                        //Persona1 = persona
                    };

                    usuarios.Add(usuario);
                    Context.SaveChanges();
                }
                else
                {
                    userIterator--;
                }
            }
        }
Example #23
0
 internal static X509Certificate2Collection GetCertificates(Cryptography.SafeCertStoreHandle safeCertStoreHandle) {
     X509Certificate2Collection collection = new X509Certificate2Collection();
     IntPtr pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, IntPtr.Zero);
     while (pEnumContext != IntPtr.Zero) {
         X509Certificate2 certificate = new X509Certificate2(pEnumContext);
         collection.Add(certificate);
         pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, pEnumContext);
     }
     return collection;
 }
Example #24
0
 public ActionResult AddStaff(AddStaffViewModel model)
 {
     try
     {
         HttpCookie conString = Request.Cookies.Get("rwxgqlb"); //getting the connection string from cookies
         if (!ModelState.IsValid)
         {
             return(View());
         }
         if (model.StaffType == StaffTypes.NonTeaching && model.JobType == null)
         {
             ModelState.AddModelError("JobType", "This field is required"); //adding model error which displayed on invalid entry
             return(View());
         }
         NonTeachingStaff nts = null;
         Teacher          t   = null;
         try
         {
             if (model.StaffType == StaffTypes.NonTeaching)
             {
                 nts = new NonTeachingStaff(model.Name, model.CNIC, model.Address, new Models.HelperModels.MobileNumber(model.MCountryCode, model.MCompanyCode, model.MNumber), model.Salary, model.Gender, model.JobType, Cryptography.Decrypt(conString.Value));
             }
             else if (model.StaffType == StaffTypes.Teacher)
             {
                 t = new Teacher(model.Name, model.CNIC, model.Address, new Models.HelperModels.MobileNumber(model.MCountryCode, model.MCompanyCode, model.MNumber), model.Salary, model.Gender, Cryptography.Decrypt(conString.Value));
             }
         }
         catch (Exception ex)
         {
             ModelState.AddModelError(string.Empty, ex.Message);
             return(View());
         }
         if (model.StaffType == StaffTypes.Teacher && t != null)
         {
             ViewTeacherDetailsViewModel vtdvm = new ViewTeacherDetailsViewModel
             {
                 Address        = t.Address,
                 CNIC           = t.CNIC,
                 Gender         = t.Gender + "",
                 Id             = t.StaffId,
                 MNumber        = t.PhoneNumber.GetLocalViewFormat(),
                 Name           = t.Name,
                 Qualifications = new List <TeacherQualification>(),
                 Salary         = decimal.Round(t.Salary),
                 Sections       = new List <TeacherSection>(),
                 JoiningDate    = t.Joiningdate.ToLongDateString()
             };
             foreach (var item in t.Qualifications)
             {
                 vtdvm.Qualifications.Add(new TeacherQualification
                 {
                     Degree    = item.Degree,
                     Id        = item.Id,
                     Year      = item.Year.ToString(),
                     TeacherId = t.StaffId
                 });
             }
             foreach (var item in t.GetAssignedSections())
             {
                 vtdvm.Sections.Add(new TeacherSection
                 {
                     Class     = item.Section.Class.Name,
                     Section   = item.Section.Name,
                     SectionId = item.Section.SectionId,
                     Subject   = item.Subject.Name,
                     SubjectId = item.Subject.SubjectId,
                     TeacherId = t.StaffId
                 });
             }
             ViewBag.Success = true;
             return(View("ViewTeacherDetails", vtdvm));
         }
         else if (model.StaffType == StaffTypes.NonTeaching && nts != null)
         {
             ViewNonStaffDetailsViewModel vnvm = new ViewNonStaffDetailsViewModel
             {
                 Address     = nts.Address,
                 CNIC        = nts.CNIC,
                 Gender      = nts.Gender + "",
                 Id          = nts.StaffId,
                 JobType     = nts.JobType,
                 MNumber     = nts.PhoneNumber.GetLocalViewFormat(),
                 Name        = nts.Name,
                 Salary      = decimal.Round(nts.Salary),
                 JoiningDate = nts.Joiningdate.ToLongDateString()
             };
             ViewBag.Success = true;
             return(View("ViewNonStaffDetails", vnvm));
         }
         else
         {
             return(View());
         }
     }
     catch (Exception ex)
     {
         return(Content(ex.Message));
     }
 }
        private unsafe static Cryptography.SafeCertStoreHandle FindCertInStore(Cryptography.SafeCertStoreHandle safeSourceStoreHandle, X509FindType findType, Object findValue, bool validOnly) {
            if (findValue == null)
                throw new ArgumentNullException("findValue");

            IntPtr pvFindPara = IntPtr.Zero;
            object pvCallbackData1 = null;
            object pvCallbackData2 = null;
            FindProcDelegate pfnCertCallback1 = null;
            FindProcDelegate pfnCertCallback2 = null;
            uint dwFindType = CAPI.CERT_FIND_ANY;
            string subject, issuer;

            CAPI.CRYPTOAPI_BLOB HashBlob = new CAPI.CRYPTOAPI_BLOB();
            SafeLocalAllocHandle pb = SafeLocalAllocHandle.InvalidHandle;
            _FILETIME ft = new _FILETIME();
            string oidValue = null;

            switch(findType) {
            case X509FindType.FindByThumbprint:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                byte[] hex = X509Utils.DecodeHexString((string) findValue);
                pb = X509Utils.ByteToPtr(hex);
                HashBlob.pbData = pb.DangerousGetHandle(); 
                HashBlob.cbData = (uint) hex.Length;
                dwFindType = CAPI.CERT_FIND_HASH;
                pvFindPara = new IntPtr(&HashBlob);
                break;

            case X509FindType.FindBySubjectName:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                subject = (string) findValue;
                dwFindType = CAPI.CERT_FIND_SUBJECT_STR;
                pb = X509Utils.StringToUniPtr(subject);
                pvFindPara = pb.DangerousGetHandle();
                break;

            case X509FindType.FindBySubjectDistinguishedName:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                subject = (string) findValue;
                pfnCertCallback1 = new FindProcDelegate(FindSubjectDistinguishedNameCallback);
                pvCallbackData1 = subject;
                break;

            case X509FindType.FindByIssuerName:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                issuer = (string) findValue;
                dwFindType = CAPI.CERT_FIND_ISSUER_STR;
                pb = X509Utils.StringToUniPtr(issuer);
                pvFindPara = pb.DangerousGetHandle();
                break;

            case X509FindType.FindByIssuerDistinguishedName:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                issuer = (string) findValue;
                pfnCertCallback1 = new FindProcDelegate(FindIssuerDistinguishedNameCallback);
                pvCallbackData1 = issuer;
                break;

            case X509FindType.FindBySerialNumber:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                pfnCertCallback1 = new FindProcDelegate(FindSerialNumberCallback);
                pfnCertCallback2 = new FindProcDelegate(FindSerialNumberCallback);
                BigInt h = new BigInt();
                h.FromHexadecimal((string) findValue);
                pvCallbackData1 = (byte[]) h.ToByteArray();
                h.FromDecimal((string) findValue);
                pvCallbackData2 = (byte[]) h.ToByteArray();
                break;

            case X509FindType.FindByTimeValid:
                if (findValue.GetType() != typeof(DateTime))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                *((long*) &ft) = ((DateTime) findValue).ToFileTime();
                pfnCertCallback1 = new FindProcDelegate(FindTimeValidCallback);
                pvCallbackData1 = ft; 
                break;

            case X509FindType.FindByTimeNotYetValid:
                if (findValue.GetType() != typeof(DateTime))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                *((long*) &ft) = ((DateTime) findValue).ToFileTime();
                pfnCertCallback1 = new FindProcDelegate(FindTimeNotBeforeCallback);
                pvCallbackData1 = ft; 
                break;

            case X509FindType.FindByTimeExpired:
                if (findValue.GetType() != typeof(DateTime))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                *((long*) &ft) = ((DateTime) findValue).ToFileTime();
                pfnCertCallback1 = new FindProcDelegate(FindTimeNotAfterCallback);
                pvCallbackData1 = ft; 
                break;

            case X509FindType.FindByTemplateName:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                pvCallbackData1 = (string) findValue; 
                pfnCertCallback1 = new FindProcDelegate(FindTemplateNameCallback);
                break;

            case X509FindType.FindByApplicationPolicy:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                // If we were passed the friendly name, retrieve the value string.
                oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, (string) findValue, Cryptography.OidGroup.Policy);
                if (oidValue == null) {
                    oidValue = (string) findValue;
                    X509Utils.ValidateOidValue(oidValue);
                }
                pvCallbackData1 = oidValue;
                pfnCertCallback1 = new FindProcDelegate(FindApplicationPolicyCallback);
                break;

            case X509FindType.FindByCertificatePolicy:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                // If we were passed the friendly name, retrieve the value string.
                oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, (string)findValue, Cryptography.OidGroup.Policy);
                if (oidValue == null) {
                    oidValue = (string) findValue;
                    X509Utils.ValidateOidValue(oidValue);
                }
                pvCallbackData1 = oidValue;
                pfnCertCallback1 = new FindProcDelegate(FindCertificatePolicyCallback);
                break;

            case X509FindType.FindByExtension:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                // If we were passed the friendly name, retrieve the value string.
                oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, (string)findValue, Cryptography.OidGroup.ExtensionOrAttribute);
                if (oidValue == null) {
                    oidValue = (string) findValue;
                    X509Utils.ValidateOidValue(oidValue);
                }
                pvCallbackData1 = oidValue;
                pfnCertCallback1 = new FindProcDelegate(FindExtensionCallback);
                break;

            case X509FindType.FindByKeyUsage:
                // The findValue object can be either a friendly name, a X509KeyUsageFlags enum or an integer.
                if (findValue.GetType() == typeof(string)) {
                    CAPI.KEY_USAGE_STRUCT[] KeyUsages = new CAPI.KEY_USAGE_STRUCT[] { 
                        new CAPI.KEY_USAGE_STRUCT("DigitalSignature", CAPI.CERT_DIGITAL_SIGNATURE_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("NonRepudiation",   CAPI.CERT_NON_REPUDIATION_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("KeyEncipherment",  CAPI.CERT_KEY_ENCIPHERMENT_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("DataEncipherment", CAPI.CERT_DATA_ENCIPHERMENT_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("KeyAgreement",     CAPI.CERT_KEY_AGREEMENT_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("KeyCertSign",      CAPI.CERT_KEY_CERT_SIGN_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("CrlSign",          CAPI.CERT_CRL_SIGN_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("EncipherOnly",     CAPI.CERT_ENCIPHER_ONLY_KEY_USAGE),
                        new CAPI.KEY_USAGE_STRUCT("DecipherOnly",     CAPI.CERT_DECIPHER_ONLY_KEY_USAGE)
                    };

                    for (uint index = 0; index < KeyUsages.Length; index++) {
                        if (String.Compare(KeyUsages[index].pwszKeyUsage, (string) findValue, StringComparison.OrdinalIgnoreCase) == 0) {
                            pvCallbackData1 = KeyUsages[index].dwKeyUsageBit;
                            break;
                        }
                    }
                    if (pvCallbackData1 == null)
                        throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindType));
                } else if (findValue.GetType() == typeof(X509KeyUsageFlags)) {
                    pvCallbackData1 = findValue;
                } else if (findValue.GetType() == typeof(uint) || findValue.GetType() == typeof(int)) {
                    // We got the actual DWORD
                    pvCallbackData1 = findValue;
                } else 
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindType));

                pfnCertCallback1 = new FindProcDelegate(FindKeyUsageCallback);
                break;

            case X509FindType.FindBySubjectKeyIdentifier:
                if (findValue.GetType() != typeof(string))
                    throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue));
                pvCallbackData1 = (byte[]) X509Utils.DecodeHexString((string) findValue);
                pfnCertCallback1 = new FindProcDelegate(FindSubjectKeyIdentifierCallback);
                break;

            default:
                throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindType));
            }

            // First, create a memory store
            Cryptography.SafeCertStoreHandle safeTargetStoreHandle = CAPI.CertOpenStore(new IntPtr(CAPI.CERT_STORE_PROV_MEMORY), 
                                                                           CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, 
                                                                           IntPtr.Zero, 
                                                                           CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG | CAPI.CERT_STORE_CREATE_NEW_FLAG, 
                                                                           null);
            if (safeTargetStoreHandle == null || safeTargetStoreHandle.IsInvalid)
                throw new CryptographicException(Marshal.GetLastWin32Error());

            // FindByCert will throw an exception in case of failures.
            FindByCert(safeSourceStoreHandle, 
                       dwFindType,
                       pvFindPara, 
                       validOnly, 
                       pfnCertCallback1,
                       pfnCertCallback2, 
                       pvCallbackData1,
                       pvCallbackData2, 
                       safeTargetStoreHandle);

            pb.Dispose();
            return safeTargetStoreHandle;
        }
Example #26
0
 public ActionResult EditStaff(AddStaffViewModel model, int id)
 {
     try
     {
         HttpCookie conString = Request.Cookies.Get("rwxgqlb"); //getting the encrypted connection string from cookies
         if (!ModelState.IsValid)
         {
             //f the model state is not acorrding to the given format
             ViewBag.StaffId   = id;              //sending the staff id back to the view for again processing
             ViewBag.StaffType = model.StaffType; //sending staff type to the view  via viewbag
             return(View());
         }
         if (model.StaffType == StaffTypes.NonTeaching && model.JobType == null)
         {
             //if the staff type is non-teaching & job type is not selected
             ModelState.AddModelError("JobType", "This field is required"); //adding error meesage
             ViewBag.StaffId   = id;                                        //sending the staff id back to the view for again processing
             ViewBag.StaffType = model.StaffType;                           //sending staff type to the view  via viewbag
             return(View());
         }
         try
         {
             if (model.StaffType == StaffTypes.NonTeaching)
             {
                 //if non-teachng staff is selected
                 NonTeachingStaff s = new NonTeachingStaff(id, Cryptography.Decrypt(conString.Value))
                 {
                     Address     = model.Address,
                     CNIC        = model.CNIC,
                     JobType     = model.JobType,
                     Name        = model.Name,
                     PhoneNumber = new MobileNumber(model.MCountryCode, model.MCompanyCode, model.MNumber),
                     Salary      = model.Salary
                 };
             }
             else if (model.StaffType == StaffTypes.Teacher)
             {
                 //if teaching staff is selected
                 Teacher s = new Teacher(id, Cryptography.Decrypt(conString.Value))
                 {
                     Address     = model.Address,
                     CNIC        = model.CNIC,
                     Name        = model.Name,
                     PhoneNumber = new MobileNumber(model.MCountryCode, model.MCompanyCode, model.MNumber),
                     Salary      = model.Salary
                 };
             }
         }
         catch (Exception ex)
         {
             ModelState.AddModelError(string.Empty, ex.Message);
             return(View());
         }
         if (model.StaffType == StaffTypes.Teacher)
         {
             return(RedirectToAction("ViewTeacherDetails", new { id = id, s = true }));
         }
         else
         {
             return(RedirectToAction("ViewNonStaffDetails", new { id = id, s = true }));
         }
     }
     catch (Exception ex)
     {
         return(Content(ex.Message));
     }
 }
        private static unsafe int FindTimeNotBeforeCallback(Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData) {
            _FILETIME ft = (_FILETIME) pvCallbackData;
            CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle());
            if (CAPI.CertVerifyTimeValidity(ref ft, pCertContext.pCertInfo) == -1)
                return CAPI.S_OK;

            return CAPI.S_FALSE;
        }
        internal unsafe X509ExtensionCollection(Cryptography.SafeCertContextHandle safeCertContextHandle) {
            using (Cryptography.SafeCertContextHandle certContext = CAPI.CertDuplicateCertificateContext(safeCertContextHandle)) {
                CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) certContext.DangerousGetHandle());
                CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO));
                uint cExtensions = pCertInfo.cExtension;
                IntPtr rgExtensions = pCertInfo.rgExtension;

                for (uint index = 0; index < cExtensions; index++) {
                    X509Extension extension = new X509Extension(new IntPtr((long)rgExtensions + (index * Marshal.SizeOf(typeof(CAPI.CERT_EXTENSION)))));
                    X509Extension customExtension = CryptoConfig.CreateFromName(extension.Oid.Value) as X509Extension;
                    if (customExtension != null) {
                        customExtension.CopyFrom(extension);
                        extension = customExtension;
                    }
                    Add(extension);
                }
            }
        }
        private static unsafe int FindExtensionCallback(Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData) {
            CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle());
            CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO));

            IntPtr pExtension = CAPI.CertFindExtension((string) pvCallbackData,
                                                       pCertInfo.cExtension,
                                                       pCertInfo.rgExtension);
            if (pExtension == IntPtr.Zero)
                return CAPI.S_FALSE;

            return CAPI.S_OK;
        }
Example #30
0
        internal static unsafe int BuildChain (IntPtr hChainEngine,
                                               Cryptography.SafeCertContextHandle pCertContext,
                                               X509Certificate2Collection extraStore, 
                                               OidCollection applicationPolicy,
                                               OidCollection certificatePolicy,
                                               X509RevocationMode revocationMode,
                                               X509RevocationFlag revocationFlag,
                                               DateTime verificationTime,
                                               TimeSpan timeout,
                                               ref SafeX509ChainHandle ppChainContext) {
            if (pCertContext == null || pCertContext.IsInvalid)
                throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidContextHandle), "pCertContext");

            Cryptography.SafeCertStoreHandle hCertStore = Cryptography.SafeCertStoreHandle.InvalidHandle;
            if (extraStore != null && extraStore.Count > 0)
                hCertStore = X509Utils.ExportToMemoryStore(extraStore);

            CAPI.CERT_CHAIN_PARA ChainPara = new CAPI.CERT_CHAIN_PARA();

            // Initialize the structure size.
            ChainPara.cbSize = (uint) Marshal.SizeOf(ChainPara);

            Cryptography.SafeLocalAllocHandle applicationPolicyHandle = Cryptography.SafeLocalAllocHandle.InvalidHandle;
            Cryptography.SafeLocalAllocHandle certificatePolicyHandle = Cryptography.SafeLocalAllocHandle.InvalidHandle;
            try {
                // Application policy
                if (applicationPolicy != null && applicationPolicy.Count > 0) {
                    ChainPara.RequestedUsage.dwType = CAPI.USAGE_MATCH_TYPE_AND;
                    ChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint) applicationPolicy.Count;
                    applicationPolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy);
                    ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyHandle.DangerousGetHandle();
                }

                // Certificate policy
                if (certificatePolicy != null && certificatePolicy.Count > 0) {
                    ChainPara.RequestedIssuancePolicy.dwType = CAPI.USAGE_MATCH_TYPE_AND;
                    ChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint) certificatePolicy.Count;
                    certificatePolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy);
                    ChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyHandle.DangerousGetHandle();
                }

                ChainPara.dwUrlRetrievalTimeout = (uint) Math.Floor(timeout.TotalMilliseconds);

                _FILETIME ft = new _FILETIME();
                *((long*) &ft) = verificationTime.ToFileTime();

                uint flags = X509Utils.MapRevocationFlags(revocationMode, revocationFlag);

                // Build the chain.
                if (!CAPI.CertGetCertificateChain(hChainEngine,
                                                  pCertContext,
                                                  ref ft,
                                                  hCertStore,
                                                  ref ChainPara,
                                                  flags,
                                                  IntPtr.Zero,
                                                  ref ppChainContext))
                    return Marshal.GetHRForLastWin32Error();
            }
            finally {
                applicationPolicyHandle.Dispose();
                certificatePolicyHandle.Dispose();
            }

            return CAPI.S_OK;
        }
Example #31
0
 private bool CheckSignature(bool useAes, ApiClient client, string signature, string timestamp, string nonce)
 {
     return(useAes ? Cryptography.Signature(client.Config.Token, timestamp, nonce)
            .Equals(signature, StringComparison.OrdinalIgnoreCase) : true);
 }
Example #32
0
        private string BuildJQGridResults(List <WorkOrderEMS.Models.CommonModels.WorkRequestAssignmentModelList> WorkRequestList, int numberOfRows, int pageIndex, int TotalRecords)
        {
            JQGridResults    result = new JQGridResults();
            List <JQGridRow> rows   = new List <JQGridRow>();

            try
            {
                foreach (var WorkRequest in WorkRequestList)
                {
                    JQGridRow row = new JQGridRow();
                    //row.id = Project.ProjectID;
                    row.id   = Cryptography.GetEncryptedData(WorkRequest.WorkRequestAssignmentID.ToString(), true);
                    row.cell = new string[25];

                    row.cell[0]  = Convert.ToString(WorkRequest.WorkRequestType);
                    row.cell[1]  = WorkRequest.WorkRequestTypeName;
                    row.cell[2]  = Convert.ToString(WorkRequest.AssetID);
                    row.cell[3]  = Convert.ToString(WorkRequest.LocationID);
                    row.cell[4]  = WorkRequest.LocationName;
                    row.cell[5]  = WorkRequest.ProblemDesc;
                    row.cell[6]  = Convert.ToString(WorkRequest.PriorityLevel);
                    row.cell[7]  = WorkRequest.PriorityLevelName;
                    row.cell[8]  = WorkRequest.WorkRequestImage;
                    row.cell[9]  = Convert.ToString(WorkRequest.SafetyHazard);
                    row.cell[10] = WorkRequest.ProjectDesc;
                    row.cell[11] = Convert.ToString(WorkRequest.WorkRequestStatus);
                    row.cell[12] = WorkRequest.WorkRequestStatusName;
                    row.cell[13] = Convert.ToString(WorkRequest.RequestBy);
                    row.cell[14] = Convert.ToString(WorkRequest.AssignToUserId);
                    row.cell[15] = WorkRequest.AssignToUserName;
                    row.cell[16] = Convert.ToString(WorkRequest.AssignByUserId);
                    row.cell[17] = WorkRequest.Remarks;
                    row.cell[18] = Convert.ToString(WorkRequest.WorkRequestProjectType);
                    row.cell[19] = WorkRequest.WorkRequestProjectTypeName;
                    row.cell[20] = WorkRequest.CodeID;
                    row.cell[21] = WorkRequest.CreationDate;
                    //row.cell[22] = WorkRequest.AssignedTime;
                    //row.cell[23] = WorkRequest.StartTime;
                    //row.cell[24] = WorkRequest.EndTime;
                    row.cell[22] = WorkRequest.AssignedTime != null?Convert.ToDateTime(WorkRequest.AssignedTime).ToString("MM/dd/yyyy HH:mm:ss") : null;

                    row.cell[23] = WorkRequest.StartTime != null?Convert.ToDateTime(WorkRequest.StartTime).ToString("MM/dd/yyyy HH:mm:ss") : null;

                    row.cell[24] = WorkRequest.EndTime != null?Convert.ToDateTime(WorkRequest.EndTime).ToString("MM/dd/yyyy HH:mm:ss") : null;

                    rows.Add(row);
                }
                result.rows    = rows.ToArray();
                result.page    = pageIndex;
                result.total   = (int)Math.Ceiling((decimal)TotalRecords / numberOfRows);
                result.records = TotalRecords;
            }
            catch (DivideByZeroException ex)
            {
                string error = ex.Message;
            }
            catch (Exception ex)
            {
                string error = ex.Message;
            }
            return(new JavaScriptSerializer().Serialize(result));
        }
Example #33
0
        public ActionResult Index(eTracLoginModel eTracLogin)
        {
            try
            {
                //TimeZoneInfo nyTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
                //DateTime nyTime = GetLocalDateTime(DateTime.UtcNow, nyTimeZone);

                //if (nyTimeZone.IsDaylightSavingTime(nyTime))
                string loginMessage = "";
                if (ModelState.IsValid)
                {
                    eTracLoginModel result = _ILogin.AuthenticateUser(eTracLogin);
                    //result.RememberMe = eTracLogin.RememberMe;
                    if (result.UserId > 0)
                    {
                        this.CreateAuthenticateFormsTicket(result);
                        Common_B obj_Common_B = new Common_B();
                        Session["eTrac_SelectedDasboardLocationID"] = result.LocationID;
                        Session["eTrac_UserRoles"]        = this.Get_UserAssignedRoles();
                        Session["eTrac_DashboardWidget"]  = this.GetUserDashboardWidget();
                        Session["eTrac_LocationServices"] = obj_Common_B.GetLocationServicesByLocationID(result.LocationID, result.UserRoleId);
                        Session["eTrac_ProfileImage"]     = result.ProfileImage;
                        CallbackController.UserRoleId     = result.UserRoleId;
                        CallbackController.UserId         = result.UserId;
                        HomeController.UserRoleId         = result.UserRoleId;
                        HomeController.UserId             = result.UserId;
                        switch (result.UserRoleId)
                        {
                        case ((Int64)(UserType.GlobalAdmin)):
                            Session["eTrac_UserLocations"] = _ILogin.GetUserAssignedLocations(result.UserRoleId, result.UserId);
                            Session["eTrac_UserRoles"]     = Session["eTrac_LocationServices"]; // this line has been added by vijay bcz if usetype is GAdmin or ITAdmin then this type of users will be able too see all services which is assigned to this current location.
                            // QuickBookIndex();
                            return(RedirectToAction("Index", "GlobalAdmin"));

                            break;

                        case ((Int64)(UserType.ITAdministrator)):
                            Session["eTrac_UserLocations"] = _ILogin.GetUserAssignedLocations(result.UserRoleId, result.UserId);
                            Session["eTrac_UserRoles"]     = Session["eTrac_LocationServices"];
                            //QuickBookIndex();
                            return(RedirectToAction("Index", "ITAdministrator"));

                            break;

                        case ((Int64)(UserType.Administrator)):
                            Session["eTrac_UserLocations"] = _ILogin.GetAdminAssignedLocation(result.UserId);
                            // QuickBookIndex();
                            return(RedirectToAction("Index", "Administrator"));

                            break;

                        case ((Int64)(UserType.Manager)):
                            Session["eTrac_UserLocations"] = _ILogin.GetManagerAssignedLocation(result.UserId);

                            #region this code will execute only when manager declined vendor from vendor email verification page.
                            try
                            {
                                if (Request.Cookies["eTrack_VendorIdForEditAfterDeclinedByManager"] != null)
                                {
                                    string isVendorIDExists = Request.Cookies["eTrack_VendorIdForEditAfterDeclinedByManager"]["VendorID"];
                                    if (isVendorIDExists != null)
                                    {
                                        var abc = Cryptography.GetDecryptedData(isVendorIDExists, true);

                                        if (Convert.ToInt32(abc) > 0)
                                        {
                                            //string HostingPrefix = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["hostingPrefix"], System.Globalization.CultureInfo.InvariantCulture);
                                            //var adfadsf = HostingPrefix + "/Manager/EditRegisterVendor/?vdr=" + isVendorIDExists;
                                            //Response.Redirect(adfadsf);
                                            // QuickBookIndex();
                                            return(RedirectToAction("EditRegisterVendor", "Manager", new { vdr = isVendorIDExists }));
                                        }
                                    }
                                }
                            }
                            catch
                            {
                            }
                            #endregion     // by vijay sahu on 2 july 2015

                            #region This Code Will Execute if Vehicle Declined by Manager and after login redirect to edit vehicle
                            try
                            {
                                if (Request.Cookies["eTrac_VehicleIdForEditAfterDeclinedByManager"] != null)
                                {
                                    string isVehicleIDExists = Request.Cookies["eTrac_VehicleIdForEditAfterDeclinedByManager"]["QRCID"];
                                    if (isVehicleIDExists != null)
                                    {
                                        var abc = Cryptography.GetDecryptedData(isVehicleIDExists, true);

                                        if (Convert.ToInt32(abc) > 0)
                                        {
                                            //string HostingPrefix = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["hostingPrefix"], System.Globalization.CultureInfo.InvariantCulture);
                                            var redirectURL = HostingPrefix + "QRCSetup/VehicleRegistration/?qr=" + isVehicleIDExists;
                                            Response.Redirect(redirectURL);
                                            //return RedirectToAction("VehicleRegistration", "QRCSetup", new { qr = isVehicleIDExists });
                                        }
                                    }
                                }
                            }
                            catch
                            {
                            }
                            #endregion     // by Bhushan Dod on 22 September 2015
                            //QuickBookIndex();
                            return(RedirectToAction("Dashboard", "Manager"));

                            break;

                        case ((Int64)(UserType.Employee)):
                            Session["eTrac_UserLocations"] = _ILogin.GetEmployeeAssignedLocation(result.UserId);
                            //QuickBookIndex();
                            return(RedirectToAction("Index", "Employee"));

                            break;

                        case ((Int64)(UserType.Client)):
                            //Session["eTrac_UserLocations"] = _ILogin.GetEmployeeAssignedLocation(result.UserId);
                            //QuickBookIndex();
                            return(RedirectToAction("Index", "Client"));

                            break;
                        }
                    }//else { ModelState.AddModelError("", "User not found. Please check UserName or Password"); }
                    else
                    {
                        loginMessage = "User not found. Please check Username or Password";
                    }
                }//else { ModelState.AddModelError("", "Invalid UserName or Password"); }
                else
                {
                    loginMessage = "Invalid Username or Password";
                }
                ViewBag.Message = loginMessage; ViewBag.AlertMessageClass = ObjAlertMessageClass.Danger;
            }
            catch (Exception ex)
            {
                Exception_B.exceptionHandel_Runtime(ex, "public ActionResult Index(eTracLoginModel eTracLogin)", "from loginController", eTracLogin);
                ViewBag.Error = ex.Message; ViewBag.Message = "Something went wrong. Please contact support team."; ViewBag.AlertMessageClass = ObjAlertMessageClass.Danger;
            }//ModelState.AddModelError("", ex.Message);
            return(View("Index", eTracLogin));
        }
 public void DecryptEmptyTextECBPKCS7Test()
 {
     _ = Cryptography.Decrypt(string.Empty, string.Empty);
 }
Example #35
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var appSettingsSection = Configuration.GetSection("AppSettings");
            var connectionStrings  = string.Empty;

            services.Configure <AppSettings>(appSettingsSection);
            var appSettings = appSettingsSection.Get <AppSettings>();

            if (appSettings.ISTEST.Equals("Y"))
            {
                connectionStrings = Configuration.GetValue <string>("ConnectionStrings:Development:SQLConnection")
                                    .Replace($"[{ nameof(AppSettings.SQL_USERID) }]", Cryptography.DecryptString(appSettings.SQL_USERID))
                                    .Replace($"[{ nameof(AppSettings.SQL_PASSWD) }]", Cryptography.DecryptString(appSettings.SQL_PASSWD));
            }
            else
            {
                connectionStrings = Configuration.GetValue <string>("ConnectionStrings:Production:SQLConnection")
                                    .Replace($"[{ nameof(AppSettings.SQL_USERID) }]", Cryptography.DecryptString(appSettings.SQL_USERID))
                                    .Replace($"[{ nameof(AppSettings.SQL_PASSWD) }]", Cryptography.DecryptString(appSettings.SQL_PASSWD));
            }

            services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(connectionStrings));

            // configure jwt authentication
            var key = Encoding.ASCII.GetBytes(appSettings.SECRET);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };
            });

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title          = "LHB DOPA API Service",
                    Version        = "v1",
                    Description    = "Check Card status.",
                    TermsOfService = new Uri("https://www.lhbank.co.th"),
                    Contact        = new OpenApiContact
                    {
                        Name  = "Deposit Department",
                        Email = "*****@*****.**"
                    },
                    License = new OpenApiLicense
                    {
                        Name = $"Copyright{DateTime.Now.Year} LAND AND HOUSES BANK PUBLIC COMPANY LIMITED",
                        Url  = new Uri("https://www.lhbank.co.th")
                    }
                });
            });

            services.Configure <RequestLocalizationOptions>(options =>
            {
                options.DefaultRequestCulture = new RequestCulture("en-US");
            });

            services.AddScoped(typeof(ICheckCardStatusService), typeof(CheckCardStatusService));
            services.AddScoped(typeof(IApiService), typeof(ApiService));
            services.AddControllers();
        }
 public void DecryptEmptyKeyECBPKCS7Test()
 {
     _ = Cryptography.Encrypt(_text, string.Empty);
 }
Example #37
0
 private void Desencriptar(object sender, EventArgs e)
 {
     richTextBox2.Text = Cryptography.Decrypt(richTextBox1.Text, richTextBox3.Text);
 }
 public void DecryptShortKeyECBPKCS7Test()
 {
     _ = Cryptography.Decrypt(_text, _shortKey);
 }
Example #39
0
 /// <summary>
 /// Decrypt the encrypted string.
 /// </summary>
 /// <param name="Input">The string search for match.</param>
 /// <param name="Pattern">The regular expression to match.</param>
 /// <param name="Tag">A unicode character to be removed.</param>
 /// <returns></returns>
 public static string DecryptStringData(string Input, string Pattern,string Tag)
 {
     string _result = string.Empty;
     Cryptography _cryp = new Cryptography();
     string _DecryptedVal = Regex.Match(Input, Pattern).ToString();
     Input = Input.Replace(_DecryptedVal, _cryp.Decrypt(_DecryptedVal.Replace(Tag, "")));
     return Input;
 }
        public void DecryptECBPKCS7Test()
        {
            var result = Cryptography.Decrypt(_encryptedText, _secret);

            Assert.AreEqual(_text, result);
        }
Example #41
0
        public HttpResponseMessage Login([FromBody] JObject model)
        {
            try
            {
                Logging.EventLog(null, "User attempted to login to the application");
                //Creating instance for response.
                HttpResponseMessage      response = new HttpResponseMessage();
                Response <LoginResponse> output   = new Response <LoginResponse>();

                //Getting all the values from model.
                string userName = model.Value <string>("email");
                string password = model.Value <string>("password");


                //invoking custom data method
                var userData = _login.UserAuthentication(userName, password);

                if (userData != null)
                {
                    //check whether the user is active or not
                    if (userData.bt_status == true)
                    {
                        //verify the user's password
                        if (userData.vc_password == Cryptography.Encrypt(password))
                        {
                            var accessToken = Guid.NewGuid().ToString("n");
                            userData.vc_auth_token = accessToken;
                            //save access token in database
                            _login.UpdateUserAuthToken(userData.int_user_id, accessToken);


                            output.Message = "Successfully Logged In.";
                            output.Status  = true;
                            output.Data    = new LoginResponse {
                                UserDetails = userData, UserRights = _login.GetUserRights(userData.int_user_id), Roles = _login.GetUserRoles(userData.int_user_id).Select(x => x.vc_role_name).Distinct().ToList(), SettingDetails = _login.GetAllSettings()
                            };
                            response = Request.CreateResponse(HttpStatusCode.OK, JObject.FromObject(output));
                            Logging.EventLog(userData.int_user_id, "User has successfully logged in to the application");
                        }
                        else
                        {
                            output.Message = "Login failed due to incorrect password.";
                            output.Status  = false;

                            response = Request.CreateResponse(HttpStatusCode.OK, JObject.FromObject(output));
                            Logging.EventLog(null, "User has failed to login to the application");
                        }
                    }
                    else
                    {
                        output.Message = "Login failed. User is not active.";
                        output.Status  = false;
                        response       = Request.CreateResponse(HttpStatusCode.OK, JObject.FromObject(output));
                        Logging.EventLog(null, "User has failed to login to the application");
                    }
                }
                else
                {
                    output.Message = "Login failed. User not exist.";
                    output.Status  = false;
                    response       = Request.CreateResponse(HttpStatusCode.OK, JObject.FromObject(output));
                    Logging.EventLog(null, "User has failed to login to the application");
                }



                return(response);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #42
0
 public int UpdateInterfaceSftpDetailsByInterfaceId(ZionWeb.DAL.Entities.InterfaceSftpDetails interfaceSftpDetails)
 {
     interfaceSftpDetails.Password = Cryptography.Encrypt(interfaceSftpDetails.Password, _intefraceSftpDAL.GetPublicKey());
     return(_intefraceSftpDAL.UpdateInterfaceSftpDetailsByInterfaceId(interfaceSftpDetails));
 }
Example #43
0
 public static bool VerifyPassword(string storedPassword, string sentPassword)
 {
     return(storedPassword == Cryptography.Encrypt(sentPassword));
 }
 public UserRegistrationController(employeesContext employeeRegistration, Cryptography cryptography, UMAuthentication emAuth)
 {
     _emAuth = emAuth;
     _employeeRegistration = employeeRegistration;
     _cryptography         = cryptography;
 }
Example #45
0
        // Try to find OID info within a specific group, and if that doesn't work fall back to all
        // groups for compatibility with previous frameworks
        internal static string FindOidInfoWithFallback(uint key, string value, Cryptography.OidGroup group) {
            string info = FindOidInfo(key, value, group);

            // If we couldn't find it in the requested group, then try again in all groups
            if (info == null && group != Cryptography.OidGroup.All) {
                info = FindOidInfo(key, value, Cryptography.OidGroup.All);
            }

            return info;
        }
        public override void Load(Stream stream)
        {
            // Let the base class do the heavy lifting.
            base.Load(stream);

            foreach (var kvp in Data)
            {
                OriginalData.Add(kvp.Key, kvp.Value);
            }

            // Do decryption here, you can tap into the Data property like so:
            Data = Data?.ToDictionary(k => k.Key.ToUpperInvariant(), v => v.Value) as IDictionary <string, string>;

            if (Data == null)
            {
                return;
            }

            var toUpdate = new Dictionary <string, string>();

            foreach (var kvp in Data)
            {
                var keyAr = kvp.Key?.Split(':');
                if (keyAr == null)
                {
                    continue;
                }
                if (keyAr.Length == 0)
                {
                    continue;
                }

                var valueKey = string.Empty;
                if (keyAr.Length > 2)
                {
                    const string customSetting = "JOBSCUSTOMSETTINGS";
                    if (keyAr[0] == customSetting)
                    {
                        valueKey = $"{keyAr[1]}:{keyAr[2]}:VALUE";
                    }
                }
                if (kvp.Key == valueKey)
                {
                    continue;
                }

                var isEncrypted = Data.FirstOrDefault(kp => kp.Key.ToUpper().EndsWith("ISENCRYPTED") & kp.Value?.ToUpper() == "TRUE").Key != null;

                //var isEncrypted = keyAr.Any(v => v == "ISENCRYPTED");
                if (isEncrypted & Data.ContainsKey(valueKey))
                {
                    var encVal = Data[valueKey];
                    var decVal = Cryptography.DecryptText(encVal);
                    toUpdate.Add(valueKey, decVal);
                }
            }

            //updates
            foreach (var kvp in toUpdate)
            {
                Data[kvp.Key] = kvp.Value;
            }



            //Data["abc:password"] = MyEncryptionLibrary.Decrypt(Data["abc:password"]);

            // But you have to make your own MyEncryptionLibrary, not included here
        }
Example #47
0
        internal static unsafe int VerifyCertificate (Cryptography.SafeCertContextHandle pCertContext,
                                                      OidCollection applicationPolicy,
                                                      OidCollection certificatePolicy,
                                                      X509RevocationMode revocationMode,
                                                      X509RevocationFlag revocationFlag,
                                                      DateTime verificationTime,
                                                      TimeSpan timeout,
                                                      X509Certificate2Collection extraStore,
                                                      IntPtr pszPolicy,
                                                      IntPtr pdwErrorStatus) {
            if (pCertContext == null || pCertContext.IsInvalid)
                throw new ArgumentException("pCertContext");

            CAPI.CERT_CHAIN_POLICY_PARA PolicyPara = new CAPI.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_PARA)));
            CAPI.CERT_CHAIN_POLICY_STATUS PolicyStatus = new CAPI.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_STATUS)));

            // Build the chain.
            SafeX509ChainHandle pChainContext = SafeX509ChainHandle.InvalidHandle;
            int hr = X509Chain.BuildChain(new IntPtr(CAPI.HCCE_CURRENT_USER),
                                          pCertContext, 
                                          extraStore,
                                          applicationPolicy, 
                                          certificatePolicy,
                                          revocationMode,
                                          revocationFlag,
                                          verificationTime,
                                          timeout,
                                          ref pChainContext);
            if (hr != CAPI.S_OK)
                return hr;

            // Verify the chain using the specified policy.
            if (CAPI.CertVerifyCertificateChainPolicy(pszPolicy, pChainContext, ref PolicyPara, ref PolicyStatus)) {
                if (pdwErrorStatus != IntPtr.Zero)
                    *(uint*) pdwErrorStatus = PolicyStatus.dwError;

                if (PolicyStatus.dwError != 0)
                    return CAPI.S_FALSE;
            } else {
                // The API failed.
                return Marshal.GetHRForLastWin32Error();
            }

            return CAPI.S_OK;
        }
Example #48
0
        /// <summary>
        ///
        /// </summary>
        private void WithdrawApply()
        {
            string msg = "";

            try
            {
                if (!SettleSettings.OpenWithdraw)
                {
                    msg = SettleSettings.ColseWithdrawReason;
                }
                else
                {
                    //提现金额
                    decimal          dwithdrawAmt = 0M, charges = 0M;
                    TocashSchemeInfo scheme = null;

                    string withdrawAmt = txtApplyMoney.Value.ToLower();
                    string safepass    = txtcashpwd.Text;

                    if (string.IsNullOrEmpty(withdrawAmt))
                    {
                        msg = "请输入您要提现的金额";
                    }
                    else if (!decimal.TryParse(withdrawAmt, out dwithdrawAmt))
                    {
                        msg = "请输入您正确的金额";
                    }
                    else if (string.IsNullOrEmpty(safepass))
                    {
                        msg = "请输入您的提现密码";
                    }
                    else if (Cryptography.MD5(safepass) != CurrentUser.Password2)
                    {
                        msg = "提现密码不正确";
                    }
                    else
                    {
                        scheme = TocashScheme.GetModelByUser(1, UserId);

                        if (scheme == null)
                        {
                            msg = "未设置提现方案,请联系客服人员!";
                        }
                        else
                        {
                            #region 比较余额
                            //账户可用余额
                            decimal balanceAmt = viviapi.BLL.User.UsersAmt.GetUserAvailableBalance(UserId);

                            if (dwithdrawAmt > balanceAmt)
                            {
                                msg = "余额不足,请修改提现金额";
                            }
                            else if (dwithdrawAmt < scheme.minamtlimitofeach)
                            {
                                msg = "您的提现金额小于最低提现金额限制.";
                            }
                            else if (dwithdrawAmt > scheme.maxamtlimitofeach)
                            {
                                msg = "您的提现金额大于最大提现金额限制.";
                            }
                            else
                            {
                                int todaytimes = viviapi.BLL.Finance.Withdraw.Instance.GetUserDaySettledTimes(UserId,
                                                                                                              FormatConvertor.DateTimeToDateString(DateTime.Now));

                                if (todaytimes >= scheme.dailymaxtimes)
                                {
                                    msg = "您今天的提现次数已达到最多限制,请明天再试。";
                                }
                                else
                                {
                                    decimal todayAmt = viviapi.BLL.Finance.Withdraw.Instance.GetUserDaySettledAmt(UserId,
                                                                                                                  FormatConvertor.DateTimeToDateString(DateTime.Now));

                                    if (todayAmt + dwithdrawAmt >= scheme.dailymaxamt)
                                    {
                                        msg = string.Format("您今天的提现将超过最大限额,你最多还可提现{0:f2}", scheme.dailymaxamt - todayAmt);
                                    }
                                }
                            }

                            if (string.IsNullOrEmpty(msg))
                            {
                                #region 计算手续费
                                charges = scheme.chargerate * dwithdrawAmt;
                                if (scheme.lowerLimit > 0)
                                {
                                    if (charges < scheme.lowerAmt)
                                    {
                                        charges = scheme.lowerAmt;
                                    }
                                }
                                if (scheme.upperLimit > 0)
                                {
                                    if (charges > scheme.upperAmt)
                                    {
                                        charges = scheme.upperAmt;
                                    }
                                }
                                #endregion

                                if (charges >= dwithdrawAmt)
                                {
                                    msg = "余额不足";
                                }
                            }
                            #endregion

                            if (string.IsNullOrEmpty(msg))
                            {
                                #region 保存记录
                                var acctBLL           = new viviapi.BLL.User.SettlementAccount();
                                var settlementAccount = acctBLL.GetModel(this.UserId);

                                if (settlementAccount != null)
                                {
                                    var itemInfo = new Withdraw()
                                    {
                                        Tranno  = viviapi.BLL.Finance.Withdraw.Instance.GenerateOrderId(),
                                        Addtime = DateTime.Now,
                                        Amount  = dwithdrawAmt,
                                        Charges = charges,
                                        Paytime = DateTime.Now,
                                        Status  = WithdrawStatus.Auditing,
                                        Tax     = 0M,
                                        Userid  = UserId,


                                        BankCode  = settlementAccount.BankCode,
                                        PayeeBank = settlementAccount.PayeeBank,

                                        ProvinceCode = settlementAccount.ProvinceCode,
                                        BankProvince = settlementAccount.BankProvince,

                                        CityCode     = settlementAccount.CityCode,
                                        BankCity     = settlementAccount.BankCity,
                                        Payeeaddress = settlementAccount.BankAddress,


                                        PayeeName  = settlementAccount.PayeeName,
                                        AccoutType = settlementAccount.AccoutType,
                                        Account    = settlementAccount.Account,
                                        Paytype    = settlementAccount.Pmode,
                                        Settmode   = WithdrawMode.Manual,
                                        Required   = DateTime.Now.AddHours(2),
                                        Suppstatus = 0
                                    };

                                    if (DateTime.Now.Hour > 16)
                                    {
                                        itemInfo.Required = DateTime.Now.AddDays(1);
                                    }

                                    if (scheme.vaiInterface > 0)
                                    {
                                        itemInfo.SuppId     = chnlBLL.GetSupplier(itemInfo.BankCode);
                                        itemInfo.Suppstatus = 1;
                                    }

                                    int result = viviapi.BLL.Finance.Withdraw.Instance.Apply(itemInfo);
                                    itemInfo.ID = result;
                                    if (result > 0)
                                    {
                                        msg = "提现成功";

                                        #region 通过接口提现
                                        if (itemInfo.Suppstatus == 1 &&
                                            itemInfo.SuppId > 0 &&
                                            scheme.tranRequiredAudit == 0)
                                        {
                                            bool audit = viviapi.BLL.Finance.Withdraw.Instance.Audit(itemInfo.Tranno
                                                                                                     , DateTime.Now.ToString("yyyyMMddHHmmssfff")
                                                                                                     , 1
                                                                                                     , "自动确认");

                                            if (audit)
                                            {
                                                viviapi.ETAPI.Common.Withdrawal.InitDistribution(itemInfo);
                                            }
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        msg = "提现失败";
                                    }
                                }
                                else
                                {
                                    msg = "未设置结算账户";
                                }



                                #endregion
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                msg = exception.Message;
            }

            lblMessage.Text = msg;

            string email     = System.Web.Configuration.WebConfigurationManager.AppSettings["SysEmail"];
            string useNotice = System.Web.Configuration.WebConfigurationManager.AppSettings["UseEmailNotice"];
            if (useNotice == "1")
            {
                var emailcom = new EmailSender(email
                                               , "提现通知"
                                               , "ID为" + UserId + "的用户正在申请提现,操作状态:" + msg
                                               , true
                                               , System.Text.Encoding.GetEncoding("gbk"));
                emailcom.Send();
            }
        }
        private unsafe static byte[] ExportCertificatesToBlob(Cryptography.SafeCertStoreHandle safeCertStoreHandle, X509ContentType contentType, string password) {
            Cryptography.SafeCertContextHandle safeCertContextHandle = Cryptography.SafeCertContextHandle.InvalidHandle;
            uint dwSaveAs = CAPI.CERT_STORE_SAVE_AS_PKCS7;
            byte[] pbBlob = null;
            CAPI.CRYPTOAPI_BLOB DataBlob = new CAPI.CRYPTOAPI_BLOB();
            SafeLocalAllocHandle pbEncoded = SafeLocalAllocHandle.InvalidHandle;

            switch(contentType) {
            case X509ContentType.Cert:
                safeCertContextHandle = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, safeCertContextHandle);
                if (safeCertContextHandle != null && !safeCertContextHandle.IsInvalid) {
                    CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle());
                    pbBlob = new byte[pCertContext.cbCertEncoded];
                    Marshal.Copy(pCertContext.pbCertEncoded, pbBlob, 0, pbBlob.Length);
                }
                break;

            case X509ContentType.SerializedCert:
                safeCertContextHandle = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, safeCertContextHandle);
                uint cbEncoded = 0;
                if (safeCertContextHandle != null && !safeCertContextHandle.IsInvalid) {
                    if (!CAPI.CertSerializeCertificateStoreElement(safeCertContextHandle, 
                                                                   0, 
                                                                   pbEncoded, 
                                                                   new IntPtr(&cbEncoded))) 
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    pbEncoded = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbEncoded));
                    if (!CAPI.CertSerializeCertificateStoreElement(safeCertContextHandle, 
                                                                   0, 
                                                                   pbEncoded, 
                                                                   new IntPtr(&cbEncoded)))
                        throw new CryptographicException(Marshal.GetLastWin32Error());

                    pbBlob = new byte[cbEncoded];
                    Marshal.Copy(pbEncoded.DangerousGetHandle(), pbBlob, 0, pbBlob.Length);
                }
                break;

            case X509ContentType.Pkcs12:
                if (!CAPI.PFXExportCertStore(safeCertStoreHandle, 
                                             new IntPtr(&DataBlob), 
                                             password, 
                                             CAPI.EXPORT_PRIVATE_KEYS | CAPI.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY))
                    throw new CryptographicException(Marshal.GetLastWin32Error());

                pbEncoded = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(DataBlob.cbData));
                DataBlob.pbData = pbEncoded.DangerousGetHandle();
                if (!CAPI.PFXExportCertStore(safeCertStoreHandle, 
                                             new IntPtr(&DataBlob),
                                             password, 
                                             CAPI.EXPORT_PRIVATE_KEYS | CAPI.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY))
                    throw new CryptographicException(Marshal.GetLastWin32Error());

                pbBlob = new byte[DataBlob.cbData];
                Marshal.Copy(DataBlob.pbData, pbBlob, 0, pbBlob.Length);
                break;

            case X509ContentType.SerializedStore:
                // falling through
            case X509ContentType.Pkcs7:
                if (contentType == X509ContentType.SerializedStore)
                    dwSaveAs = CAPI.CERT_STORE_SAVE_AS_STORE;

                // determine the required length
                if (!CAPI.CertSaveStore(safeCertStoreHandle, 
                                        CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, 
                                        dwSaveAs, 
                                        CAPI.CERT_STORE_SAVE_TO_MEMORY, 
                                        new IntPtr(&DataBlob), 
                                        0)) 
                    throw new CryptographicException(Marshal.GetLastWin32Error());

                pbEncoded = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(DataBlob.cbData));
                DataBlob.pbData = pbEncoded.DangerousGetHandle();
                // now save the store to a memory blob
                if (!CAPI.CertSaveStore(safeCertStoreHandle, 
                                        CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, 
                                        dwSaveAs, 
                                        CAPI.CERT_STORE_SAVE_TO_MEMORY, 
                                        new IntPtr(&DataBlob), 
                                        0)) 
                    throw new CryptographicException(Marshal.GetLastWin32Error());

                pbBlob = new byte[DataBlob.cbData];
                Marshal.Copy(DataBlob.pbData, pbBlob, 0, pbBlob.Length);
                break;

            default:
                throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidContentType));
            }

            pbEncoded.Dispose();
            safeCertContextHandle.Dispose();

            return pbBlob;
        }
Example #50
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="newemail"></param>
        /// <returns></returns>
        public string SendChange_email(string newemail)
        {
            string message;

            try
            {
                string tempcontent = Helper.GetEmailChangeTemp();
                if (!string.IsNullOrEmpty(tempcontent))
                {
                    var itemInfo = new EmailCheckInfo
                    {
                        userid    = CurrentUser.ID,
                        status    = EmailCheckStatus.提交中,
                        addtime   = DateTime.Now,
                        checktime = DateTime.Now,
                        email     = newemail,
                        typeid    = EmailCheckType.修改,
                        Expired   = DateTime.Now.AddDays(7)
                    };

                    var bll    = new EmailCheck();
                    int result = bll.Add(itemInfo);
                    if (result > 0)
                    {
                        string parms       = string.Format("id={0}&", result);
                        string securityKey = HttpUtility.UrlEncode(Cryptography.RijndaelEncrypt(parms));
                        string verifyurl   = GetVerifyUrl(securityKey);

                        tempcontent = tempcontent.Replace("{#personName#}", CurrentUser.full_name);
                        tempcontent = tempcontent.Replace("{#useremail#}", newemail);
                        string sitename   = "";
                        string sitedomain = "";
                        if (webInfo != null)
                        {
                            sitename   = webInfo.Name;
                            sitedomain = webInfo.Domain;
                        }
                        tempcontent = tempcontent.Replace("{#sitename#}", sitename);
                        tempcontent = tempcontent.Replace("{#sitedomain#}", sitedomain);
                        tempcontent = tempcontent.Replace("{#verify_email#}", verifyurl);

                        var emailcom = new EmailHelper(CurrentUser.Email
                                                       , CurrentUser.Email + "修改邮箱"
                                                       , tempcontent
                                                       , true
                                                       , System.Text.Encoding.Default);

                        emailcom.Send2();

                        message = "操作成功";
                    }
                    else
                    {
                        message = "系统出错,请联系管理员";
                    }
                }
                else
                {
                    message = "系统出错,未找到邮件模版!";
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return(message);
        }
        private static void FindByCert(Cryptography.SafeCertStoreHandle safeSourceStoreHandle, 
                                        uint dwFindType, 
                                        IntPtr pvFindPara, 
                                        bool validOnly, 
                                        FindProcDelegate pfnCertCallback1, 
                                        FindProcDelegate pfnCertCallback2, 
                                        object pvCallbackData1, 
                                        object pvCallbackData2,
                                        Cryptography.SafeCertStoreHandle safeTargetStoreHandle) {

            int hr = CAPI.S_OK;

            Cryptography.SafeCertContextHandle pEnumContext = Cryptography.SafeCertContextHandle.InvalidHandle;
            pEnumContext = CAPI.CertFindCertificateInStore(safeSourceStoreHandle, 
                                                           CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
                                                           0, 
                                                           dwFindType,
                                                           pvFindPara,
                                                           pEnumContext);

            while (pEnumContext != null && !pEnumContext.IsInvalid) {
                if (pfnCertCallback1 != null) {
                    hr = pfnCertCallback1(pEnumContext, pvCallbackData1);
                    if (hr == CAPI.S_FALSE) {
                        if (pfnCertCallback2 != null) 
                            hr = pfnCertCallback2(pEnumContext, pvCallbackData2);

                        if (hr == CAPI.S_FALSE) // skip this certificate
                            goto skip;
                    }

                    if (hr != CAPI.S_OK)
                        break;
                }

                if (validOnly) {
                    hr = X509Utils.VerifyCertificate(pEnumContext, 
                                           null,
                                           null,
                                           X509RevocationMode.NoCheck,
                                           X509RevocationFlag.ExcludeRoot,
                                           DateTime.Now,
                                           new TimeSpan(0, 0, 0), // default
                                           null,
                                           new IntPtr(CAPI.CERT_CHAIN_POLICY_BASE), 
                                           IntPtr.Zero);
                    if (hr == CAPI.S_FALSE) // skip this certificate
                        goto skip;

                    if (hr != CAPI.S_OK)
                        break;
                }

                //
                // We use CertAddCertificateLinkToStore to keep a link to the original store, so any property changes get
                // applied to the original store. This has a limit of 99 links per cert context however.
                //

                if (!CAPI.CertAddCertificateLinkToStore(safeTargetStoreHandle, 
                                                        pEnumContext, 
                                                        CAPI.CERT_STORE_ADD_ALWAYS,
                                                        Cryptography.SafeCertContextHandle.InvalidHandle)) {
                    hr = Marshal.GetHRForLastWin32Error();
                    break;
                }

skip:
                // CertFindCertificateInStore always releases the context regardless of success 
                // or failure so we don't need to manually release it
                GC.SuppressFinalize(pEnumContext);

                pEnumContext = CAPI.CertFindCertificateInStore(safeSourceStoreHandle, 
                                                               CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
                                                               0, 
                                                               dwFindType, 
                                                               pvFindPara,
                                                               pEnumContext);
            }

            if (pEnumContext != null && !pEnumContext.IsInvalid)
                pEnumContext.Dispose();

            if (hr != CAPI.S_FALSE && hr != CAPI.S_OK)
                throw new CryptographicException(hr);
        }
Example #52
0
        public bool Connect()
        {
            SQLiteCommand    sqlite_cmd;
            SQLiteDataReader sqlite_datareader;
            String           key = "trugLk";

            try
            {
                String path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                myconn = new SQLiteConnection("DataSource=" + path + "\\LiberB1\\LiberB1DB.db;");
                myconn.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error 501 - " + ex.Message);
            }


            sqlite_cmd             = myconn.CreateCommand();
            sqlite_cmd.CommandText = "SELECT [ConexaoLiber],[userLiber],[PassLiber],[PortLiber]" +
                                     "from[Connection]; ";

            sqlite_datareader = sqlite_cmd.ExecuteReader();
            sqlite_datareader.Read();

            endpoint  = sqlite_datareader.GetString(0);
            LiberUser = sqlite_datareader.GetString(1);
            LiberPass = Cryptography.Decrypt(sqlite_datareader.GetString(2), key);
            LiberPort = sqlite_datareader.GetString(3);

            myconn.Close();
            //MessageBox.Show(endpoint + " ---- " + LiberUser + " ---- " + LiberPass + " ---- " + LiberPort);

            //testar a conexao com o rabbit
            ConnectionFactory factory = new ConnectionFactory
            {
                UserName    = LiberUser,
                Password    = LiberPass,
                VirtualHost = "/",
                Port        = System.Convert.ToInt32(LiberPort),
                HostName    = endpoint
            };

            try
            {
                conn = factory.CreateConnection();

                //IModel channel = conn.CreateModel();

                //MessageBox.Show("Conectado com sucesso!");

                //channel.Close();
                //conn.Close();

                //MyLogger.Log("Rabbit conectado");

                return(true);
            }
            catch (Exception ex)
            {
                MyLogger.Log("Falha na conexão - " + ex);
                MessageBox.Show("Falha na conexão - " + ex);
                return(false);
            }
        }
        private static unsafe int FindSerialNumberCallback(Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData) {
            CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle());
            CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO));

            byte[] hex = new byte[pCertInfo.SerialNumber.cbData];
            Marshal.Copy(pCertInfo.SerialNumber.pbData, hex, 0, hex.Length);

            int size = X509Utils.GetHexArraySize(hex);
            byte[] serialNumber = (byte[]) pvCallbackData;
            if (serialNumber.Length != size)
                return CAPI.S_FALSE;

            for (int index = 0; index < serialNumber.Length; index++) {
                if (serialNumber[index] != hex[index])
                    return CAPI.S_FALSE;
            }

            return CAPI.S_OK;
        }
        public BINValue this[string path]
        {
            get
            {
                string[] properties = path.Split('/');
                string   property   = properties[0];

                //Build next recursive property path
                string nextPath = string.Empty;
                if (properties.Length != 1)
                {
                    for (int i = 1; i < properties.Length; i++)
                    {
                        nextPath += properties[i];

                        if (i + 1 != properties.Length)
                        {
                            nextPath += '/';
                        }
                    }
                }

                //Determine the property type
                if (Regex.IsMatch(property, @"^\[\d+\]"))
                {
                    int valueIndex = int.Parse(property.Substring(1, property.IndexOf(']') - 1));

                    return((this.Value as BINContainer).Values[valueIndex]);
                }
                else if (property.Contains('[') && !property.Contains('.'))
                {
                    int startIndex = property.IndexOf('[');
                    int valueIndex = int.Parse(property.Substring(startIndex + 1, property.IndexOf(']') - startIndex - 1));

                    if (this.Type == BINValueType.Container &&
                        (this.Value as BINContainer).EntryType == BINValueType.Embedded ||
                        (this.Value as BINContainer).EntryType == BINValueType.Structure)
                    {
                        BINContainer container = this.Value as BINContainer;

                        return(container.Values[valueIndex]);
                    }
                }
                else if (property.Contains('.'))
                {
                    string[] structureProperties = property.Split('.');
                    string   structureProperty   = structureProperties[0];
                    string   fieldProperty       = structureProperties[1];
                    int?     structureIndex      = null;

                    //Check if structure property has an array index
                    if (structureProperty.Contains('['))
                    {
                        int startIndex = structureProperty.IndexOf('[');
                        structureIndex    = int.Parse(structureProperty.Substring(startIndex + 1, structureProperty.IndexOf(']') - startIndex - 1));
                        structureProperty = structureProperty.Remove(structureProperty.IndexOf('['));
                    }

                    uint structureHash = 0;
                    uint fieldHash;
                    if (structureIndex == null && !uint.TryParse(structureProperty, out structureHash))
                    {
                        structureHash = Cryptography.FNV32Hash(structureProperty);
                    }
                    if (!uint.TryParse(fieldProperty, out fieldHash))
                    {
                        fieldHash = Cryptography.FNV32Hash(fieldProperty);
                    }

                    BINStructure structure  = (structureIndex == null) ? this.Value as BINStructure : (this.Value as BINContainer).Values[(int)structureIndex].Value as BINStructure;
                    BINValue     fieldValue = structure[fieldHash];
                    if (nextPath != string.Empty)
                    {
                        return(structure[fieldHash][nextPath]);
                    }
                    else
                    {
                        return(structure[fieldHash]);
                    }
                }
                else if (this.Type == BINValueType.Map)
                {
                    BINMap map = this.Value as BINMap;

                    if (map.KeyType == BINValueType.Byte)
                    {
                        return(map[map.Values.Keys.Where(x => byte.Parse(property).Equals(x.Value)).First()]);
                    }
                    else if (map.KeyType == BINValueType.UInt16)
                    {
                        return(map[map.Values.Keys.Where(x => ushort.Parse(property).Equals(x.Value)).First()]);
                    }
                    else if (map.KeyType == BINValueType.UInt32)
                    {
                        return(map[map.Values.Keys.Where(x => uint.Parse(property).Equals(x.Value)).First()]);
                    }
                    else if (map.KeyType == BINValueType.UInt64)
                    {
                        return(map[map.Values.Keys.Where(x => ulong.Parse(property).Equals(x.Value)).First()]);
                    }
                    else if (map.KeyType == BINValueType.String)
                    {
                        return(map[map.Values.Keys.Where(x => string.Equals(property, x.Value)).First()]);
                    }
                    else if (map.KeyType == BINValueType.Hash)
                    {
                        return(map[map.Values.Keys.Where(x => uint.Parse(property).Equals(x.Value)).First()]);
                    }
                    else
                    {
                        throw new Exception("Unsupported Map Key Type: " + map.KeyType);
                    }
                }

                return(null);
            }
        }
        private static unsafe int FindTemplateNameCallback(Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData) {
            IntPtr pV1Template = IntPtr.Zero;
            IntPtr pV2Template = IntPtr.Zero;

            CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle());
            CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO));

            pV1Template = CAPI.CertFindExtension(CAPI.szOID_ENROLL_CERTTYPE_EXTENSION,
                                                 pCertInfo.cExtension,
                                                 pCertInfo.rgExtension);
            pV2Template = CAPI.CertFindExtension(CAPI.szOID_CERTIFICATE_TEMPLATE,
                                                 pCertInfo.cExtension,
                                                 pCertInfo.rgExtension);

            if (pV1Template == IntPtr.Zero && pV2Template == IntPtr.Zero)
                return CAPI.S_FALSE;

            if (pV1Template != IntPtr.Zero) {
                CAPI.CERT_EXTENSION extension = (CAPI.CERT_EXTENSION) Marshal.PtrToStructure(pV1Template, typeof(CAPI.CERT_EXTENSION));
                byte[] rawData = new byte[extension.Value.cbData];
                Marshal.Copy(extension.Value.pbData, rawData, 0, rawData.Length);

                uint cbDecoded = 0;
                SafeLocalAllocHandle decoded = null;
                // Decode the extension.
                bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_UNICODE_ANY_STRING), 
                                                rawData,
                                                out decoded,
                                                out cbDecoded);
                if (result) {
                    CAPI.CERT_NAME_VALUE pNameValue = (CAPI.CERT_NAME_VALUE) Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CERT_NAME_VALUE));
                    string s = Marshal.PtrToStringUni(pNameValue.Value.pbData);
                    if (String.Compare(s, (string) pvCallbackData, StringComparison.OrdinalIgnoreCase) == 0)
                        return CAPI.S_OK;
                }
            }

            if (pV2Template != IntPtr.Zero) {
                CAPI.CERT_EXTENSION extension = (CAPI.CERT_EXTENSION) Marshal.PtrToStructure(pV2Template, typeof(CAPI.CERT_EXTENSION));
                byte[] rawData = new byte[extension.Value.cbData];
                Marshal.Copy(extension.Value.pbData, rawData, 0, rawData.Length);

                uint cbDecoded = 0;
                SafeLocalAllocHandle decoded = null;
                // Decode the extension.
                bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_CERTIFICATE_TEMPLATE), 
                                                rawData,
                                                out decoded,
                                                out cbDecoded);
                if (result) {
                    CAPI.CERT_TEMPLATE_EXT pTemplate = (CAPI.CERT_TEMPLATE_EXT) Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CERT_TEMPLATE_EXT));
                    // If we were passed the friendly name, retrieve the value string.
                    string oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, (string)pvCallbackData, Cryptography.OidGroup.Template);
                    if (oidValue == null)
                        oidValue = (string) pvCallbackData;
                    if (String.Compare(pTemplate.pszObjId, oidValue, StringComparison.OrdinalIgnoreCase) == 0)
                        return CAPI.S_OK;
                }
            }

            return CAPI.S_FALSE;
        }
Example #56
0
        public async Task <IActionResult> Put(int id, [FromBody] members entity)
        {
            members ObjectToBeUpdated = null;

            try
            {
                if (string.IsNullOrEmpty(entity.fname) || string.IsNullOrEmpty(entity.lname) || string.IsNullOrEmpty(entity.username) ||
                    string.IsNullOrEmpty(entity.phone) || string.IsNullOrEmpty(entity.email) || entity.agency_id < 1 || entity.role_id < 1)
                {
                    return(new BadRequestObjectResult(new Error(errorEnum.e_badRequest))); // This returns HTTP 404
                }
                //fetch object, assuming it exists
                ObjectToBeUpdated = await agent.Find <members>(id);

                if (ObjectToBeUpdated == null)
                {
                    return(new NotFoundObjectResult(entity));
                }

                if ((!User.IsInRole("Admin") && !User.IsInRole("Manager")) && LoggedInUser().member_id != id)
                {
                    return(new UnauthorizedResult());
                }

                ObjectToBeUpdated.username  = entity.username;
                ObjectToBeUpdated.fname     = entity.fname;
                ObjectToBeUpdated.lname     = entity.lname;
                ObjectToBeUpdated.agency_id = entity.agency_id;
                ObjectToBeUpdated.phone     = entity.phone;
                ObjectToBeUpdated.email     = entity.email;
                ObjectToBeUpdated.emergency_contact_name = (string.IsNullOrEmpty(entity.emergency_contact_name) ?
                                                            ObjectToBeUpdated.emergency_contact_name : entity.emergency_contact_name);
                ObjectToBeUpdated.emergency_contact_phone = (string.IsNullOrEmpty(entity.emergency_contact_phone) ?
                                                             ObjectToBeUpdated.emergency_contact_phone : entity.emergency_contact_phone);

                //last updated parts
                var loggedInMember = LoggedInUser();
                if (loggedInMember == null)
                {
                    return(new BadRequestObjectResult("Invalid input parameters"));
                }

                entity.last_updated    = DateTime.Now;
                entity.last_updated_by = loggedInMember.member_id;

                //admin can only change role
                if (User.IsInRole("Admin"))
                {
                    ObjectToBeUpdated.role_id = entity.role_id;
                }

                //change password if needed
                if (!string.IsNullOrEmpty(entity.password) && !Cryptography
                    .VerifyPassword(Encoding.UTF8.GetString(Convert.FromBase64String(entity.password)),
                                    ObjectToBeUpdated.salt, ObjectToBeUpdated.password))
                {
                    ObjectToBeUpdated.salt     = Cryptography.CreateSalt();
                    ObjectToBeUpdated.password = Cryptography.GenerateSHA256Hash(Encoding.UTF8
                                                                                 .GetString(Convert.FromBase64String(entity.password)), ObjectToBeUpdated.salt);
                    ObjectToBeUpdated.resetFlag = null;
                }//end if

                var x = await agent.Update <members>(id, ObjectToBeUpdated);

                //remove info not relevant
                x.salt     = string.Empty;
                x.password = string.Empty;

                return(Ok(x));
            }
            catch (Exception ex)
            {
                return(await HandleExceptionAsync(ex));
            }
        }
        private static unsafe int FindCertificatePolicyCallback(Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData) {
            string certPolicy = (string) pvCallbackData;
            if (certPolicy.Length == 0)
                return CAPI.S_FALSE;
            CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle());
            CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO));

            IntPtr pExtension = CAPI.CertFindExtension(CAPI.szOID_CERT_POLICIES,
                                                       pCertInfo.cExtension,
                                                       pCertInfo.rgExtension);
            if (pExtension == IntPtr.Zero)
                return CAPI.S_FALSE;

            CAPI.CERT_EXTENSION extension = (CAPI.CERT_EXTENSION) Marshal.PtrToStructure(pExtension, typeof(CAPI.CERT_EXTENSION));
            byte[] rawData = new byte[extension.Value.cbData];
            Marshal.Copy(extension.Value.pbData, rawData, 0, rawData.Length);

            uint cbDecoded = 0;
            SafeLocalAllocHandle decoded = null;
            // Decode the extension.
            bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_CERT_POLICIES), 
                                            rawData,
                                            out decoded,
                                            out cbDecoded);
            if (result) {
                CAPI.CERT_POLICIES_INFO pInfo = (CAPI.CERT_POLICIES_INFO) Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CERT_POLICIES_INFO));
                for (int index = 0; index < pInfo.cPolicyInfo; index++) {
                    IntPtr pPolicyInfoPtr = new IntPtr((long) pInfo.rgPolicyInfo + index * Marshal.SizeOf(typeof(CAPI.CERT_POLICY_INFO)));
                    CAPI.CERT_POLICY_INFO pPolicyInfo = (CAPI.CERT_POLICY_INFO) Marshal.PtrToStructure(pPolicyInfoPtr, typeof(CAPI.CERT_POLICY_INFO));
                    if (String.Compare(certPolicy, pPolicyInfo.pszPolicyIdentifier, StringComparison.OrdinalIgnoreCase) == 0)
                        return CAPI.S_OK;
                }
            }

            return CAPI.S_FALSE;
        }
Example #58
0
        public static IServiceCollection AddJwtAuthentication(this IServiceCollection services)
        {
            var settings = GetAuthoriztaionSettings(services);

            services.AddAuthentication(opt =>
            {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = settings.Issuer,
                    ValidAudience    = settings.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Cryptography.Decrypt(settings.SecretKey)))
                };
            });

            return(services);
        }
        private static unsafe int FindKeyUsageCallback(Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData) {
            CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle());
            uint dwUsages = 0;
            if (!CAPI.CertGetIntendedKeyUsage(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, 
                                              pCertContext.pCertInfo, 
                                              new IntPtr(&dwUsages), 
                                              4 /* sizeof(DWORD) */)) 
                return CAPI.S_OK; // no key usage means it is valid for all key usages.

            uint dwCheckUsage = Convert.ToUInt32(pvCallbackData, null);
            if ((dwUsages & dwCheckUsage) == dwCheckUsage)
                return CAPI.S_OK;

            return CAPI.S_FALSE;
        }
Example #60
0
        private void SignIn()
        {
            string message = "";

            string userName   = XRequest.GetString("username");
            string passWord   = XRequest.GetString("password");
            string code       = XRequest.GetString("CCode");
            string RememberMe = WebBase.GetFormString("RememberMe", "");

            if (string.IsNullOrEmpty(code))
            {
                message = ("请输入验证码!");
            }
            else if (string.IsNullOrEmpty(userName))
            {
                message = ("请输入代理账号!");
            }
            else if (string.IsNullOrEmpty(passWord))
            {
                message = ("请输入代理密码!");
            }
            else
            {
                message = WebUtility.CheckValiDateCode(code);
            }

            if (string.IsNullOrEmpty(message))
            {
                string lastLoginIp      = ServerVariables.TrueIP;
                string lastLoginAddress = WebUtility.GetIPAddress(lastLoginIp);

                message = viviapi.BLL.User.Login.SignIn(0, 1, userName, Cryptography.MD5(passWord), lastLoginIp,
                                                        lastLoginAddress);

                if (message == "success")
                {
                    if (viviapi.BLL.User.Login.CurrentMember.UserType == UserTypeEnum.代理)
                    {
                        if (RememberMe != null)
                        {
                            HttpCookie hc = new HttpCookie("yklm_agent");
                            DateTime   dt = DateTime.Now;
                            TimeSpan   ts = new TimeSpan(90, 0, 0, 0, 0); //过期时间为1分钟
                            hc.Expires = dt.Add(ts);                      //设置过期时间

                            hc.Values.Add("username", userName);

                            Response.AppendCookie(hc);
                        }
                        else
                        {
                            HttpCookie hc = new HttpCookie("yklm_agent");
                            hc.Expires = DateTime.Now.AddMonths(-24);
                            Response.Cookies.Add(hc);
                        }
                    }
                    else
                    {
                        message = ("非代理权限,无法登录!");
                    }
                }
            }

            if (message == "success")
            {
                Response.Redirect("main.aspx");
            }
            else
            {
                ShowMessageBox(message);
            }
        }