Please note that the below code is for demonstration purposes only and more complex encryption algorithms and more secure key management schemes should be used in real-world applications. In addition, since the Crypto API needs to run in HTTPS or local environment, the above code cannot run in a normal HTTP environment.
// Encryption function
function encrypt(str, key) {
// Convert the key to a byte array
var keyBytes = new TextEncoder().encode(key);
// Convert the plaintext to a byte array
var textBytes = new TextEncoder().encode(str);
// Generate an AES key using the Crypto API
crypto.subtle.importKey("raw", keyBytes, "AES-CBC", false, ["encrypt"]).then(function(key) {
// Encrypt using AES algorithm
crypto.subtle.encrypt({ name: "AES-CBC", iv: new Uint8Array(16) }, key, textBytes).then(function(encryptedBytes) {
// Convert the encrypted byte array to a Base64 string
var encryptedBase64 = btoa(String.fromCharCode.apply(null, new Uint8Array(encryptedBytes)));
console.log("Encrypted string: ", encryptedBase64);
});
});
}
// Decryption function
function decrypt(encryptedBase64, key) {
// Convert the key to a byte array
var keyBytes = new TextEncoder().encode(key);
// Convert the Base64 string to a byte array
var encryptedBytes = new Uint8Array(atob(encryptedBase64).split("").map(function(c) { return c.charCodeAt(0); }));
// Generate an AES key using the Crypto API
crypto.subtle.importKey("raw", keyBytes, "AES-CBC", false, ["decrypt"]).then(function(key) {
// Decrypt using AES algorithm
crypto.subtle.decrypt({ name: "AES-CBC", iv: new Uint8Array(16) }, key, encryptedBytes).then(function(decryptedBytes) {
// Convert the decrypted byte array to a string
var decryptedText = new TextDecoder().decode(decryptedBytes);
console.log("Decrypted string: ", decryptedText);
});
});
}
// Example code
var key = "MySecretKey12345"; // Key, can be any string of any length
var plaintext = "Hello World!"; // String to be encrypted
encrypt(plaintext, key);
var ciphertext = "q3Hx4zA4PTGZf41zZSSbEg=="; // Encrypted string, can be obtained from the encrypt function
decrypt(ciphertext, key);