Skip to content

Commit

Permalink
Merge pull request #438 from ably/fromencoded-with-cipher-keny
Browse files Browse the repository at this point in the history
Allow Message#fromEncoded to take a short-form (key-only) cipherParams
  • Loading branch information
SimonWoolf authored Dec 11, 2017
2 parents d1438ef + a354a86 commit 68b632c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
11 changes: 11 additions & 0 deletions common/lib/types/message.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,18 @@ var Message = (function() {
return result;
};

function normalizeCipherOptions(options) {
if(options && options.cipher && !options.cipher.channelCipher) {
if(!Crypto) throw new Error('Encryption not enabled; use ably.encryption.js instead');
var cipher = Crypto.getCipher(options.cipher);
options.cipher = cipher.cipherParams;
options.channelCipher = cipher.cipher;
}
}

Message.fromEncoded = function(encoded, options) {
var msg = Message.fromValues(encoded);
normalizeCipherOptions(options);
/* if decoding fails at any point, catch and return the message decoded to
* the fullest extent possible */
try {
Expand All @@ -228,6 +238,7 @@ var Message = (function() {
};

Message.fromEncodedArray = function(encodedArray, options) {
normalizeCipherOptions(options);
return Utils.arrMap(encodedArray, function(encoded) {
return Message.fromEncoded(encoded, options);
});
Expand Down
26 changes: 26 additions & 0 deletions spec/realtime/crypto.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,32 @@ define(['ably', 'shared_helper', 'async'], function(Ably, helper, async) {
});
};

exports.fromEncoded_cipher_options = function(test) {
if(!Crypto) {
test.ok(false, 'Encryption not supported');
test.done();
return;
}

loadTestData(testResourcesPath + 'crypto-data-256.json', function(err, testData) {
if(err) {
test.ok(false, 'Unable to get test assets; err = ' + displayError(err));
return;
}
var key = BufferUtils.base64Decode(testData.key);
var iv = BufferUtils.base64Decode(testData.iv);

test.expect(testData.items.length);
for(var i = 0; i < testData.items.length; i++) {
var item = testData.items[i];
var testMessage = Message.fromEncoded(item.encoded);
var decryptedMessage = Message.fromEncoded(item.encrypted, {cipher: {key: key, iv: iv}});
test.ok(compareMessage(testMessage, decryptedMessage));
}
test.done();
});
};

exports.msgpack_128 = function(test) {
if(typeof ArrayBuffer === 'undefined') {
/* Encryption or binary transport not supported */
Expand Down

0 comments on commit 68b632c

Please sign in to comment.