示例#1
0
        public ActionResult Login(LoanViewModel lvm)
        {
            try
            {
                users.Email   = lvm.AccountsModel.Email;
                users.pasword = lvm.AccountsModel.pasword;
                var EncrypPassword = new CryptographyManager().ComputeHash(users.pasword, HashName.SHA256);
                users.pasword = EncrypPassword;

                var valid = DataReaders.loggedIn(users.Email, EncrypPassword);

                if (valid == true)
                {
                    if (users.Email != null)
                    {
                        Session["id"]   = users.Email;
                        Session["User"] = "******" + Session["id"];
                        var    LoggedInuser = new LogginHelper();
                        string user         = LoggedInuser.LoggedInUser();
                        return(View("index"));
                    }
                    else
                    {
                        ViewBag.Message = "Invalid Details ! Try Again";
                        return(View("Signin"));
                    }
                }
                return(View("Signin"));
            }
            catch (Exception ex)
            {
                WebLog.Log(ex.Message.ToString());
                return(null);
            }
        }
示例#2
0
        public string GetCustomerDetails(CustomerObj cusObj)
        {
            try
            {
                dynamic obj = new JObject();

                string agentID    = ConfigurationManager.AppSettings["agentID"];
                string agentKey   = ConfigurationManager.AppSettings["agentKey"];
                var    MerchantFk = cusObj.MerchantFk;
                var    MeterType  = cusObj.MeterType;
                obj.agentkey    = agentKey;
                obj.agentID     = agentID;
                obj.customerId  = cusObj.CustomerID;
                obj.MerchantFK  = MerchantFk;
                obj.accountType = MeterType;


                var plainText = (agentID + agentKey + obj.customerId);
                var builder   = new StringBuilder();
                builder.Append(agentID).Append(agentKey).Append(obj.customerId);

                var hash = new CryptographyManager().ComputeHash(builder.ToString(), HashName.SHA256);
                obj.hashValue = hash;
                var json    = obj.ToString();
                var PostUrl = ConfigurationManager.AppSettings["ValidateCustomerID"];
                var data    = Utility.DoPosts(json, $"{PostUrl}");
                return(data);
            }
            catch (Exception ex)
            {
                WebLog.Log(ex.Message.ToString());
                return(null);
            }
        }
示例#3
0
        public static string PostBuySubcriptionJson(CustomerObj cusObj)
        {
            try
            {
                string agentID  = ConfigurationManager.AppSettings["agentID"];
                string agentKey = ConfigurationManager.AppSettings["agentKey"];

                dynamic obj       = new JObject();
                string  valueTime = DateTime.Now.ToString("Hmmss");
                obj.refNumber    = "Agent" + DateTime.Now.ToString("yyyyMMdd") + valueTime;
                obj.customername = cusObj.CustomerName;
                obj.amount       = cusObj.Amount;
                obj.agentkey     = agentKey;
                obj.agentID      = agentID;
                obj.customerId   = cusObj.CustomerID;
                obj.MerchantFK   = cusObj.MerchantFk;
                obj.accountType  = cusObj.MeterType;

                var plainText = (agentID + agentKey + obj.customerId);
                var builder   = new StringBuilder();
                builder.Append(agentID).Append(agentKey).Append(obj.customerId);
                var hash = new CryptographyManager().ComputeHash(builder.ToString(), HashName.SHA256);
                obj.hashValue = hash;
                var json    = obj.ToString();
                var PostUrl = ConfigurationManager.AppSettings["Buypower"];
                var data    = Utility.DoPosts(json, $"{PostUrl}");
                return(data);
            }
            catch (Exception ex)
            {
                WebLog.Log(ex.Message.ToString());
                //Label1.Text = ex.Message.ToString();
                return(null);
            }
        }
        public void SetUp()
        {
            hashProviders           = new Dictionary <string, IHashProvider>();
            symmetricCrytoProviders = new Dictionary <string, ISymmetricCryptoProvider>();

            CreateKeyFile(symmetricKeyFile);
            CreateKeyFile(keyedHashKeyFile);

            configSource = ConfigurationSourceFactory.Create();

            HashProviderFactory factory = new HashProviderFactory(configSource);

            defaultHashProvider = factory.Create(hashInstance);
            hashProviders.Add(hashInstance, defaultHashProvider);

            SymmetricCryptoProviderFactory symmfactory = new SymmetricCryptoProviderFactory(configSource);

            defaultSymmetricCryptoProvider  = symmfactory.Create(symmInstance);
            algorithSymmetricCryptoProvider = symmfactory.Create(symmetricAlgorithm1);

            symmetricCrytoProviders.Add(symmInstance, defaultSymmetricCryptoProvider);
            symmetricCrytoProviders.Add(symmetricAlgorithm1, algorithSymmetricCryptoProvider);

            var container = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

            cryptographyManager = container.GetInstance <CryptographyManager>();
        }
        public void DeleteKeyFile()
        {
            File.Delete(symmetricKeyFile);
            File.Delete(keyedHashKeyFile);

            cryptographyManager = null;
        }
示例#6
0
        public static string GetSessionID()
        {
            try
            {
                string agentid      = ConfigurationManager.AppSettings["agentID"];
                string agentKey     = ConfigurationManager.AppSettings["agentKey"];
                string EmailAddress = ConfigurationManager.AppSettings["agentEmail"];

                var signaturetext = new StringBuilder();
                signaturetext.Append(agentid).Append(agentKey).Append(EmailAddress);

                var signature = new CryptographyManager().ComputeHash(signaturetext.ToString(), HashName.SHA512);

                dynamic obj = new JObject();
                obj.agentkey  = agentKey;
                obj.signature = signature;

                var json    = obj.ToString();
                var PostUrl = ConfigurationManager.AppSettings["GetSessionID"];

                PostUrl = System.Configuration.ConfigurationManager.AppSettings["GetSessionID"];

                PostUrl = PostUrl.Replace("{$agentid}", agentid.ToString()).Trim().Replace("{$agentkey}", agentKey.ToString()).Trim().Replace("{$signature}", signature.ToString()).Trim();

                var     data      = Utility.DoGet1($"{PostUrl}", agentid, agentKey, signature);
                dynamic session   = JObject.Parse(data);
                var     sessionID = session?.sessionid;
                return(sessionID);
            }
            catch (Exception ex)
            {
                WebLog.Log(ex.Message.ToString());
                return(null);
            }
        }
        public static IAppBuilder UseConsulRegistration(this IAppBuilder builder,
                                                        string serviceName,
                                                        string serviceCategory,
                                                        string localAddress,
                                                        int port)
        {
            // 服务注册
            var localImpls      = builder.ServiceProvider.GetServices <IServiceActor <AmpMessage> >();
            var serviceRegistor = builder.ServiceProvider.GetRequiredService <IServiceRegistrationProvider>();

            foreach (var actors in localImpls)
            {
                string      hashId = CryptographyManager.Md5Encrypt(localAddress + port);
                ServiceMeta meta   = new ServiceMeta
                {
                    Id          = hashId + "$" + actors.Id.Split('$')[0], //还要根据IP和端口添加一个MD5
                    ServiceName = serviceName,
                    IPAddress   = localAddress,
                    Port        = port,
                    Tags        = new string[] { serviceCategory }
                };

                serviceRegistor.RegisterAsync(meta).Wait();
            }
            return(builder);
        }
示例#8
0
        /// <summary>
        /// Updates the user password and salt.
        /// </summary>
        /// <param name="userId">The user's id.</param>
        /// <param name="oldPassword">The old password which should be updated.</param>
        /// <param name="newPassword">The new password for user.</param>
        /// <exception cref="System.Security.Authentication.AuthenticationException">Invalid email or password.</exception>
        public void UpdateUserCredentials(int userId, string oldPassword, string newPassword)
        {
            Log.DebugFormat("Begin UpdateUserCredentials(userId:'{0}')", userId);

            string passwordFromDataBase;
            string oldSalt;

            this.GetUserCredentials(userId, out passwordFromDataBase, out oldSalt);

            ICryptographyManager cryptographyManager = new CryptographyManager();

            oldPassword = cryptographyManager.HashPassword(oldPassword, oldSalt);

            if (oldPassword != passwordFromDataBase)
            {
                const string Message = "Invalid email or password.";
                Log.Debug(Message);
                throw new AuthenticationException(Message);
            }

            using (IdeaStorageEntities context = new IdeaStorageEntities())
            {
                USER user = context.USERS.Single(u => u.UserId == userId);
                user.Salt     = cryptographyManager.CreateSalt(12);
                user.Password = cryptographyManager.HashPassword(newPassword, user.Salt);
                context.SaveChanges();
            }

            Log.DebugFormat("Credentials updated for user with ID:'{0}'", userId);
        }
示例#9
0
        /// <summary>
        /// Creates the user using model and password string.
        /// </summary>
        /// <param name="newUser">Model of the new user.</param>
        /// <param name="password">The string with password for new user.</param>
        /// <returns>Id of newly created user.</returns>
        public int CreateUser(User newUser, string password)
        {
            Log.DebugFormat("Begin CreateUser('{0}')", newUser);
            UserValidator userValidator = new UserValidator();

            userValidator.ValidateAndThrow(newUser);

            if (this.FindUserByEmail(newUser.Email) != null)
            {
                string message = string.Format("User with email:'{0}' already exists in data base.", newUser.Email);
                Log.Debug(message);
                throw new DuplicateEntityException(message);
            }

            using (IdeaStorageEntities context = new IdeaStorageEntities())
            {
                ICryptographyManager cryptography = new CryptographyManager();
                string salt = cryptography.CreateSalt(12);
                USER   user = new USER
                {
                    FirstName  = newUser.FirstName,
                    SecondName = newUser.SecondName,
                    IsDeleted  = newUser.IsDeleted,
                    Email      = newUser.Email.ToLower(),
                    Salt       = salt,
                    Password   = cryptography.HashPassword(password, salt)
                };

                context.USERS.Add(user);
                context.SaveChanges();
                Log.DebugFormat("Created user's ID:'{0}'", user.UserId);
                return(user.UserId);
            }
        }
示例#10
0
        public override async Task <VoidRsp> CreateAsync(UserReq user)
        {
            VoidRsp rsp = new VoidRsp();

            rsp.Status  = 0;
            rsp.Message = "test";
            try
            {
                Logger.Debug("receive CreateAsync,data=" + Google.Protobuf.JsonFormatter.Default.Format(user));

                UserReq existing = await this._repo.FindByNameAsync(user.Account);

                if (existing != null)
                {
                    Logger.Debug("user already exists:{0}", user.Account);
                }
                Assert.IsNotNull(existing, "user already exists:" + user.Account);

                user.Password = CryptographyManager.Md5Encrypt(user.Account + "$" + user.Password);
                Logger.Debug("saving db");
                await this._repo.SaveUserAsync(user);

                Logger.Debug("saving db success");
            }
            catch (Exception ex) {
                rsp.Status  = -1;
                rsp.Message = ex.Message;
            }

            return(rsp);
        }
        /// <summary>
        /// This method reads and decrypts the values
        /// in the app.config appSettings section.
        /// </summary>
        /// <param name="settingName"></param>
        /// <returns></returns>
        private string ReadAppSetting(string settingName)
        {
            // initial value
            string settingValue = null;

            try
            {
                // if UseEncryption is true and the EncryptionKey exists
                if ((UseEncryption) && (HasEncryptionKey))
                {
                    // encrypted value
                    string encryptedValue = ConfigurationManager.AppSettings[settingName].ToString();

                    // now decrypt value with EncryptionKey
                    settingValue = CryptographyManager.DecryptString(encryptedValue, this.EncryptionKey);
                }
                else
                {
                    // read the setting value as is
                    settingName = ConfigurationManager.AppSettings[settingName].ToString();
                }
            }
            catch (Exception error)
            {
                // set the last error
                this.LastError = error;
            }

            // return value
            return(settingValue);
        }
        public void CreateSalt_SpecificSize_CorrectStringLengthIsReturned()
        {
            ICryptographyManager cryptographyManager = new CryptographyManager();
            string salt = cryptographyManager.CreateSalt(12);

            Assert.AreEqual(16, salt.Length);
        }
        /// <summary>
        /// TODO:  ipv4  protocol
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task WriteDataWithTrojanProtocolHead(byte[] data, int offset, int size)
        {
            using (var stream = new MemoryStream())
                using (var writer = new BinaryWriter(stream))
                {
                    var ss = CryptographyManager.SH224(_trojanClientPass).ToHexString();
                    writer.Write(Encoding.UTF8.GetBytes(ss));
                    writer.Write(CRLF);
                    writer.Write((byte)Command.Connect);
                    writer.Write((byte)AddressType.Domain);
                    writer.Write((byte)_targetHost.Length);
                    writer.Write(Encoding.UTF8.GetBytes(_targetHost));
                    writer.Write(IPAddress.HostToNetworkOrder((short)_targetPot));
                    writer.Write(CRLF);
                    writer.Write(data, offset, size);
                    // it always true because we use MemoryStream(int capacity) constructor
                    stream.TryGetBuffer(out var buffer);

                    await((SslStream)this.OutStream).WriteAsync(buffer.Array, buffer.Offset, buffer.Count);



                    _handshakeComplete = true;
                }
        }
示例#14
0
        protected void ProcessResponse()
        {
            var trxRef    = Request.QueryString["trxRef"];
            var trxToken  = Request.QueryString["trxToken"];
            var SecretKey = ConfigurationManager.AppSettings["SecretKey"];
            TransactionalInformation trans;

            try
            {
                dynamic obj = new JObject();
                obj.trxRef   = trxRef.Trim();
                obj.trxToken = trxToken.Trim();
                var json = obj.ToString();
                // string url = "http://www.paytrx.org/api/web/GetTransactionRecord";
                string url = "http://paytrx.net/api/web/GetTransactionRecord";

                //re-query payment gateway for the transaction.
                var reqData = "{\"TrxRef\":\"" + trxRef + "\"" + ",\"TrxToken\":\"" + trxToken + "\"}";
                //  var url = ConfigurationManager.AppSettings["FlutterWave_Requery"];
                //var url = FlutteWaveEngine.FlutterWaveRequery;
                string serverResponse = string.Empty;

                var plainText = (trxRef + trxToken + SecretKey);

                var hash   = new CryptographyManager().ComputeHash(plainText, HashName.SHA256);
                var isPaid = PaymentRequery(reqData, url, hash, out serverResponse, out trans);
                var jvalue = JObject.Parse(serverResponse);

                dynamic jvalues = JObject.Parse(serverResponse);
                if (jvalue != null && $"{jvalues?.data?.resp_code}".ToLower() == "00")
                {
                    AgentAccount AgtAccount = new AgentAccount();
                    string       user       = LoggedInuser.LoggedInUser();
                    if (user != null)
                    {
                        int userid = DataReaders.GetUserIdByEmail(user);
                        AgtAccount.AgentUser_FK    = userid;
                        AgtAccount.Credit          = jvalues?.data?.amount;
                        AgtAccount.Debit           = 0;
                        AgtAccount.ReferenceNumber = jvalues?.data?.trxref;
                        AgtAccount.TranxDate       = jvalues?.data?.created_at;
                        AgtAccount.ValueDate       = DateTime.Now.ToString("yyyy:mm:dd");
                        AgtAccount.ValueTime       = DateTime.Now.ToString("HH:mm:ss");
                        db.AgentAccounts.Add(AgtAccount);
                        db.SaveChanges();
                        TempData["paymentmsg"] = "Payment Not Succesfull";
                    }
                }
                else
                if (jvalue != null && $"{jvalues?.data?.resp_code}".ToLower() != "00")
                {
                    //var hash = ComputeHash(plainText);
                    TempData["Message"] = "Payment Not Succesfull";
                }
            }
            catch (Exception ex)
            {
                //lblStatusMsg.Text = ex.Message.ToString();
            }
        }
示例#15
0
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="request">注册用户的请求</param>
        /// <returns></returns>
        public override async Task <RpcResult <RegisterRsp> > RegisterAsync(RegisterReq request)
        {
            var res = new RpcResult <RegisterRsp>();
            var rsp = new RegisterRsp();

            bool isvalid = ValidateRegisterInfo(request, out string errorMsg);

            if (!isvalid)
            {
                res.Code = ErrorCodes.PARAMS_VALIDATION_FAIL;
                res.Data.ReturnMessage = errorMsg;
                return(res);
            }

            var user = new UserInfo();

            user.Account    = request.Account;
            user.FullName   = request.FullName;
            user.Password   = CryptographyManager.Md5Encrypt(user.Account + request.Password);
            user.IsAdmin    = false;
            user.UpdateTime = DateTime.Now;
            user.CreateTime = DateTime.Now;
            var userId = await this._userRepo.InsertAsync(user);

            rsp.UserId = (int)userId;

            return(res);
        }
        /// <summary>
        /// This method reads and decrypts the values
        /// in the app.config appSettings section.
        /// </summary>
        /// <param name="settingName"></param>
        /// <returns></returns>
        private bool ReadBooleanAppSetting(string settingName, bool defaultValue)
        {
            // initial value
            bool settingValue = defaultValue;

            try
            {
                // encrypted value
                string encryptedValue = ConfigurationManager.AppSettings[settingName].ToString();

                // now decrypt value
                settingValue = Convert.ToBoolean(CryptographyManager.DecryptString(encryptedValue));
            }
            catch (Exception error)
            {
                // If ErrorProcessor exists
                if (this.ErrorProcessor != null)
                {
                    // locals
                    string methodName = "ReadAppSetting";
                    string objectName = "ApplicationLogicComponent.StartUp.RADApplicationConfiguration";

                    // Log the current error
                    this.ErrorProcessor.LogError(methodName, objectName, error);
                }
            }

            // return value
            return(settingValue);
        }
示例#17
0
        public string payData(dynamic cusObj)
        {
            try
            {
                dynamic obj          = new JObject();
                dynamic headervalues = new JObject();
                string  agentid      = ConfigurationManager.AppSettings["agentID"];
                string  agentKey     = ConfigurationManager.AppSettings["agentKey"];
                var     email        = ConfigurationManager.AppSettings["agentEmail"];
                //obj.agentkey = agentKey;

                obj.customerId    = cusObj.CustomerID;
                obj.customerName  = cusObj.CustomerName;
                obj.bundleType    = cusObj.ServiceDetails;
                obj.amount        = cusObj.Amount;
                obj.CustomerPhone = cusObj.CustomerPhone;
                obj.refNumber     = cusObj.ReferenceNumber;
                obj.MerchantFK    = cusObj.Merchant_FK;

                // for Payload
                var hashValue = (agentid + agentKey + obj.customerId + obj.refNumber);

                hashValue = new CryptographyManager().ComputeHash(hashValue.ToString(), HashName.SHA512);

                //for header
                //var builder = new StringBuilder();
                //builder.Append(agentid).Append(agentKey).Append(obj.customerId).Append(obj.Amount);

                //var hash = new CryptographyManager().ComputeHash(builder.ToString(), HashName.SHA512);


                //For The Signature
                string customerId    = obj.customerId;
                var    signaturetext = new StringBuilder();
                signaturetext.Append(agentid).Append(agentKey).Append(email);

                var signature = new CryptographyManager().ComputeHash(signaturetext.ToString(), HashName.SHA512);


                obj.hashValue = hashValue;
                var json = obj.ToString();
                WebLog.Log("BuyData" + json);
                string sessionID = Paytv.GetSessionID();
                WebLog.Log("SessionID" + sessionID);
                var PostUrl = ConfigurationManager.AppSettings["BuyData"];
                WebLog.Log("BuyData" + json);
                var data = Utility.DoPosts1(json, $"{PostUrl}", agentid, agentKey, signature, sessionID);


                WebLog.Log("BuyData" + json);
                WebLog.Log("PostUrl" + PostUrl + agentid + agentKey);
                return(data);
            }
            catch (Exception ex)
            {
                WebLog.Log(ex.Message.ToString());
                return(null);
            }
        }
        public void CreateSalt_SimilarCondition_SaltIsUnique()
        {
            ICryptographyManager cryptographyManager = new CryptographyManager();
            string salt1 = cryptographyManager.CreateSalt(12);
            string salt2 = cryptographyManager.CreateSalt(12);

            Assert.AreNotEqual(salt1, salt2);
        }
 /// <summary>
 /// The constructor takes more than one parameter
 /// as oppose to only one parameter is the bare bone Thread
 /// class. This allow we to perform some additional service
 /// based on the additional parameters, in our case, we will pass
 /// the configuration data that contains the user account information
 /// which is later used to perform the thread's security switch
 /// </summary>
 /// <param name="start">the ThreadStart delegate for the target method</param>
 /// <param name="xml">the configuraiton data contains the user account information</param>
 public SecuritySwitchThread(ThreadStart start, RunAs runAs, CryptographyManager crypto)
 {
     Crypto          = crypto;
     serviceDelegate = start;
     RunAs           = runAs;
     //create a new thread that calls the WrappingMethod
     newT = new Thread(new ThreadStart(WrappingMethod));
 }
示例#20
0
        public static Class.Usuarios Actualizar(Class.Usuarios model)
        {
            var db = new TemplateEntities1();

            if (model.UsuarioId == null)
            {
                var usuarioRecuperado = db.Usuarios.FirstOrDefault(x => x.Nombre == model.Nombre);
                if (usuarioRecuperado == null)
                {
                    var siguienteUsuario = 1;
                    if (db.Usuarios.Any())
                    {
                        siguienteUsuario = db.Usuarios.Max(x => x.UsuarioId);
                    }


                    var nuevoUsuario = db.Usuarios.Create();
                    nuevoUsuario.Nombre          = model.Nombre;
                    nuevoUsuario.NombreDeUsuario = "@" + model.Nombre.Replace(" ", string.Empty).ToLower() + (siguienteUsuario + 1);
                    nuevoUsuario.Password        = CryptographyManager.ComputeHash("tracker?", "SHA512", null);
                    nuevoUsuario.ApellidoPaterno = model.ApellidoPaterno;
                    nuevoUsuario.ApellidoMaterno = model.ApellidoMaterno;
                    nuevoUsuario.Activo          = model.Activo;
                    nuevoUsuario.RolId           = model.RolId;

                    db.Usuarios.Add(nuevoUsuario);
                    db.SaveChanges();
                    model.UsuarioId = nuevoUsuario.UsuarioId;
                }
                else
                {
                    var usuarioEncontrado = db.Usuarios.Create();
                    usuarioEncontrado.Nombre          = model.Nombre;
                    usuarioEncontrado.NombreDeUsuario = model.NombreDeUsuario;
                    usuarioEncontrado.ApellidoPaterno = model.ApellidoPaterno;
                    usuarioEncontrado.ApellidoMaterno = model.ApellidoMaterno;
                    usuarioEncontrado.Activo          = model.Activo;
                    usuarioEncontrado.RolId           = model.RolId;

                    db.Usuarios.AddOrUpdate(usuarioEncontrado);
                    db.SaveChanges();
                    model.UsuarioId = usuarioEncontrado.UsuarioId;
                }
            }
            else
            {
                var usuarioActualizado = db.Usuarios.First(x => x.UsuarioId == model.UsuarioId);
                usuarioActualizado.Nombre          = model.Nombre;
                usuarioActualizado.NombreDeUsuario = model.NombreDeUsuario;
                usuarioActualizado.ApellidoPaterno = model.ApellidoPaterno;
                usuarioActualizado.ApellidoMaterno = model.ApellidoMaterno;
                usuarioActualizado.Activo          = model.Activo;
                usuarioActualizado.RolId           = model.RolId;

                db.SaveChanges();
            }
            return(Funciones.GetUsuarios(model.UsuarioId));
        }
示例#21
0
 public SessionService(
     CryptographyManager cryptographyManager,
     RedisServer redis,
     IServerConfigService serviceConfigService)
 {
     _cryptographyManager = cryptographyManager;
     _redis = redis;
     _serviceConfigService = serviceConfigService;
 }
        public void HashPassword_AnyInputPassword_44SymbolsOutputHashIsGenerated(string password, int saltSize)
        {
            ICryptographyManager cryptographyManager = new CryptographyManager();

            string salt = cryptographyManager.CreateSalt(256);
            string hash = cryptographyManager.HashPassword(password, salt);

            // Check, that password length is 44 symbols always.
            Assert.AreEqual(44, hash.Length);
        }
示例#23
0
        public string PaySubscription(dynamic payObj, dynamic Phones)
        {
            try
            {
                dynamic payObjs  = new JObject();
                string  payerPwd = new CryptographyManager().ComputeHash(Plaincode, HashName.MD5);
                TransactionNo       = payerId + TransactionNumb() + SerialNum();
                payObjs.CustomerID  = payObj.CustomerID;
                payObjs.ServiceAmt  = payObj.Amount;
                payObjs.Service     = payObj.ServiceDetails;
                payObjs.Bouquet     = payObj.ServiceDetails;
                payObjs.customerTel = Phones.Phone;
                string   methodName = ConfigurationManager.AppSettings["customerPay2"];
                string   Amount     = payObjs.ServiceAmt;
                string   CustomerID = payObjs.CustomerID;
                string   TransacNum = payObj.ReferenceNumber;
                DateTime TrnDate    = (DateTime)payObj.TrnDate;
                //var Dates = Convert.ToString(payObj.TrnDate);
                // var Dates = "2018-11-11 19:32:59";
                var            Dates           = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string         Phone           = Phones.Phone;
                HttpWebRequest request         = CreateWebRequest(methodName);
                XmlDocument    soapEnvelopeXml = new XmlDocument();
                var            xmlObject       = File.ReadAllText(HttpContext.Current.Server.MapPath("/Xmlfiles/CustomerPay.xml"));
                xmlObject = xmlObject.Replace("$payerID", payerId);
                xmlObject = xmlObject.Replace("$payerPwd", payerPwd);
                xmlObject = xmlObject.Replace("$Phone", Phone);
                xmlObject = xmlObject.Replace("$smartCardCode", CustomerID);
                xmlObject = xmlObject.Replace("$fee", Amount);
                xmlObject = xmlObject.Replace("$transactionNo", TransacNum);
                xmlObject = xmlObject.Replace("$transferTime", Dates);
                soapEnvelopeXml.LoadXml(xmlObject);

                using (Stream stream = request.GetRequestStream())
                {
                    soapEnvelopeXml.Save(stream);
                }

                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                    {
                        soapResult = rd.ReadToEnd();
                        returnMsg  = soapResult;
                    }
                }
                return(returnMsg);
            }

            catch (Exception ex)
            {
                Error = ex.Message;
                return(Error);
            }
        }
        public void HashPassword_ConstantPasswordAndSalt_HashIsConstant()
        {
            ICryptographyManager cryptographyManager = new CryptographyManager();

            string       salt     = cryptographyManager.CreateSalt(12);
            const string Password = "******";
            string       hash1    = cryptographyManager.HashPassword(Password, salt);
            string       hash2    = cryptographyManager.HashPassword(Password, salt);

            Assert.AreEqual(hash1, hash2);
        }
        public void HashPassword_AnyInputPassword_HashDoesNotContainInputPassword()
        {
            ICryptographyManager cryptographyManager = new CryptographyManager();

            string       salt     = cryptographyManager.CreateSalt(12);
            const string Password = "******";
            string       hash     = cryptographyManager.HashPassword(Password, salt);

            // Check, that output hash doesn't contain input password in any form.
            Assert.IsFalse(hash.Contains(Password));
        }
示例#26
0
        private void MessageReceived(MessageEventArgs args)
        {
            string message = args.Message;

            // TODO: Decrypt message
            CryptographyManager crypto = EnterpriseLibraryContainer.Current.GetInstance <CryptographyManager>();
            string plainText           = crypto.DecryptSymmetric(symmProvider, message);

            this.txtMessages.AppendText(
                args.Sender + " says: " + plainText + Environment.NewLine);
        }
示例#27
0
        public void CryptographyManagerTest()
        {
            //System.Web.HttpUtility.UrlDecode()
            var aa = Base64Helper.Base64Decode("c2tkZmprc2o=");

            CryptographyManager cryptography = new CryptographyManager();

            string a = cryptography.Encrypt("1");

            string e = cryptography.Decrypt(a);
        }
        /// <inheritdoc />
        public byte[] SignWithCertificate(string message, X509Certificate2 certificate)
        {
            if (certificate.PublicKey.Key.KeySize < ClientCredentialWrapper.MinKeySizeInBits)
            {
                throw new ArgumentOutOfRangeException(nameof(certificate),
                                                      string.Format(CultureInfo.InvariantCulture, MsalErrorMessage.CertificateKeySizeTooSmallTemplate,
                                                                    ClientCredentialWrapper.MinKeySizeInBits));
            }

            return(CryptographyManager.SignWithCertificate(message, certificate));
        }
示例#29
0
        private void GetEncryptedPassword()
        {
            CryptographyManager crypto = EnterpriseLibraryContainer.Current.GetInstance <CryptographyManager>();

            System.Console.Write("\nEnter new password:"******"AesManaged", password);

            System.Console.WriteLine("New encrypted password is: " + encPassword);
            System.Console.ReadKey();
        }
示例#30
0
        public string GetCustomerInfo(CustomerObj _cobj)
        {
            try
            {
                dynamic payObj   = new JObject();
                string  payerPwd = new CryptographyManager().ComputeHash(Plaincode, HashName.MD5);
                TransactionNo     = payerId + TransactionNumb() + SerialNum();//"420020181227072633oNl8R";
                payObj.CustomerID = _cobj.CustomerID;
                //"02146506386";
                payObj.ServiceAmt = _cobj.Amount;
                payObj.Service    = _cobj.Service;
                payObj.Bouquet    = _cobj.Bouquet;
                var    smartCardCode = _cobj.CustomerID;
                string methodName    = ConfigurationManager.AppSettings["querySubscriberInfo"];
                WebLog.Log("method Name :" + methodName.ToString());
                HttpWebRequest request = CreateWebRequest(methodName);
                WebLog.Log("request Url :" + request.RequestUri + request.ServerCertificateValidationCallback);
                XmlDocument soapEnvelopeXml = new XmlDocument();
                var         xmlObject       = File.ReadAllText(HttpContext.Current.Server.MapPath("/Xmlfiles/StattimeGetCustomerInfo.xml"));
                xmlObject = xmlObject.Replace("$payerID", payerId);
                xmlObject = xmlObject.Replace("$payerPwd", payerPwd);
                xmlObject = xmlObject.Replace("$smartCardCode", smartCardCode);
                xmlObject = xmlObject.Replace("$transactionNo", TransactionNo);
                soapEnvelopeXml.LoadXml(xmlObject);
                WebLog.Log("xmlObject:" + xmlObject);
                using (Stream stream = request.GetRequestStream())
                {
                    WebLog.Log("stream:" + stream);
                    soapEnvelopeXml.Save(stream);
                    WebLog.Log("stream:" + stream);
                }

                using (WebResponse response = request.GetResponse())
                {
                    WebLog.Log("response:" + response);
                    using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                    {
                        WebLog.Log("soapResult:" + soapResult);
                        soapResult = rd.ReadToEnd();
                        returnMsg  = soapResult;
                        WebLog.Log("soapResult:" + soapResult);
                        WebLog.Log("returnMsg:" + returnMsg);
                    }
                }
                return(returnMsg);
            }

            catch (Exception ex)
            {
                WebLog.Log(ex.Message.ToString());
                Error = ex.Message;
                return(Error);
            }
        }
示例#31
0
        /// <summary>
        /// Encrypt secret data and create hidden seed
        /// </summary>
        /// <param name="Jdsm"></param>
        /// <returns></returns>
        public JsonDatasetModel Secure(JsonDatasetModel Jdsm)
        {
            //string seed = "1qwsdefcfvffgffg";
            string seed = Guid.NewGuid().ToString();

            string sixteenDigit = seed.Replace("-", "");

            seed = "";
            for (int i = 0; i < sixteenDigit.Length; i = i + 2)
            {
                seed += sixteenDigit[i];
            }


            Repository.Database.ViewsModel.InteractionMasterSet convertedSeed = CreateHiddenSeed(Jdsm, seed);

            CryptographyManager crypto = new CryptographyManager(seed);

            foreach (var categoryList in Jdsm.Categories)
            {
                categoryList.b =  crypto.Encrypt(categoryList.b);
            }

            foreach (var interactionMaster in Jdsm.InteractionMasters)
            {
                interactionMaster.b = crypto.Encrypt(interactionMaster.b);
                interactionMaster.d = crypto.Encrypt(interactionMaster.d);
                interactionMaster.e = crypto.Encrypt(interactionMaster.e);
                interactionMaster.c = crypto.Encrypt(interactionMaster.c);
                interactionMaster.f = crypto.Encrypt(interactionMaster.f);
            }

            foreach (var prescription in Jdsm.Prescriptions)
            {
                prescription.d = crypto.Encrypt(prescription.d);
            }

            Jdsm.InteractionMasters.Add(convertedSeed);

            return Jdsm;
        }
示例#32
0
        public int login(string email, string password)
        {
            int userType = -1;
            connection.Open ();
            CryptographyManager manager = new CryptographyManager ();
            password = manager.CalculateSHA256Hash(password);
            using (var contents = connection.CreateCommand ()) {
                contents.CommandText = "SELECT userType FROM users users inner join account on users.userID = account.userID WHERE email = @email and accountPassword = @accountPassword";

                contents.Parameters.AddWithValue ("@email",email);
                contents.Parameters.AddWithValue ("@accountPassword",  password);

                var dr = contents.ExecuteReader();

                if (dr.Read ()) {
                    userType = Int32.Parse(dr["userType"].ToString());

                }
            }
            connection.Close ();
            return userType;
        }