0

I am storing the password encrypted format in table and assign there value in modelclass property of password but give an error?

validation failed one or more property.

see my watch window

HomeController.cs

        public static string Encrypt(string clearText)
        {
            try
            {
                byte[] hashBytes = ComputeHash(clearText);
                byte[] saltBytes = GetRandomSalt();
                byte[] saltHash = ComputeHash(saltBytes.ToString());

                byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length];
                for (int i = 0; i < hashBytes.Length; i++)
                    hashWithSaltBytes[i] = hashBytes[i];
                for (int i = 0; i < saltBytes.Length; i++)
                    hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

                string hashValue = Convert.ToBase64String(hashWithSaltBytes);

                return hashValue;
            }
            catch (Exception)
            {

                throw;
            }
        }


        public static byte[] GetRandomSalt()
        {
            int minSaltSize = 16;
            int maxSaltSize = 32;

            Random random = new Random();
            int saltSize = random.Next(minSaltSize, maxSaltSize);
            byte[] saltBytes = new byte[saltSize];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetNonZeroBytes(saltBytes);
            return saltBytes;
        }

        public static byte[] ComputeHash(string plainText)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            HashAlgorithm hash = new SHA256Managed();
            return hash.ComputeHash(plainTextBytes);
        }

        public ActionResult create()
        {
            return View();
        }

        public ActionResult create(student stud)
        {
            try
            {
                string pass = Encrypt(stud.password);
                stud.password = pass; //assigning a string pass to stud.pass

                var create = dbstud.students.Add(stud);
                dbstud.SaveChanges();
                return RedirectToAction("Login");

            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
        }

student.cs

    public partial class student
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public student()
        {
            this.blogs = new HashSet<blog>();
        }

        public int studid { get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public string email { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<blog> blogs { get; set; }
    }
dbstud.SaveChanges();     //here give an error validation failed one or more entities.

see watch window which place come to this error

now I am storing the password encrypted format and assign there value in modelclass property of password but give an error?

how to solve this error?

password varchar(50)

when I enter the password 1 run time then give an error: see this image

enter image description here

Raju
  • 75
  • 6
  • You should look into what validation errors are happening. See https://stackoverflow.com/a/7798264/493557 for help on how to do that. – G_P Jun 09 '20 at 12:55
  • @G_P I see that link but catch throw a exception which place throw exception that I don't know – Raju Jun 09 '20 at 12:57
  • @G_P https://i.stack.imgur.com/rKOqW.png exactly does not know which place is error? – Raju Jun 09 '20 at 13:03
  • you need to review the output of the Console.Writeline statements in that catch statement. It will step through and output what the various validation errors are on your student class – G_P Jun 09 '20 at 13:14
  • @G_P see my watch window image which place come to this error? – Raju Jun 09 '20 at 14:08
  • I'm not really sure what you are asking. Put a breakpoint on line 95, and debug your code. When the breakpoint is hit (note, it may get hit multiple times if more than 1 validation error exists) look at the values of ve.PropertyName and ve.ErrorMessage to see what is wrong – G_P Jun 09 '20 at 14:20
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/215593/discussion-between-raju-and-g-p). – Raju Jun 09 '20 at 14:20
  • @G_P https://i.stack.imgur.com/HKQTN.png this is an error ? – Raju Jun 09 '20 at 14:33

1 Answers1

0

From the chat the underlying error was

"The field password must be a string or array type with a maximum length of '50'." string //this is the error

That error means that your database column for password will not allow a string longer than 50 characters, and the value you have for password when trying to save the student is longer than 50 characters.

You need to take off the maximum string length for the column, or increase it so that the 'encrypted' password length will never exceed it.

To alter the varchar maximum length of your column you can do something like (I'm guessing at your table name here). This will remove the max length limitation on that column entirely:

ALTER TABLE [student] ALTER COLUMN [password] VARCHAR(MAX)

see https://stackoverflow.com/a/8829066/493557 and https://stackoverflow.com/a/2696003/493557 for additional info.

G_P
  • 2,100
  • 3
  • 16
  • 18
  • still facing this error see this image when I enter only string https://i.stack.imgur.com/2H17K.png not solved? – Raju Jun 09 '20 at 16:13
  • @Raju I suggest updating your question with specifics about what you changes you have made to try to resolve the error. If I had to guess, again - it is a guess, it looks like either you didn't change the maximum length for the password field in the database, or if you did change it, perhaps you're pointing to a different instance of the database. Again, these are all guesses without knowing specifics of what you have tried thus far. – G_P Jun 09 '20 at 17:37
  • still I am facing this issue see my updated question give the same error – Raju Jun 11 '20 at 11:41
  • I have included additional detail in my answer - you need to increase the maximum length for your password column in your database. – G_P Jun 11 '20 at 13:42
  • yes you are right now passwword is store in securely way but issue is when I login not work the login functionality and when I uncomment the password functionality code then login functionality work fine – Raju Jun 12 '20 at 04:38
  • @Raju I suggest writing a new question for the new problem you're facing – G_P Jun 12 '20 at 11:49