Sodium Crypto Secret Box - How to Encrypt Passwords in PHP
A function is a tool that can perform specific tasks for you. Functions accept information passed to them through arguments, which are specified after the function name within parenthesis. This information is used to modify the behavior of a function. For example, an argument can change the return type or input parameters. Arguments are also used for storing information in variables, which can be useful for security purposes, such as to store passwords safely.
Sodium is a cryptographic library which provides high-level abstractions for encryption, decryption, signing, and password hashing in PHP. It is a fork of NaCl, which was a popular cryptography library. Libsodium is modern (v1 released in 2014), portable, and has a lot of functionality.
The main difference between Sodium and other cryptography libraries is that it supports authenticated encryption. This means that every piece of encrypted data is affixed with a Message Authentication Code (MAC), which can validate that the data hasn’t been manipulated in transit. If the MAC is invalid, Sodium will immediately error.
To encrypt an object, pass it to the sodium_crypto_secretbox() function with an $key and a generated nonce. You can generate a nonce using the random_bytes() function, but it’s safer to use a built-in function like sodium_crypto_secretbox_keygen(). If you encrypt and decrypt the same object, it’s important to use a different nonce each time. Otherwise, you’ll get a cryptic error that says “Security violation: the key or secret is not valid.” This is because a MAC needs to be generated with a new key for each encrypt/decrypt operation.