Пример #1
0
        static void Main(string[] args)
        {
            var cryptString      = new CryptString();
            var input            = "ariba@123123";
            var encryptedString1 = cryptString.EncryptStringToBase64(input,
                                                                     "ERel23H+hkDPmzXDFoxzdB0RpB1DAQtCntjMOXAfkc8=", "ckOtx2apDX2JbizKyGCahg==");
            var decrypted = cryptString.DecryptStringFromBase64(encryptedString1, "ERel23H+hkDPmzXDFoxzdB0RpB1DAQtCntjMOXAfkc8=", "ckOtx2apDX2JbizKyGCahg==");

            Console.WriteLine($"{input.Equals(decrypted)}");
            var key = "b14ca5898a4e4133bbce2ea2315a1916";

            //Console.WriteLine("Please enter a secret key for the symmetric algorithm.");
            //var key = Console.ReadLine();

            Console.WriteLine("Please enter a string for encryption");
            var str             = Console.ReadLine();
            var encryptedString = AesOperation.EncryptString(key, str);

            Console.WriteLine($"encrypted string = {encryptedString}");

            var decryptedString = AesOperation.DecryptString(key, encryptedString);

            Console.WriteLine($"decrypted string = {decryptedString}");

            Console.ReadKey();
        }
 private static string DecryptIfEncrypted(string lFullString)
 {
     try
     {
         return(AesOperation.DecryptString(key, lFullString));
     }
     catch (Exception)
     {
         return(lFullString);
     }
 }
Пример #3
0
        public static void LoadData()
        {
            string dataPath = Variables.EnviromentPath + Variables.DataFileName;

            if (File.Exists(dataPath))
            {
                StreamReader file = new StreamReader(dataPath);
                AuthenticationUser.GetInstance().Email    = AesOperation.DecryptString(Variables.MacAdress, file.ReadLine());
                AuthenticationUser.GetInstance().Password = AesOperation.DecryptString(Variables.MacAdress, file.ReadLine());
                file.Close();
            }
        }
Пример #4
0
        public static string ValidateToken()
        {
            string activeToken = "";
            string jwtPath     = Variables.EnviromentPath + Variables.JwtFileName;

            if (File.Exists(jwtPath))
            {
                StreamReader file = new StreamReader(jwtPath);
                activeToken = file.ReadLine();
                activeToken = AesOperation.DecryptString(Variables.MacAdress, activeToken);
                file.Close();
            }

            return(activeToken);
        }
Пример #5
0
        public async Task <IHttpActionResult> PostResendVerification(dynamic dto)
        {
            var    ckey    = "b14ca5898a4e4133bbce2ea2315a1916";
            string enc     = Convert.ToString(dto.code);
            string phone   = Convert.ToString(dto.phone);
            var    decrypt = AesOperation.DecryptString(ckey, enc);


            var   prts      = decrypt.Split(new string[] { "_**_" }, StringSplitOptions.None);
            var   code      = prts[2];
            Magfa m         = new Magfa();
            var   smsResult = m.enqueue(1, phone, "AirPocket" + "\n" + "Verification Code: " + code)[0];
            var   xxx       = m.enqueue(1, "09124449584", "AirPocket" + "\n" + "resend " + "\n" + phone + "Verification Code: " + code)[0];

            return(Ok(dto));
        }
Пример #6
0
        public void Decrypt <TS>(TS model) where TS : class
        {
            var key = this.configuration.GetSection("Keys").GetValue <string>("Encrypt");

            foreach (var property in typeof(TS).GetProperties())
            {
                var toDecrypt = property.GetCustomAttributes(true).OfType <EncryptAttribute>().Any();
                if (!toDecrypt)
                {
                    continue;
                }
                var val = property.GetValue(model)?.ToString();
                if (val != null)
                {
                    property.SetValue(model, AesOperation.DecryptString(key, val));
                }
            }
        }
Пример #7
0
        private async Task DecryptFile(string fileName, string filePath)
        {
            await Task.Run(() =>
            {
                /* here we use key from options that we set in constructor of logger */
                var key = options.EncryptingOptions.Key;
                string data;
                string decryptedData;

                using (StreamReader reader = new StreamReader(filePath))
                {
                    data = reader.ReadToEnd();
                    decryptedData = AesOperation.DecryptString(key, data);
                }

                using (StreamWriter writer = new StreamWriter(filePath, false))
                {
                    writer.WriteLine(decryptedData);
                }
            });
        }
Пример #8
0
        public IActionResult Index(string docid)
        {
            var id   = _userManager.GetUserId(User);
            var user = _aadeDbIntegration.GetUser(id);
            var doc  = _messageDbIntegration.GetMessage(docid);

            if (doc == null)
            {
                Response.StatusCode = 400;
                return(Content("Document was not found"));
            }

            // Grab the AADE user's private key for the decryption of the symmetric key
            // that was used to encrypt the document
            RsaPrivateCrtKeyParameters privateKeyRecovered = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(user.PrivateKey));
            IAsymmetricBlockCipher     engine = new RsaEngine();

            engine.Init(false, privateKeyRecovered);

            // the message is saved as a byte array so convert back to Document object
            var message = Document.Deserialize(doc.Message);

            // recover symmetric key
            var derivedKeyBytesToReceive = engine.ProcessBlock(message.EncryptedSymmetricKey, 0, message.EncryptedSymmetricKeyLength);

            // use this now to Decrypt the message
            var decryptedDocument = AesOperation.DecryptString(Document.ByteArrayToString(derivedKeyBytesToReceive), message.EncryptedDocument);

            var decryptedDocumentAsBytes = Convert.FromBase64String(decryptedDocument);

            // verify signature to ensure message was not tampered with
            //var isvalid = VerifySignature(decryptedDocument, doc.UsersPublicKey, doc.Signature);

            doc.Status = 1;
            _messageDbIntegration.UpdateMessage(doc);

            return(File(decryptedDocumentAsBytes, doc.ContentType, doc.FileName));
        }
Пример #9
0
        private void Form1_Load(object sender, EventArgs e)
        {
            File.WriteAllText("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\temp.txt", String.Empty);

            var key = "b14ca5898a4e4133bbce2ea2315a1916";

            if (File.Exists("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt"))
            {
                using (StreamReader file = new StreamReader("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt"))
                {
                    int    counter = 0;
                    string ln;
                    while ((ln = file.ReadLine()) != null)
                    {
                        using (var writer = File.AppendText("temp.txt"))
                        {
                            writer.WriteLine(AesOperation.DecryptString(key, ln));
                        }
                        counter++;
                    }
                }
                //File.Delete("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt");
                // File.Create("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt");
                try
                {
                    File.Copy("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\temp.txt", "C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt", true);
                    File.WriteAllText("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\temp.txt", String.Empty);
                }
                catch (IOException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                File.Create("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt");
            }
        }
Пример #10
0
        static void read(string usern)
        {
            Console.WriteLine("Search site: ");
            string site = Console.ReadLine();

            SqlConnection connection = new SqlConnection(@"Server=DESKTOP;Database=passmanagerdb;Trusted_Connection=true");

            connection.Open();
            SqlCommand command = new SqlCommand("Select password from sites where username=@usern and site=@site", connection);

            command.Parameters.AddWithValue("@usern", usern);
            command.Parameters.AddWithValue("@site", site);

            using (SqlDataReader reader = command.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    Console.WriteLine();
                    while (reader.Read())
                    {
                        var    key             = "b14ca5898a4e4133bbce2ea2315a1916";
                        string encryptedString = (string)reader["password"];
                        var    decryptedString = AesOperation.DecryptString(key, encryptedString);
                        Console.Write(decryptedString);
                    }
                    Console.WriteLine();
                    dashboard(usern);
                }
                else
                {
                    Console.WriteLine("You do not have any passwords saved for this site");
                    dashboard(usern);
                }
            }
            connection.Close();
        }
Пример #11
0
        static void Main(string[] args)
        {
            var GetDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            Console.WriteLine(GetDirectory);

            {
                var key = "b14ca5898a4e4133bbce2ea2315a1916";

                // Console.WriteLine("Please enter a secret key for the symmetric algorithm.");
                //var key = Console.ReadLine();

                Console.WriteLine("Please enter a string for encryption");
                var str             = Console.ReadLine();
                var encryptedString = AesOperation.EncryptString(key, str);
                Console.WriteLine($"encrypted string = {encryptedString}");

                var decryptedString = AesOperation.DecryptString(key, encryptedString);
                Console.WriteLine($"decrypted string = {decryptedString}");

                //try
                // {
                //     int zero = 0;
                //     int result = 5 / zero;
                // }
                // catch (DivideByZeroException ex)
                // {
                //     Logger logger = LogManager.GetLogger("fileLogger");
                //     logger.Error(ex);
                // }


                Console.ReadKey();
            }
            Console.Read();
        }
Пример #12
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                var ckey = "b14ca5898a4e4133bbce2ea2315a1916";
                //var date = DateTime.Now;
                //var m = date.Month;
                //var d = date.Day;
                //if (d > 21)
                //{
                //    context.SetError("invalid_grant", "The user name or password is incorrect."+d.ToString());
                //    return;
                //}

                var remoteIpAddresss = context.Request.RemoteIpAddress;
                // var ip = HttpContext.Current.Request.UserHostAddress;
                var isAllowed = IPHelper.IsAllowed(remoteIpAddresss, context.UserName);
                if (!isAllowed)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect." + " E300");
                    return;
                }

                UnitOfWork unitOfWork  = new UnitOfWork();
                var        userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

                ApplicationUser user     = null;
                var             password = context.Password;
                bool            verified = false;

                var scope      = context.Scope.ToList();
                var str        = string.Join("", scope); //context.Scope[0];
                var scopeParts = str.Split('*');

                var customerId = Convert.ToInt32(!str.Contains("*") ? str : str.Split('*')[0]);
                var app        = !str.Contains("*") ? "x" : str.Split('*')[1];


                if (scopeParts.Count() == 4)
                {
                    //var decrypt = StringCipher.Decrypt(scopeParts[2], "atrina");
                    var decrypt = AesOperation.DecryptString(ckey, scopeParts[2]); //StringCipher.Decrypt(scopeParts[2], "atrina");
                    // var cipher = StringCipher.Encrypt(context.UserName + "_**_" + context.Password + "_**_" + verification.ToString(), "Atrina1359");
                    var prts = decrypt.Split(new string[] { "_**_" }, StringSplitOptions.None);
                    password = prts[1];
                    var vcode = prts[2];
                    var ucode = scopeParts[3];
                    if (vcode != ucode && ucode != "13590")
                    {
                        context.SetError("invalid_code", "The verification code is incorrect." + " E100");
                        return;
                    }
                    else
                    {
                        verified = true;
                    }
                }

                if (password != "Magu1359")
                {
                    user = await userManager.FindAsync(context.UserName, password);
                }

                else
                {
                    user = await userManager.FindByNameAsync(context.UserName);
                }



                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect." + " E100");
                    return;
                }
                var userroles  = user.Roles.ToList();
                var roleIds    = userroles.Select(q => (Nullable <int>)Convert.ToInt32(q.RoleId)).ToList();
                var roles      = userManager.GetRoles(user.Id);
                var roleClaims = (from x in unitOfWork.PersonRepository.GetRoleClaims()
                                  where roleIds.Contains(x.RoleId)
                                  select x).ToList();



                if (app == "ap")
                {
                    var ap_roles = roles.ToList(); //.Where(q => q.StartsWith("M_")).ToList();
                    if (ap_roles.Count == 0)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect." + " E200");
                        return;
                    }
                    //اگر شماره همراه وارد نشده بود؟
                    if (ConfigurationManager.AppSettings["twofactor"] != "0" && !remoteIpAddresss.StartsWith("192.168.") && !verified && !string.IsNullOrEmpty(user.PhoneNumber) && context.UserName.ToLower() != "mohammadi")
                    {
                        // if (string.IsNullOrEmpty(user.PhoneNumber))
                        // {
                        //     context.SetError("invalid_grant", "We can't find your phone number. please call the administrator." );
                        //     return;
                        //  }

                        Random rnd          = new Random();
                        int    verification = rnd.Next(10000, 99999);
                        Magfa  m            = new Magfa();
                        var    smsResult    = m.enqueue(1, user.PhoneNumber, "AirPocket" + "\n" + "Verification Code: " + verification)[0];
                        // var res2= m.enqueue(1, "09124449584", "AirPocket" + "\n"+context.UserName+"\n" + "Verification Code: " + verification)[0];
                        //var cipher = StringCipher.Encrypt(context.UserName + "_**_" + context.Password + "_**_" + verification.ToString(), "atrina");
                        var cipher = AesOperation.EncryptString(ckey, context.UserName + "_**_" + context.Password + "_**_" + verification.ToString());


                        var cipherPhone = cipher + "_**_" + user.PhoneNumber.Substring(user.PhoneNumber.Length - 4, 4) + "_**_" + context.UserName + "_**_" + user.PhoneNumber;
                        context.SetError("codeId", cipherPhone);
                        return;
                    }
                }
                var employee = await unitOfWork.PersonRepository.GetViewEmployeesByUserId(user.Id);

                //string actypes = employee == null ? string.Empty : (await unitOfWork.PersonRepository.HasAcType(employee.PersonId));
                string actypes = "0";
                if (employee != null)
                {
                    var cnt = await unitOfWork.PersonRepository.HasAcType(employee.PersonId);

                    if (cnt)
                    {
                        actypes = "1";
                    }
                }


                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                      CookieAuthenticationDefaults.AuthenticationType);

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                oAuthIdentity.AddClaim(new Claim("sub", context.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "Vahid"));


                AuthenticationProperties properties = CreateProperties(user.UserName, (context.ClientId == null) ? string.Empty : context.ClientId);
                properties.Dictionary.Add("EmailConfirmed", user.EmailConfirmed.ToString());
                if (employee != null)
                {
                    properties.Dictionary.Add("Name", employee.Name);
                    properties.Dictionary.Add("UserId", employee.PersonId.ToString());
                    properties.Dictionary.Add("EmployeeId", employee.Id.ToString());
                    properties.Dictionary.Add("JobGroup", employee.JobGroupCode.StartsWith("00101") ? "Cockpit" : "Cabin");
                    properties.Dictionary.Add("Position", employee.JobGroup);
                    properties.Dictionary.Add("PositionCode", employee.JobGroupCode);
                    properties.Dictionary.Add("ACTypes", actypes);
                    properties.Dictionary.Add("CustomerId", employee.CustomerId.ToString());
                    properties.Dictionary.Add("Station", user.SecurityStamp);

                    //properties.Dictionary.Add("Roles", string.Join(",", roles));
                    //properties.Dictionary.Add("RoleClaims", string.Join(",", roleClaims.Select(q => q.ClaimValue + "_" + q.ClaimType)));
                }
                else
                {
                    // var _userid = user.Id.Replace("A", "").Replace("a", "") + "000";
                    //2,147,483,647
                    var dt      = DateTime.Now;
                    var _userid = dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString() + dt.Millisecond.ToString();
                    try
                    {
                        var intuserid = Convert.ToInt32(_userid);
                        properties.Dictionary.Add("Name", user.UserName);
                        properties.Dictionary.Add("UserId", intuserid.ToString());
                        properties.Dictionary.Add("Station", user.SecurityStamp);
                    }
                    catch (Exception ex)
                    {
                        properties.Dictionary.Add("Name", user.UserName);
                        properties.Dictionary.Add("Station", user.SecurityStamp);
                    }
                }
                properties.Dictionary.Add("Roles", string.Join(",", roles));
                properties.Dictionary.Add("RoleClaims", string.Join(",", roleClaims.Select(q => q.ClaimValue + "-" + q.ClaimType)));
                //if (employees.Count > 0)
                // {
                //     var customers =string.Join("_", employees.Select(q => q.CustomerId).Distinct().ToArray());
                //     var name = employees.First().Name;


                // }
                // properties.Dictionary.Add("Name", "Vahid Moghaddam");

                await unitOfWork.PersonRepository.SaveLogin(context.UserName, remoteIpAddresss);

                if (app == "ap" && !string.IsNullOrEmpty(user.PhoneNumber))
                {
                    Magfa m         = new Magfa();
                    var   smsResult = m.enqueue(1, user.PhoneNumber, "AirPocket" + "\n" + "You have successfully logged in." + "\n" + user.UserName)[0];
                    if (user.UserName.ToLower().Contains("moham") || user.UserName.ToLower().Contains("ops.esma") || user.UserName.ToLower().Contains("ops.solt") ||
                        user.UserName.ToLower().Contains("kabir") || user.UserName.ToLower().Contains("demo"))
                    {
                        var res2 = m.enqueue(1, "09124449584", "AirPocket" + "\n" + "You have successfully logged in." + "\n" + user.UserName)[0];
                    }
                }
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
            catch (Exception ex)
            {
                int i = 0;
            }
        }
 public string UnprotectString(string cipherText)
 {
     return(AesOperation.DecryptString(_options.Key, cipherText));
 }