10

How to hash/encrypt string value in JavaScript? I need a mechanism to do so for hiding some data in localStorage/cookie?

It is something related to security concern but I want some protection for my data.

Deepak Biswal
  • 4,280
  • 2
  • 20
  • 37
  • https://code.google.com/p/crypto-js/ does it. How are you planning on protecting the secret from snooping? – Mike Samuel Aug 07 '13 at 20:19
  • Thanks! I'll look into cryptojs. I want to encrypt the data and store in my cookie, so that it has some level of security. – Deepak Biswal Aug 07 '13 at 20:22
  • I understand what you want to do. Whom are you protecting against, and how are you going to have access the secret that you use to encrypt the data when you need it without making it vulnerable to theft? – Mike Samuel Aug 07 '13 at 20:32

1 Answers1

6

There are lots of encryption libraries for javascript. Here's the first one that came up on Google: http://crypto.stanford.edu/sjcl/

Your user can always gain access to the key, so this won't protect data from your user. If you want to hide things from the user, you'll have to encrypt it on the server and never send the key to the client.

Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
  • 1
    If the key is only resident in browser memory, then you can protect against an attacker who has privileged file system access, but not privileged memory access since the former does not grant access to the segment of disk used for virtual memory in most OSes. Keeping responses with secrets out of the cache requires being very careful with cache headers, but there is a set of headers that major browsers respect -- just not the obvious ones, IIRC. – Mike Samuel Aug 07 '13 at 20:36
  • @Mike Samuel: could you elaborate a bit on that solution? I e, how to keep secrets out of the cache, and which headers to use? It deserves its own answer. – Per Quested Aronsson Sep 17 '13 at 19:21
  • @PerQuestedAronsson, I think ["Industry-wide Misunderstandings of HTTPS"](http://securityevaluators.com/content/case-studies/caching/) has the best treatment of this I've seen. "Although there are no technical constraints preventing content sent over an encrypted connection from being decrypted and written to disk, it is logical to presume that if content is too sensitive to be sent over a network without encryption, then it may also be too sensitive to store unprotected on a hard drive." It goes on to evaluate caching behavior of 4 browsers w.r.t. various headers. – Mike Samuel Sep 17 '13 at 20:08