ring-clojure / ring

Clojure HTTP server abstraction
MIT License
3.75k stars 519 forks source link

Example of generating and storing a byte array for cookies #414

Closed trevor closed 4 years ago

trevor commented 4 years ago

I see secret-key for cookies now expects to be something along the lines of:

user=> (crypto.random/bytes 16)
#object["[B" 0x2fa7eb81 "[B@2fa7eb81"]

I store the secret-key in an EDN configuration file as a string currently in a key-value map. How can I store this as a byte array in EDN?

weavejester commented 4 years ago

You can convert a byte-array into a vector with vec:

user=> (vec (crypto.random/bytes 16))
[76 123 -88 -31 -122 -128 19 -14 -112 -108 125 0 19 -52 108 -35]

And convert it back to a byte array with byte-array:

user=> (byte-array *1)
#object["[B" 0x2bb1b68e "[B@2bb1b68e"]
trevor commented 4 years ago

Very interesting, I'll look into it, thank you.

Will this be documented on the wiki or elsewhere?

Also, what was the motivation for changing from a string to a byte-array? Is it more secure? It seems to add some complexity.

weavejester commented 4 years ago

Strings encourage keys with insufficient entropy, as it's often tempting to use strings with only visible characters. If you were storing your secret in edn, perhaps this was also the case for you? By deprecating that and encouraging byte arrays, we indicate that the key should make use of all 8 bits in each byte.

We can document it in the wiki. This is useful information, but should be considered supplementary documentation, as converting between byte arrays is really more of a general feature of Clojure, rather than anything specific to Ring.

trevor commented 4 years ago

Interesting, yes I hadn't considered the inclusion of unprintable characters.

This would be helpful to have documented, it's not an area of Clojure I encounter often. Thanks for the thorough explanation.