> Implementation is best left to cryptographers.
You suggest we hire a cryptographer every time we need something secured?
I mean, come on, this is ridiculous. The code quoted does not implement encryption, it invokes encryption. The AES algorithm being invoked, I expect, was written by proper cryptographers.
The reason this code is insecure is that the API is a piece of shit.
Most standard crypto modules have calls of the form
encrypt(algorithmName, arg, arg)
Depending on the algorithm chosen
totally different parameters need to be passed or else. Or else what? Or else the function works perfectly well, produces an encrypted byte array, but with totally broken security. The programmer will be none the wiser except if they were lucky enough to post the code somewhere on HN and someone writes a condescending comment.
This is shit design and we can blame the cryptographers. It doesn't have to be this way.
Some languages and libraries get it right, here and there. Eg PHP doesn't just expose a way to call bcrypt, but also has two functions password_hash and password_hash_verify. These implement all the best practices, with seeds, the right algorithm parameters, keeping the ability to rehash in the future, etc.
We need similar APIs for symmetric and asymmetric encryption, for common use cases, or this madness is simply going to continue. Cryptographers, please get your act together. Job safety is nice, but a secure internet is nicer. Please make it easy for morons like me to use crypto right.
I mean, I don't even know what the different considerations are so I can't design these functions right, so please consider the spirit of the following proposal and not the details.
What about a function like encrypt_symmetric_for_single_user(payload, userid, key) which takes care of picking the right algorithm, doing the right dance with keys and nonces and whatnot? Or maybe functions need to include naming like encrypt_for_sending_once and encrypt_for_storing_long? My understanding is that you want different crypto in such cases, right? I'm sure better cryptographers than me can immediately see what I'm doing wrong here, but you catch the gist right? Why can't this be made easier? Why do we at the same time, collectively, shame everyone who gets security wrong and make it so unnecessarily hard for people to get right?