Ivan Sukhetskyi Ivan Sukhetskyi - 3 months ago 14
ASP.NET (C#) Question

How can I convert password string to Base64 string before sending form to backend?

I have a sample registration form, it works properly for most cases, but when I try to register new user with password "U8$&#6G#CBj" I'm getting an exception "A potentially dangerous Request.Form value was detected from the client"
My idea is to convert password to Base64 format before sending it to backend and on backend convert it back. How can I do it?

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Use a local account to log in.</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log in" class="btn btn-default" />
</div>
</div>
<p>
@Html.ActionLink("Register as a new user", "Register")
</p>
@* Enable this once you have account confirmation enabled for password reset functionality *@
<p>
@Html.ActionLink("Forgot your password?", "ForgotPassword")
</p>
}

Answer

With help of Alexei Levenkov for frontend part and Vidhyadhar Galande for backend I solved my problem here is the code: on View to form I have added this javascript function on submit event

function encode(){
        $('#Password').val(btoa($('#Password').val()));
        $('#ConfirmPassword').val(btoa($('#ConfirmPassword').val()));
    }

and on backend decode strings back:

private string DecodeFromBase64(string inputBas64)
{
    var base64EncodedBytesPassword = System.Convert.FromBase64String(model.Password);
    string password = System.Text.Encoding.UTF8.GetString(base64EncodedBytesPassword);
    return password;
}
Comments