Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var winEcrypt = ( ( _w )=>{
let oKey = {};
return {
"base64ToArrayBuffer": function(base64) {
var binary_string = _w.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
},
"rawKeyToCryptoKey": function(key) {
var decodedKey = winEcrypt.base64ToArrayBuffer(key);
return _w.crypto.subtle.importKey(
"raw", decodedKey, "AES-CBC", true, ["encrypt", "decrypt"]
);
},
"arrayBufferToBase64": function(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
for (var i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return _w.btoa(binary);
},
"generateNewKey": function() { // This will generate a valid AES-256 key, and report the value as a Base64 encoded string
var keyPromise = _w.crypto.subtle.generateKey(
{ name: "AES-CBC", length: 256 }, true, ["encrypt", "decrypt"])
.then(
value => {
var exportPromise = crypto.subtle.exportKey("raw", value)
.then(
value => {
oKey.generatedKey = value;
oKey.encodedKey = winEcrypt.arrayBufferToBase64(value);
})
.catch(err => { console.warn( err ) });
}).catch(err => { console.warn( err ) });
},
"getKeyBase64": () => oKey.encodedKey,
"getKeyRaw": () => oKey.generatedKey,
"getEncryptedMsg64": () => oKey.generatedKey,
"generateMessage": function(rawData) {
// This takes in the raw data message and the base64 encoded key, and outputs an encrypted base64 encoded url encoded value for the ud parameter
var self = this;
var message = JSON.stringify(rawData);
console.log("stringified message: " + message);
var enc = new TextEncoder();
var encodedMessage = enc.encode(message);
console.log("encoded message: " + encodedMessage);
var iv = _w.crypto.getRandomValues(new Uint8Array(16));
var keyPromise = winEcrypt.rawKeyToCryptoKey( winEcrypt.getKeyBase64() );
keyPromise.then(
value => {
var encryptionPromise = _w.crypto.subtle.encrypt(
{ name: "AES-CBC", iv},
value, encodedMessage
);
encryptionPromise.then(
value => {
console.log("encrypted message: " + value);
var resultArray = new Uint8Array(value, 0, value.byteLength);
var fullRawResponse = new Uint8Array(iv.length + resultArray.length);
fullRawResponse.set(iv); // set the first 16 bytes to be the IV
fullRawResponse.set(resultArray, iv.length);
var b64message = self.arrayBufferToBase64(fullRawResponse.buffer);
console.log("b64 encoded message: " + b64message);
var eb64eu = encodeURIComponent(b64message);
console.log(eb64eu);
oKey.EncryptedMsg64 = eb64eu;
}).catch(err => { console.log(err) });
}
).catch(err => { console.log(err) });
}
};
} )( window );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment