JSFiddle - React, Tailwind, and code Playground
by Abhishek Kumar
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.2.0/crypto-js.min.js"></script>
JavaScript
function wrapKey(key, wrappingKey) {
const keyToWrap = CryptoJS.enc.Hex.parse(key);
const wrappingKeyBytes = CryptoJS.enc.Hex.parse(wrappingKey);
const wrappedKey = CryptoJS.AES.encrypt(keyToWrap, wrappingKeyBytes, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.NoPadding,
}).ciphertext//.toString();
return wrappedKey;
}
function unwrapKey(wrappedKey, wrappingKey) {
const wrappedKeyBytes = CryptoJS.enc.Hex.parse(wrappedKey);
const wrappingKeyBytes = CryptoJS.enc.Hex.parse(wrappingKey);
const unwrappedKey = CryptoJS.AES.decrypt(wrappedKey, wrappingKeyBytes, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.NoPadding,
}).toString();
return unwrappedKey;
}
// Generate a key to wrap
const key = CryptoJS.lib.WordArray.random(16).toString();
// Generate a wrapping key
const wrappingKey = CryptoJS.lib.WordArray.random(32).toString();
// Wrap the key
const wrappedKey = wrapKey(key, wrappingKey);
// Unwrap the key
const unwrappedKey = unwrapKey(wrappedKey, wrappingKey);
// Check if the unwrapped key is the same as the original key
const isSameKey = key === unwrappedKey;
console.log("Is the unwrapped key the same as the original key?", isSameKey, key, wrappingKey, wrappedKey, unwrappedKey);