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