0

I want to generate a secure and ASCII encoded random nonce for my JavaScript program (it has to work in WebKit). Preferably, I want to use an off-the-shelf tool. So far, the only answers I found was this: Secure random numbers in javascript?

The only problem with this is that the result is random, and I'm not sure how I can ASCII encode it without sacrificing security (i.e., making it less random).

Edit: Math.random() is not cryptographically secure, and window.crypto only generates values in multiples of a byte (ASCII values are 7 bits, so if the encoding mechanism is implemented naively, it would reduce the randomness).

Community
  • 1
  • 1
Discombobulous
  • 1,112
  • 2
  • 14
  • 25
  • 5
    An encoding does not change the randomness of the value it encodes. – kojiro Aug 30 '12 at 00:24
  • I thought ASCII is 7 bit, window.crypto only generates values in multiples of a byte. My gut feeling tells me encoding it back to 7 bit could decrease the randomness. – Discombobulous Aug 30 '12 at 00:29
  • Math.random() is not cryptographically secure. – Discombobulous Aug 30 '12 at 00:29
  • 1
    We can't offer a solution until you define what you mean be `secure`? – jfriend00 Aug 30 '12 at 00:31
  • 1
    @EricChen if I generate a random integer between x and y and ask you to guess it, are you better able to guess it if I happen to express the number in a different way? – kojiro Aug 30 '12 at 00:33
  • @kojiro - Yes, if you are using Math.random() I have a higher probability of guessing it since it's not a cryptographically secure pseudo-random generator. – Discombobulous Aug 30 '12 at 00:35
  • @EricChen I'm talking about encodings, not about `Math.random()`. – kojiro Aug 30 '12 at 00:36
  • @kojiri - How would you encode a 8 bits character to 7 bits? I don't think abandoning the last bit is secure. I'm not a crypto person but what I need to do requires a fully secure CSPRNG – Discombobulous Aug 30 '12 at 00:40
  • @EricChen by using more than one character to encode it, not by truncating the value to a different value. – kojiro Aug 30 '12 at 00:41
  • @EricChen If you're using a good PRNG, it doesn't matter if you truncate characters as long as you have enough bits in the end. Using the first 4 bits of two 8 bit characters is just as random as using 8 bits from one character. – G-Nugget Aug 30 '12 at 00:44
  • @kojiro - Ah sorry, I was being stupid. I see what you mean :) – Discombobulous Aug 30 '12 at 00:44

1 Answers1

0

You can encode arbitrary byte arrays as Base64 to get pure ASCII.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • As in… http://stackoverflow.com/questions/246801/how-can-you-encode-to-base64-using-javascript – kojiro Aug 30 '12 at 00:45