SHA-256 shuffle

Someone at StackOverflow asked if it was possible to shuffle a deck of cards based on the value of a SHA-256 hash. The question was deleted before I got a chance to answer, but it’s an interesting idea. A standard deck of playing cards has 52! (52 factorial) permutations. This doesn’t evenly divide the number of possible SHA-256 hashes (which is 2256, obvs), but since 52! is much smaller, the results are still very uniform. To be precise, some deck permutations will be about 0.00000007% more likely than others. This might be a problem for cryptographic applications, but I can’t see how it could cause any problems for card games. This code also provides a useful way of representing the ordering of a deck of cards with a single number from 0 to 52!−1 (226 bits, or 29 bytes).

You can try it out here. Check the source code if you want to see how it works.

Results will appear below

.

4 comments

  1. I don’t understand why my shuffle yields different results than yours. It works, but we don’t have the same deck at the end. What character encoding are you using to get your sha? I re-implemented your algorithm in C#/.NET and mine works but we end up with two different deck arrangements even though we start with the same original array. So I’m thinking we’ve got to be feeding sha different inputs and generating a different ‘p’ value. Can you explain? I tried my browser debugger but I don’t really get Javascript (I come from a lower-level background) and I’m a bit confused.

    1. I figured it out about 2 seconds after I asked, haha. You’re using ASCII and my deck arrangement is yours in reverse order from how you display yours. 😀

      1. Nope, tricked myself … only my first 3 cards match your last 3, and I don’t get how that’s possible lol. What exactly is going on here? :0

    2. Gaah, you’re right. Thanks for the heads-up 🙂
      I missed a step in the initialize_deck() function. Should be OK now. There’s not really any character encoding going on; I’m just treating the SHA256 hash as a 256-bit number.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.