From d30e950bf9688f6ecf2e98aadf9cad033ef84920 Mon Sep 17 00:00:00 2001 From: Mikunj Date: Mon, 11 Feb 2019 15:00:30 +1100 Subject: [PATCH] Changed hashing algorithm. --- js/link_previews_helper.js | 20 ++++++++------------ js/models/messages.js | 3 ++- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/js/link_previews_helper.js b/js/link_previews_helper.js index adaf8378b..87b1899c5 100644 --- a/js/link_previews_helper.js +++ b/js/link_previews_helper.js @@ -1,6 +1,7 @@ /* global Signal, textsecure, + StringView */ /* eslint-disable no-bitwise */ @@ -61,17 +62,10 @@ }; } - function hashCode(string) { - let hash = 0; - if (string.length === 0) { - return hash; - } - for (let i = 0; i < string.length; i += 1) { - const char = string.charCodeAt(i); - hash = (hash << 5) - hash + char; - hash &= hash; // Convert to 32bit integer - } - return hash; + async function sha256(string) { + const arraybuffer = new TextEncoder('utf-8').encode(string); + const digest = await window.crypto.subtle.digest('SHA-256', arraybuffer); + return StringView.arrayBufferToHex(digest); } async function getPreview(url) { @@ -132,11 +126,13 @@ } } + const hash = await sha256(url); + return { title, url, image, - hash: hashCode(url), + hash, }; } diff --git a/js/models/messages.js b/js/models/messages.js index bc0e4b9b1..2847af3bd 100644 --- a/js/models/messages.js +++ b/js/models/messages.js @@ -159,10 +159,11 @@ const { data } = image; const extension = Attachment.getFileExtension(image); if (data && extension) { + const hash32 = hash.substring(0, 32); try { const filePath = await writeAttachment({ data, - path: `previews/${hash}.${extension}`, + path: `previews/${hash32}.${extension}`, }); // return the image without the data