Encrypt and Decrypt Password stored in database using AngularJS in ASP.Net MVC

Last Reply 6 months ago By dharmendr

Posted 6 months ago

Hi,

I have one table in database with fields

Id UserName password

I am going to create new records on evety time

Coming to my requirement i need to encrypt/decrypt my password,Username

after clicking of save button in add form need tosave details to database

At database password should be encyptred i don't need to display password value at database it should be encrypted 

eX:I don't need to save like below

iD Username Password

1 mahesh mahesh

I need to save password like below

D Username Password

1 mahesh VpAXCkD/2PHIwbdPLF3KrzScvVGAOtrODF+svN6bqpc=

and also at i need to display decrypt password and encrypt password values on grid view

Could you please help me

            <div id="dvContainer">
                <div>
                    <div class="table-responsive ">
                        <table id="dvData"  class="table table-bordered">
                            <tr>
                                <th><b>Decrypted UserName</b></th>
                                <th><b>Encrypted UserName</b></th>
                                <th><b>Encrypted Password</b></th>
                                <th><b>Decrypted Password</b></th>
                            </tr>
                            <tr dir-paginate="user in users|itemsPerPage:10" >
                                <td>
                                    {{user.UserName}}
                                </td>
                                <td>
                                    {{user.UserName}}
                                </td>
                                <td>
                                    {{user.Password }}
                                </td>
                                <td>
                                    {{user.Password}}
                                </td>
                            </tr>                           
                        </table>
                    </div>
                </div>
            </div>

 

        public JsonResult getAll()
        {
            db.Configuration.ProxyCreationEnabled = false;
            var encList = (from em in db.Encrypts
                                select new
                                {
                                    em.Id,
                                    em.UserName,
                                    em.Password,                                  
                                }).ToList();

            var JsonResult = Json(encList, JsonRequestBehavior.AllowGet);
            JsonResult.MaxJsonLength = int.MaxValue;

            return JsonResult;
        }

        public string AddUser(Encrypt en)
        {
            if (en != null)
            {

                Encrypt en1 = new Encrypt();
                en1.Id = en.Id;
                en1.UserName = en.UserName;
                en1.Password = en.Password;
                db.Encrypts.Add(en1);
                db.SaveChanges();
                return "Record added Successfully";
            }
            else
            {
                return "Addition of Record unsucessfull !";
            }
        }

 


Posted 6 months ago

Hi mahesh213,

Check this example. Now please take its reference and correct your code.

Model

public class UserDetails
{
    public string Name { get; set; }
    public string EncryptedPassword { get; set; }
    public string DecryptedPassword { get; set; }
}

Controller

public class HomeController : Controller
{
    UsersDBEntities db = new UsersDBEntities();
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult getAll()
    {
        var encList = db.Users1.ToList();
        List<UserDetails> details = new List<UserDetails>();
        foreach (Users1 user in encList)
        {
            details.Add(new UserDetails
            {
                Name = user.Username,
                EncryptedPassword = user.Password,
                DecryptedPassword = Decrypt(user.Password)
            });
        }
        var JsonResult = Json(details, JsonRequestBehavior.AllowGet);

        return JsonResult;
    }

    public string AddUser(Users1 en)
    {
        if (en != null)
        {
            Users1 en1 = new Users1();
            en1.Username = en.Username;
            en1.Password = Encrypt(en.Password);
            db.Users1.AddObject(en1);
            db.SaveChanges();
            return "Record added Successfully";
        }
        else
        {
            return "Addition of Record unsucessfull !";
        }
    }

    private string Decrypt(string cipherText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }

    private string Encrypt(string clearText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
}

View

<html>
<head>
    <title>Index</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.8/angular.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/angular-utils-pagination@0.11.1/dirPagination.js"></script>
    <script type="text/javascript">
        var app = angular.module("myApp", ['angularUtils.directives.dirPagination']);
        app.controller("myCntrl", ['$scope', '$http', 'myService', function ($scope, $http, myService) {
            GetAllUsers();
            function GetAllUsers() {
                var getData = myService.getuserrate();
                getData.then(function (er) {
                    $scope.users = er.data;
                }, function (er) {
                    alert("Records gathering failed!");
                });
            }
            $scope.AddUpdateUser = function () {
                $scope.mahesh = false;
                var User = {
                    Username: $scope.UserName,
                    Password: $scope.Password
                };
                var getAction = $scope.Action;
                var getData = myService.AddUser(User);
                getData.then(function (msg) {
                    GetAllUsers();
                    alert(msg.data);
                    $scope.msg = msg.data;
                }, function (msg) {
                    alert(msg.data);
                    $scope.msg = msg.data;
                });
                GetAllUsers();
            }
            //Add Exchangerate  details
            $scope.AddUserDiv = function () {
                $scope.mahesh = $scope.mahesh ? false : true;
                GetAllUsers();
                $scope.Action = "Add";
            }
        } ]);
        app.service("myService", function ($http) {
            this.getuserrate = function () {
                return $http.get("/Home/getAll");
            };
            this.AddUser = function (user) {
                var response = $http({
                    method: "post",
                    url: "/Home/AddUser",
                    data: JSON.stringify(user),
                    dataType: "json"
                });
                return response;
            }
        });
    </script>
</head>
<body ng-app="myApp" ng-controller="myCntrl">
    <div class="container">
        <div>
            <div id="wrapper" class="clearfix" ng-show="mahesh">
                <form name="userForm" novalidate>
                <div class="form-horizontal">
                    <div class="row">
                        <div class="col-md-3">
                            <label for="UserName">
                                UserName</label>
                            <input type="text" class="form-control" ng-model="UserName" />
                        </div>
                        <div class="col-md-3">
                            <label for="Password">
                                Password</label>
                            <input type="text" class="form-control" ng-model="Password" />
                        </div>
                    </div>
                    <div>
                    </div>
                    <div class="form-group" style="width: 120%; text-align: center; padding: 10px;">
                        <div class="col-md-offset-2 col-md-5">
                            <p>
                                <button class="btn btn-success btn-sm" ng-model="IsVisible" ng-click="AddUpdateUser()">
                                    <span class="glyphicon glyphicon-ok"></span>Submitt</button>
                            </p>
                        </div>
                    </div>
                </div>
                </form>
            </div>
            <button class="btn btn-success btn-sm " ng-click="AddUserDiv();" style="margin-left: 15px;">Add</button>
            <hr />
            <div>
            </div>
            <div id="dvContainer">
                <div>
                    <div class="table-responsive ">
                        <table id="dvData" class="table table-bordered">
                            <tr>
                                <th><b>UserName</b></th>
                                <th><b>Encrypted Password</b></th>
                                <th><b>Decrypted Password</b></th>
                            </tr>
                            <tr dir-paginate="user in users|itemsPerPage:10">
                                <td>{{user.Name}}</td>
                                <td>{{user.EncryptedPassword}}</td>
                                <td>{{user.DecryptedPassword }}</td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Screenshot