diff --git a/common/lib/types/message.js b/common/lib/types/message.js index c32ea59536..c73af3039b 100644 --- a/common/lib/types/message.js +++ b/common/lib/types/message.js @@ -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 { @@ -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); }); diff --git a/spec/realtime/crypto.test.js b/spec/realtime/crypto.test.js index a330b35023..e282af1800 100644 --- a/spec/realtime/crypto.test.js +++ b/spec/realtime/crypto.test.js @@ -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 */