This project provides a simple solution for encrypting and decrypting strings using AES-CBC with a 256-bit key size. The solution is interoperable between JavaScript (for browser environments) and PHP, allowing secure encryption and decryption across different platforms. It requires no libraries.
- AES-256-CBC encryption and decryption.
- SHA-256 hashing for password-based key derivation.
- Random IV (initialization vector) generation for each encryption.
- Encoding of ciphertext in Base64 for easy storage and transmission.
- Hexadecimal encoding of IV for easy concatenation with ciphertext.
- 100% native and no libraries
- A modern web browser with support for Web Crypto API. See here for a support matrix
To use these encryption and decryption functions, simply include crypt.js
in your JavaScript project or crypt.php
in your PHP project.
Include the crypt.js
file in your HTML or JavaScript project.
<script src="path/to/crypt.js"></script>
const plaintext = "Hello, world!";
const password = "strongpassword";
encrypt(plaintext, password).then(encryptedText => {
console.log(encryptedText);
});
const encryptedText = "YourEncryptedStringHere";
const password = "strongpassword";
decrypt(encryptedText, password).then(plaintext => {
console.log(plaintext);
});
Include the crypt.php
file in your PHP project.
require 'path/to/crypt.php';
$plaintext = "Hello, world!";
$password = "strongpassword";
$encryptedText = encrypt($plaintext, $password);
echo $encryptedText;
require 'path/to/crypt.php';
$encryptedText = "YourEncryptedStringHere";
$password = "strongpassword";
$plaintext = decrypt($encryptedText, $password);
echo $plaintext;
- Always use a secure, randomly generated password.
- Do not hardcode passwords within your application code.
- I strongly recommend obfuscation for your crypt.js as it will be readable on the client side
- Store and manage passwords and keys securely, using best practices for your environment.
- This code has not been audited for security compliance and is intended for educational purposes.
Contributions are welcome! If you have a suggestion or improvement, please feel free to fork the repository and submit a pull request.
This project is open-sourced under the MIT License. See the LICENSE file for more information.