Lilia's Webcrypto branch rebased and a few very tiny tweaks

This commit is contained in:
lilia 2014-04-03 23:33:02 -07:00 committed by Matt Corallo
parent ab6ebbab16
commit 41d50d7480
7 changed files with 270 additions and 143 deletions

View file

@ -14,6 +14,8 @@
<html> <html>
<head> <head>
<script type="text/javascript" src="js/webcrypto.js"></script>
<script type="text/javascript" src="js/crypto.js"></script>
<script type="text/javascript" src="js-deps/nacl-common.js"></script> <script type="text/javascript" src="js-deps/nacl-common.js"></script>
<script type="text/javascript" src="js-deps/jquery.js"></script> <script type="text/javascript" src="js-deps/jquery.js"></script>
<script type="text/javascript" src="js-deps/core.js"></script> <script type="text/javascript" src="js-deps/core.js"></script>

15
js/crypto.js Normal file
View file

@ -0,0 +1,15 @@
function HmacSHA256(key, input) {
return window.crypto.subtle.sign({name: "HMAC", hash: "SHA-256"}, key, input);
}
function encryptAESCTR(input, key, counter) {
return window.crypto.subtle.encrypt({name: "AES-CTR", counter: counter}, key, input);
}
function decryptAESCTR(input, key, counter) {
return window.crypto.subtle.decrypt({name: "AES-CTR", counter: counter}, key, input);
}
function decryptAESCBC(input, key, iv) {
return window.crypto.subtle.decrypt({name: "AES-CBC", iv: iv}, key, input);
}

View file

@ -13,6 +13,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
/* START CRAP TO BE DELETED */
//TODO: Stolen from MDN (copyright...) //TODO: Stolen from MDN (copyright...)
function b64ToUint6 (nChr) { function b64ToUint6 (nChr) {
@ -88,11 +89,22 @@ function base64EncArr (aBytes) {
} }
/* END CRAP TO BE DELETED */
var USE_NACL = false; var USE_NACL = false;
/********************************* /*********************************
*** Type conversion utilities *** *** Type conversion utilities ***
*********************************/ *********************************/
function intToArrayBuffer(nInt) {
return new ArrayBuffer([
(nInt >> 24) && 0xFF,
(nInt >> 16) && 0xFF,
(nInt >> 8) && 0xFF,
nInt && 0xFF
]);
}
// Strings/arrays // Strings/arrays
//TODO: Throw all this shit in favor of consistent types //TODO: Throw all this shit in favor of consistent types
var StaticByteBufferProto = new dcodeIO.ByteBuffer().__proto__; var StaticByteBufferProto = new dcodeIO.ByteBuffer().__proto__;
@ -543,24 +555,17 @@ var crypto_tests = {};
} }
var ECDHE = function(pubKey, privKey, callback) { return crypto_tests.ECDHE(pubKey, privKey, callback); } var ECDHE = function(pubKey, privKey, callback) { return crypto_tests.ECDHE(pubKey, privKey, callback); }
var HMACSHA256 = function(input, key) {
//TODO: Waaayyyy less type conversion here (probably just means replacing CryptoJS)
return CryptoJS.HmacSHA256(
CryptoJS.lib.WordArray.create(toArrayBuffer(input)),
CryptoJS.enc.Latin1.parse(getString(key)))
.toString(CryptoJS.enc.Latin1);
}
crypto_tests.HKDF = function(input, salt, info) { crypto_tests.HKDF = function(input, salt, info) {
// Specific implementation of RFC 5869 that only returns exactly 64 bytes // Specific implementation of RFC 5869 that only returns exactly 64 bytes
var PRK = HMACSHA256(input, salt); return HmacSHA256(salt, input).then(function(PRK) {
var infoString = getString(info); var infoString = getString(info);
// TextSecure implements a slightly tweaked version of RFC 5869: the 0 and 1 should be 1 and 2 here // TextSecure implements a slightly tweaked version of RFC 5869: the 0 and 1 should be 1 and 2 here
var T1 = HMACSHA256(infoString + String.fromCharCode(0), PRK); return HmacSHA256(PRK, infoString + String.fromCharCode(0)).then(function(T1) {
var T2 = HMACSHA256(getString(T1) + infoString + String.fromCharCode(1), PRK); return HmacSHA256(PRK, getString(T1) + infoString + String.fromCharCode(1)).then(function(T2) {
return [ T1, T2 ]; return [ T1, T2 ];
});
});
});
} }
var HKDF = function(input, salt, info) { var HKDF = function(input, salt, info) {
@ -580,48 +585,23 @@ var crypto_tests = {};
return crypto_tests.HKDF(input, salt, info); return crypto_tests.HKDF(input, salt, info);
} }
var decryptPaddedAES = function(ciphertext, key, iv) {
//TODO: Waaayyyy less type conversion here (probably just means replacing CryptoJS)
return CryptoJS.AES.decrypt(btoa(getString(ciphertext)),
CryptoJS.enc.Latin1.parse(getString(key)),
{iv: CryptoJS.enc.Latin1.parse(getString(iv))})
.toString(CryptoJS.enc.Latin1);
}
var decryptAESCTR = function(ciphertext, key, counter) {
//TODO: Waaayyyy less type conversion here (probably just means replacing CryptoJS)
var iv = String.fromCharCode(counter & 0xff000000) + String.fromCharCode(counter & 0xff0000) + String.fromCharCode(counter & 0xff00) + String.fromCharCode(counter & 0xff);
return CryptoJS.AES.decrypt(btoa(getString(ciphertext)),
CryptoJS.enc.Latin1.parse(getString(key)),
{mode: CryptoJS.mode.CTR, iv: CryptoJS.enc.Latin1.parse(iv), padding: CryptoJS.pad.NoPadding})
.toString(CryptoJS.enc.Latin1);
}
var encryptAESCTR = function(plaintext, key, counter) {
//TODO: Waaayyyy less type conversion here (probably just means replacing CryptoJS)
var iv = String.fromCharCode(counter & 0xff000000) + String.fromCharCode(counter & 0xff0000) + String.fromCharCode(counter & 0xff00) + String.fromCharCode(counter & 0xff);
return CryptoJS.AES.encrypt(CryptoJS.enc.Latin1.parse(getString(plaintext)),
CryptoJS.enc.Latin1.parse(getString(key)),
{mode: CryptoJS.mode.CTR, iv: CryptoJS.enc.Latin1.parse(iv), padding: CryptoJS.pad.NoPadding})
.ciphertext.toString(CryptoJS.enc.Latin1);
}
var verifyMACWithVersionByte = function(data, key, mac, version) { var verifyMACWithVersionByte = function(data, key, mac, version) {
if (version === undefined) if (version === undefined)
version = 1; version = 1;
var calculated_mac = HMACSHA256(String.fromCharCode(version) + getString(data), key); HmacSHA256(key, String.fromCharCode(version) + getString(data)).then(function(calculated_mac) {
var macString = getString(mac); var macString = getString(mac);
if (calculated_mac.substring(0, macString.length) != macString) if (calculated_mac.substring(0, macString.length) != macString)
throw new Error("Bad MAC"); throw new Error("Bad MAC");
});
} }
var calculateMACWithVersionByte = function(data, key, version) { var calculateMACWithVersionByte = function(data, key, version) {
if (version === undefined) if (version === undefined)
version = 1; version = 1;
return HMACSHA256(String.fromCharCode(version) + getString(data), key); return HmacSHA256(key, String.fromCharCode(version) + getString(data));
} }
/****************************** /******************************
@ -631,7 +611,7 @@ var crypto_tests = {};
var ratchet = session.currentRatchet; var ratchet = session.currentRatchet;
ECDHE(remoteKey, ratchet.ephemeralKeyPair.privKey, function(sharedSecret) { ECDHE(remoteKey, ratchet.ephemeralKeyPair.privKey, function(sharedSecret) {
var masterKey = HKDF(sharedSecret, ratchet.rootKey, "WhisperRatchet"); HKDF(sharedSecret, ratchet.rootKey, "WhisperRatchet").then(function(masterKey) {
if (sending) if (sending)
session[getString(ratchet.ephemeralKeyPair.pubKey)] = { messageKeys: {}, chainKey: { counter: -1, key: masterKey[1] } }; session[getString(ratchet.ephemeralKeyPair.pubKey)] = { messageKeys: {}, chainKey: { counter: -1, key: masterKey[1] } };
else else
@ -639,6 +619,7 @@ var crypto_tests = {};
ratchet.rootKey = masterKey[0]; ratchet.rootKey = masterKey[0];
callback(); callback();
}); });
});
} }
var initSession = function(isInitiator, ourEphemeralKey, encodedNumber, theirIdentityPubKey, theirEphemeralPubKey, callback) { var initSession = function(isInitiator, ourEphemeralKey, encodedNumber, theirIdentityPubKey, theirEphemeralPubKey, callback) {
@ -651,8 +632,8 @@ var crypto_tests = {};
function finishInit() { function finishInit() {
ECDHE(theirEphemeralPubKey, ourEphemeralKey.privKey, function(ecRes) { ECDHE(theirEphemeralPubKey, ourEphemeralKey.privKey, function(ecRes) {
sharedSecret += getString(ecRes); sharedSecret += getString(ecRes);
var masterKey = HKDF(sharedSecret, '', "WhisperText");
HKDF(sharedSecret, '', "WhisperText").then(function(masterKey) {
var session = {currentRatchet: { rootKey: masterKey[0], lastRemoteEphemeralKey: theirEphemeralPubKey }, var session = {currentRatchet: { rootKey: masterKey[0], lastRemoteEphemeralKey: theirEphemeralPubKey },
oldRatchetList: [] oldRatchetList: []
}; };
@ -673,6 +654,7 @@ var crypto_tests = {};
callback(); callback();
} }
}); });
});
} }
if (isInitiator) { if (isInitiator) {
@ -707,16 +689,20 @@ var crypto_tests = {};
var fillMessageKeys = function(chain, counter) { var fillMessageKeys = function(chain, counter) {
if (chain.chainKey.counter + 1000 < counter) //TODO: maybe 1000 is too low/high in some cases? if (chain.chainKey.counter + 1000 < counter) //TODO: maybe 1000 is too low/high in some cases?
return; // Stalker, much? return new Promise(function(resolve) { resolve() }); // Stalker, much?
var messageKeys = chain.messageKeys; if (chain.chainKey.counter < counter) {
var key = chain.chainKey.key; return HmacSHA256(chain.chainKey.key, String.fromCharCode(1)).then(function(mac) {
for (var i = chain.chainKey.counter; i < counter; i++) { HmacSHA256(chain.chainKey.key, String.fromCharCode(2)).then(function(key) {
messageKeys[i + 1] = HMACSHA256(String.fromCharCode(1), key); chain.messageKeys[chain.chainKey.counter + 1] = mac;
key = HMACSHA256(String.fromCharCode(2), key); chain.chainKey.key = key
chain.chainKey.counter += 1;
fillMessageKeys(chain, counter);//XXX: return?
});
});
} else {
return new Promise(function(resolve) { resolve() });
} }
chain.chainKey.key = key;
chain.chainKey.counter = counter;
} }
var maybeStepRatchet = function(session, remoteKey, previousCounter, callback) { var maybeStepRatchet = function(session, remoteKey, previousCounter, callback) {
@ -727,15 +713,7 @@ var crypto_tests = {};
var ratchet = session.currentRatchet; var ratchet = session.currentRatchet;
var previousRatchet = session[getString(ratchet.lastRemoteEphemeralKey)]; var finish = function() {
if (previousRatchet !== undefined) {
fillMessageKeys(previousRatchet, previousCounter);
if (!objectContainsKeys(previousRatchet.messageKeys))
delete session[getString(ratchet.lastRemoteEphemeralKey)];
else
session.oldRatchetList[session.oldRatchetList.length] = { added: new Date().getTime(), ephemeralKey: ratchet.lastRemoteEphemeralKey };
}
calculateRatchet(session, remoteKey, false, function() { calculateRatchet(session, remoteKey, false, function() {
// Now swap the ephemeral key and calculate the new sending chain // Now swap the ephemeral key and calculate the new sending chain
var previousRatchet = getString(ratchet.ephemeralKeyPair.pubKey); var previousRatchet = getString(ratchet.ephemeralKeyPair.pubKey);
@ -757,6 +735,19 @@ var crypto_tests = {};
}); });
} }
var previousRatchet = session[getString(ratchet.lastRemoteEphemeralKey)];
if (previousRatchet !== undefined) {
fillMessageKeys(previousRatchet, previousCounter).then(function() {
if (!objectContainsKeys(previousRatchet.messageKeys))
delete session[getString(ratchet.lastRemoteEphemeralKey)];
else
session.oldRatchetList[session.oldRatchetList.length] = { added: new Date().getTime(), ephemeralKey: ratchet.lastRemoteEphemeralKey };
finish();
});
} else
finish();
}
// returns decrypted protobuf // returns decrypted protobuf
var decryptWhisperMessage = function(encodedNumber, messageBytes, callback) { var decryptWhisperMessage = function(encodedNumber, messageBytes, callback) {
var session = crypto_storage.getSession(encodedNumber); var session = crypto_storage.getSession(encodedNumber);
@ -774,12 +765,13 @@ var crypto_tests = {};
maybeStepRatchet(session, message.ephemeralKey, message.previousCounter, function() { maybeStepRatchet(session, message.ephemeralKey, message.previousCounter, function() {
var chain = session[getString(message.ephemeralKey)]; var chain = session[getString(message.ephemeralKey)];
fillMessageKeys(chain, message.counter); fillMessageKeys(chain, message.counter).then(function() {
var keys = HKDF(chain.messageKeys[message.counter], '', "WhisperMessageKeys"); HKDF(chain.messageKeys[message.counter], '', "WhisperMessageKeys").then(function(keys) {
delete chain.messageKeys[message.counter]; delete chain.messageKeys[message.counter];
verifyMACWithVersionByte(messageProto, keys[1], mac, (2 << 4) | 2); verifyMACWithVersionByte(messageProto, keys[1], mac, (2 << 4) | 2);
var plaintext = decryptAESCTR(message.ciphertext, keys[0], message.counter); var iv = getString(intToArrayBuffer(message.counter));
decryptAESCTR(message.ciphertext, keys[0], iv).then(function(plaintext) {
//TODO: removeOldChains(session); //TODO: removeOldChains(session);
delete session['pendingPreKey']; delete session['pendingPreKey'];
@ -787,6 +779,9 @@ var crypto_tests = {};
crypto_storage.saveSession(encodedNumber, session); crypto_storage.saveSession(encodedNumber, session);
callback(decodePushMessageContentProtobuf(plaintext)); callback(decodePushMessageContentProtobuf(plaintext));
}); });
});
});
});
} }
/************************* /*************************
@ -809,7 +804,7 @@ var crypto_tests = {};
verifyMACWithVersionByte(ivAndCipherText, mac_key, mac); verifyMACWithVersionByte(ivAndCipherText, mac_key, mac);
return decryptPaddedAES(ciphertext, aes_key, iv); return decryptAESCBC(ciphertext, aes_key, iv);
} }
crypto.handleIncomingPushMessageProto = function(proto, callback) { crypto.handleIncomingPushMessageProto = function(proto, callback) {
@ -846,21 +841,26 @@ var crypto_tests = {};
msg.ephemeralKey = toArrayBuffer(session.currentRatchet.ephemeralKeyPair.pubKey); msg.ephemeralKey = toArrayBuffer(session.currentRatchet.ephemeralKeyPair.pubKey);
var chain = session[getString(msg.ephemeralKey)]; var chain = session[getString(msg.ephemeralKey)];
fillMessageKeys(chain, chain.chainKey.counter + 1); fillMessageKeys(chain, chain.counter + 1).then(function() {
var keys = HKDF(chain.messageKeys[chain.chainKey.counter], '', "WhisperMessageKeys"); HKDF(chain.messageKeys[chain.chainKey.counter], '', "WhisperMessageKeys").then(function(keys) {
delete chain.messageKeys[chain.chainKey.counter]; delete chain.messageKeys[chain.chainKey.counter];
msg.counter = chain.chainKey.counter; msg.counter = chain.chainKey.counter;
msg.previousCounter = session.currentRatchet.previousCounter; msg.previousCounter = session.currentRatchet.previousCounter;
msg.ciphertext = toArrayBuffer(encryptAESCTR(plaintext, keys[0], chain.chainKey.counter)); var iv = intToArrayBuffer(chain.counter);
encryptAESCTR(plaintext, keys[0], iv).then(function(ciphertext) {
msg.ciphertext = ciphertext;
var encodedMsg = getString(msg.encode()); var encodedMsg = getString(msg.encode());
var mac = calculateMACWithVersionByte(encodedMsg, keys[1], (2 << 4) | 2); calculateMACWithVersionByte(encodedMsg, keys[1], (2 << 4) | 2).then(function(mac) {
var result = String.fromCharCode((2 << 4) | 2) + encodedMsg + mac.substring(0, 8); var result = String.fromCharCode((2 << 4) | 2) + encodedMsg + mac.substring(0, 8);
crypto_storage.saveSession(deviceObject.encodedNumber, session); crypto_storage.saveSession(deviceObject.encodedNumber, session);
callback(result); callback(result);
});
});
});
});
} }
var preKeyMsg = new PreKeyWhisperMessageProtobuf(); var preKeyMsg = new PreKeyWhisperMessageProtobuf();
@ -979,27 +979,19 @@ function subscribeToPush(message_callback) {
if (message.type == 3) { if (message.type == 3) {
console.log("Got pong message"); console.log("Got pong message");
} else if (message.type === undefined && message.id !== undefined) { } else if (message.type === undefined && message.id !== undefined) {
var proto; crypto.decryptWebsocketMessage(message.message).then(function(plaintext) {
try {
var plaintext = crypto.decryptWebsocketMessage(message.message);
var proto = decodeIncomingPushMessageProtobuf(plaintext); var proto = decodeIncomingPushMessageProtobuf(plaintext);
// After this point, a) decoding errors are not the server's fault, and // After this point, a) decoding errors are not the server's fault, and
// b) we should handle them gracefully and tell the user they received an invalid message // b) we should handle them gracefully and tell the user they received an invalid message
console.log("Successfully decoded message with id: " + message.id); console.log("Successfully decoded message with id: " + message.id);
socket.send(JSON.stringify({type: 1, id: message.id})); socket.send(JSON.stringify({type: 1, id: message.id}));
} catch (e) {
console.log("Error decoding message: " + e);
return;
}
try {
crypto.handleIncomingPushMessageProto(proto, function(decrypted) { crypto.handleIncomingPushMessageProto(proto, function(decrypted) {
storeMessage(decrypted); storeMessage(decrypted);
message_callback(decrypted); message_callback(decrypted);
}); // Decrypts/decodes/fills in fields/etc }); // Decrypts/decodes/fills in fields/etc
} catch (e) { }).catch(function(e) {
//TODO: Tell the user decryption failed console.log("Error decoding message: " + e);
} });
} }
}; };
} }

View file

@ -192,10 +192,11 @@ registerOnLoadFunction(function() {
for (var i = 0; i < 10; i++) for (var i = 0; i < 10; i++)
info[i] = 240 + i; info[i] = 240 + i;
var OKM = crypto_tests.HKDF(IKM, salt, info); crypto_tests.HKDF(IKM, salt, info).then(function(OKM){
var T1 = hexToArrayBuffer("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf"); var T1 = hexToArrayBuffer("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf");
var T2 = hexToArrayBuffer("34007208d5b887185865"); var T2 = hexToArrayBuffer("34007208d5b887185865");
callback(getString(OKM[0]) == getString(T1) && getString(OKM[1]).substring(0, 10) == getString(T2)); callback(getString(OKM[0]) == getString(T1) && getString(OKM[1]).substring(0, 10) == getString(T2));
}, console.log);
}, "HMAC RFC5869 Test vectors");*/ }, "HMAC RFC5869 Test vectors");*/
var axolotlTwoPartyTestVectorsAlice = [ var axolotlTwoPartyTestVectorsAlice = [
@ -429,6 +430,45 @@ registerOnLoadFunction(function() {
axolotlTestVectors(axolotlTwoPartyTestVectorsBob, { encodedNumber: "ALICE" }, callback); axolotlTestVectors(axolotlTwoPartyTestVectorsBob, { encodedNumber: "ALICE" }, callback);
}, "Shuffled Axolotl Test Vectors as Bob", true); }, "Shuffled Axolotl Test Vectors as Bob", true);
TEST(function(callback) {
var key = getString(hexToArrayBuffer('6f35628d65813435534b5d67fbdb54cb33403d04e843103e6399f806cb5df95febbdd61236f33245'));
var input = getString(hexToArrayBuffer('752cff52e4b90768558e5369e75d97c69643509a5e5904e0a386cbe4d0970ef73f918f675945a9aefe26daea27587e8dc909dd56fd0468805f834039b345f855cfe19c44b55af241fff3ffcd8045cd5c288e6c4e284c3720570b58e4d47b8feeedc52fd1401f698a209fccfa3b4c0d9a797b046a2759f82a54c41ccd7b5f592b'));
var mac = getString(hexToArrayBuffer('05d1243e6465ed9620c9aec1c351a186'));
HmacSHA256(key, input).then(function(result) {
callback(result.substring(0, mac.length) === mac)
});
}, "HMAC SHA-256", true);
TEST(function(callback) {
var key = getString(hexToArrayBuffer('2b7e151628aed2a6abf7158809cf4f3c'));
var counter = getString(hexToArrayBuffer('f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'));
var plaintext = getString(hexToArrayBuffer('6bc1bee22e409f96e93d7e117393172a'));
var ciphertext = getString(hexToArrayBuffer('874d6191b620e3261bef6864990db6ce'));
encryptAESCTR(plaintext, key, counter).then(function(result) {
callback(result === ciphertext);
});
}, "Encrypt AES-CTR", true);
TEST(function(callback) {
var key = getString(hexToArrayBuffer('2b7e151628aed2a6abf7158809cf4f3c'));
var counter = getString(hexToArrayBuffer('f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'));
var plaintext = getString(hexToArrayBuffer('6bc1bee22e409f96e93d7e117393172a'));
var ciphertext = getString(hexToArrayBuffer('874d6191b620e3261bef6864990db6ce'));
decryptAESCTR(ciphertext, key, counter).then(function(result) {
callback(result === plaintext);
});
}, "Decrypt AES-CTR", true);
TEST(function(callback) {
var key = getString(hexToArrayBuffer('603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'));
var iv = getString(hexToArrayBuffer('000102030405060708090a0b0c0d0e0f'));
var plaintext = getString(hexToArrayBuffer('6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710'));
var ciphertext = getString(hexToArrayBuffer('f58c4c04d6e5f1ba779eabfb5f7bfbd69cfc4e967edb808d679f777bc6702c7d39f23369a9d9bacfa530e26304231461b2eb05e2c39be9fcda6c19078c6a9d1b3f461796d6b0d6b2e0c2a72b4d80e644'));
decryptAESCBC(ciphertext, key, iv).then(function(result) {
callback(result === plaintext);
});
}, "Decrypt AES-CBC", true);
// Setup test timeouts (note that this will only work if things are actually // Setup test timeouts (note that this will only work if things are actually
// being run async, ie in the case of NaCL) // being run async, ie in the case of NaCL)
window.setInterval(function() { window.setInterval(function() {

74
js/webcrypto.js Normal file
View file

@ -0,0 +1,74 @@
/* Web Crypto polyfill. TODO: replace with web crypto */
// All inputs/outputs are arraybuffers!
window.crypto.subtle = (function() {
if (window.crypto.subtle !== undefined && window.crypto.subtle !== null) {
return window.crypto.subtle;
} else {
// private implementation functions
function HmacSHA256(key, input) {
return CryptoJS.HmacSHA256(
CryptoJS.lib.WordArray.create(toArrayBuffer(input)),
CryptoJS.enc.Latin1.parse(getString(key))
).toString(CryptoJS.enc.Latin1);
};
function encryptAESCTR(plaintext, key, counter) {
return CryptoJS.AES.encrypt(CryptoJS.enc.Latin1.parse(getString(plaintext)),
CryptoJS.enc.Latin1.parse(getString(key)),
{mode: CryptoJS.mode.CTR, iv: CryptoJS.enc.Latin1.parse(getString(counter)),
padding: CryptoJS.pad.NoPadding})
.ciphertext.toString(CryptoJS.enc.Latin1);
};
function decryptAESCTR(ciphertext, key, counter) {
return CryptoJS.AES.decrypt(btoa(getString(ciphertext)),
CryptoJS.enc.Latin1.parse(getString(key)),
{mode: CryptoJS.mode.CTR, iv: CryptoJS.enc.Latin1.parse(getString(counter)),
padding: CryptoJS.pad.NoPadding})
.toString(CryptoJS.enc.Latin1);
};
function decryptAESCBC(ciphertext, key, iv) {
return CryptoJS.AES.decrypt(btoa(getString(ciphertext)),
CryptoJS.enc.Latin1.parse(getString(key)),
{iv: CryptoJS.enc.Latin1.parse(getString(iv))})
.toString(CryptoJS.enc.Latin1);
};
// utility function for connecting front and back ends via promises
// Takes an implementation function and 0 or more arguments
function promise(implementation) {
var args = Array.prototype.slice.call(arguments);
args.shift();
return new Promise(function(resolve) {
resolve(implementation.apply(this, args));
});
}
// public interface functions
function encrypt(algorithm, key, data) {
if (algorithm.name === "AES-CTR") {
return promise(encryptAESCTR, data, key, algorithm.counter);
}
};
function decrypt(algorithm, key, data) {
if (algorithm.name === "AES-CTR") {
return promise(decryptAESCTR, data, key, algorithm.counter);
}
if (algorithm.name === "AES-CBC") {
return promise(decryptAESCBC, data, key, algorithm.iv);
}
};
function sign(algorithm, key, data) {
if (algorithm.name === "HMAC" && algorithm.hash === "SHA-256") {
return promise(HmacSHA256, key, data);
}
};
return {
encrypt : encrypt,
decrypt : decrypt,
sign : sign,
}
}
})();

View file

@ -46,6 +46,8 @@
</ul> </ul>
</div> </div>
<script type="text/javascript" src="js/webcrypto.js"></script>
<script type="text/javascript" src="js/crypto.js"></script>
<script type="text/javascript" src="js-deps/nacl-common.js"></script> <script type="text/javascript" src="js-deps/nacl-common.js"></script>
<script type="text/javascript" src="js-deps/jquery.js"></script> <script type="text/javascript" src="js-deps/jquery.js"></script>
<script type="text/javascript" src="js-deps/core.js"></script> <script type="text/javascript" src="js-deps/core.js"></script>

View file

@ -24,6 +24,8 @@
<div id="tests"> <div id="tests">
</div> </div>
<script type="text/javascript" src="js/webcrypto.js"></script>
<script type="text/javascript" src="js/crypto.js"></script>
<script type="text/javascript" src="js-deps/nacl-common.js"></script> <script type="text/javascript" src="js-deps/nacl-common.js"></script>
<script type="text/javascript" src="js-deps/jquery.js"></script> <script type="text/javascript" src="js-deps/jquery.js"></script>
<script type="text/javascript" src="js-deps/core.js"></script> <script type="text/javascript" src="js-deps/core.js"></script>