4

I am using AngularJS in my web application. I have to take password from the UI and save it in encrypted format into database.

I have to retrieve it back and decrypt it. My thought is to read the text string in js file, then encrypt it in a service before saving into database.

Any suggestions ?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Fayaz shaik
  • 157
  • 1
  • 2
  • 12
  • 6
    A better approach is not *encrypting*, but *taking hash* and store it. Whenever you want to authorize user, take a hash from the string he/she provides as a password and *compare hashes*. – Dmitry Bychenko Dec 01 '15 at 06:51
  • Check this [Encrypting & Decrypting a String in C#](http://stackoverflow.com/questions/10168240/encrypting-decrypting-a-string-in-c-sharp?answertab=active#tab-top) It will really solve your issue. – Vipan Dec 01 '15 at 07:46
  • http://www.obviex.com/samples/hash.aspx for some code samples that show how to hash instead. You never need to decrypt, you only need to verify the password when it is sent to you by the user. – flup Dec 01 '15 at 07:50
  • I totally agree with storing the hash and not the password. Also, make sure any connection to the server is done via https – Mr Moose Dec 01 '15 at 08:37

1 Answers1

0

As Dmitry Bychenko said, create a factory service to hash the password. Then store and compare the hash.

angular.module("myApp").factory("sha1", function () {
function sha1(msg)
{
  function rotl(n,s) { return n<<s|n>>>32-s; };
  function tohex(i) { for(var h="", s=28;;s-=4) { h+=(i>>>s&0xf).toString(16); if(!s) return h; } };
  var H0=0x67452301, H1=0xEFCDAB89, H2=0x98BADCFE, H3=0x10325476, H4=0xC3D2E1F0, M=0x0ffffffff; 
  var i, t, W=new Array(80), ml=msg.length, wa=new Array();
  msg += fcc(0x80);
  while(msg.length%4) msg+=fcc(0);
  for(i=0;i<msg.length;i+=4) wa.push(msg.cca(i)<<24|msg.cca(i+1)<<16|msg.cca(i+2)<<8|msg.cca(i+3));
  while(wa.length%16!=14) wa.push(0);
  wa.push(ml>>>29),wa.push((ml<<3)&M);
  for( var bo=0;bo<wa.length;bo+=16 ) {
    for(i=0;i<16;i++) W[i]=wa[bo+i];
    for(i=16;i<=79;i++) W[i]=rotl(W[i-3]^W[i-8]^W[i-14]^W[i-16],1);
    var A=H0, B=H1, C=H2, D=H3, E=H4;
    for(i=0 ;i<=19;i++) t=(rotl(A,5)+(B&C|~B&D)+E+W[i]+0x5A827999)&M, E=D, D=C, C=rotl(B,30), B=A, A=t;
    for(i=20;i<=39;i++) t=(rotl(A,5)+(B^C^D)+E+W[i]+0x6ED9EBA1)&M, E=D, D=C, C=rotl(B,30), B=A, A=t;
    for(i=40;i<=59;i++) t=(rotl(A,5)+(B&C|B&D|C&D)+E+W[i]+0x8F1BBCDC)&M, E=D, D=C, C=rotl(B,30), B=A, A=t;
    for(i=60;i<=79;i++) t=(rotl(A,5)+(B^C^D)+E+W[i]+0xCA62C1D6)&M, E=D, D=C, C=rotl(B,30), B=A, A=t;
    H0=H0+A&M;H1=H1+B&M;H2=H2+C&M;H3=H3+D&M;H4=H4+E&M;
  }
  return tohex(H0)+tohex(H1)+tohex(H2)+tohex(H3)+tohex(H4);
};
return sha1;
});

Credit this answer for the SHA1 function.

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95