-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcs255-backup.js
More file actions
1736 lines (1480 loc) · 48.2 KB
/
cs255-backup.js
File metadata and controls
1736 lines (1480 loc) · 48.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @namespace CS255-bhat-kulasinghe
// @name CS255-bhat-kulasinghe
// @description CS255-bhat-kulasinghe - CS255 Assignment 1
// @version 1.4
//
//
// @include http://www.facebook.com/*
// @include https://www.facebook.com/*
// @exclude http://www.facebook.com/messages/*
// @exclude https://www.facebook.com/messages/*
// @exclude http://www.facebook.com/events/*
// @exclude https://www.facebook.com/events/*
// ==/UserScript==
/*
Step 1: change @namespace, @name, and @description above.
Step 2: Change the filename to the format "CS255-Lastname1-Lastname2.user.js"
Step 3: Fill in the functions below.
*/
// Strict mode makes it easier to catch errors.
// You may comment this out if you want.
// See http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
"use strict";
var my_username; // user signed in as
var keys = {}; // association map of keys: group -> key
// Some initialization functions are called at the very end of this script.
// You only have to edit the top portion.
// Return the encryption of the message for the given group, in the form of a string.
//
// @param {String} plainText String to encrypt.
// @param {String} group Group name.
// @return {String} Encryption of the plaintext, encoded as a string.
function Encrypt(plainText, group) {
// CS255-todo: encrypt the plainText, using key for the group.
var cipher = new sjcl.cipher.aes(keys[group]);
if ((plainText.indexOf('aes:') == 0) || (plainText.length < 1)) {
// already done, or blank
alert("Try entering a message (the button works only once)");
return plainText;
} else {
// encrypt, add tag.
return 'aes:' + cipher.encrypt(plainText);
}
}
// Return the decryption of the message for the given group, in the form of a string.
// Throws an error in case the string is not properly encrypted.
//
// @param {String} cipherText String to decrypt.
// @param {String} group Group name.
// @return {String} Decryption of the ciphertext.
function Decrypt(cipherText, group) {
// CS255-todo: implement decryption on encrypted messages
var cipher = new sjcl.cipher.aes(keys[group]);
if (cipherText.indexOf('aes:') == 0) {
// decrypt, ignore the tag.
var decryptedMsg = cipher.decrypt(cipherText.slice(4));
return decryptedMsg;
} else {
throw "not encrypted";
}
}
// Generate a new key for the given group.
//
// @param {String} group Group name.
function GenerateKey(group) {
debugger;
var key = GetRandomValues(128);
console.log(sjcl.codec.base64.fromBits(key).length);
keys[group] = sjcl.codec.base64.fromBits(key);
console.log("Generated key for group. Now saving key-database");
SaveKeys();
}
//encrypt a given base64 string. used in SaveKeys()
function KeyEncrypt(cipher, ptext){
var key_bits = sjcl.codec.base64.toBits(ptext); //convert flattened key-database to bit array
// Padding
var extraWords = 4 - key_bits.length % 4;
if (extraWords != 4)
{
var padding = [];
padding[0] = 1 << 31;
for (var i = 1; i<extraWords; i++) padding[i] = 0;
key_bits = sjcl.bitArray.concat(key_bits,padding);
}
//Encrypting
var encrypted_arr = [];
for(var i=0; i<key_bits.length; i+=4)
{
var wordBlock = sjcl.bitArray.bitSlice(key_bits,32*i,32*i+128);
var ctext = cipher.encrypt(wordBlock);
encrypted_arr = sjcl.bitArray.concat(encrypted_arr,ctext);
}
return sjcl.codec.base64.fromBits(encrypted_arr);
}
//decrypt a given base64 string. used in LoadKeys()
function KeyDecrypt(cipher, ctext){
var key_bits = sjcl.codec.base64.toBits(ctext); //convert flattened key-database to bit array
var decrypted_arr = [];
for(var i=0; i<key_bits.length; i+=4)
{
var wordBlock = sjcl.bitArray.bitSlice(key_bits,32*i,32*i+128);
var ptext = cipher.decrypt(wordBlock);
decrypted_arr = sjcl.bitArray.concat(decrypted_arr,ptext);
}
//Remove Padding
var shift = 0;
for(var i = decrypted_arr.length - 1; i>0; i--)
{
shift++;
if(decrypted_arr[i] == (1<<31))
{
decrypted_arr.length -= shift;
break;
}
else if(decrypted_arr[i] != 0) break;
}
return sjcl.codec.base64.fromBits(decrypted_arr);
}
// Take the current group keys, and save them to disk.
function SaveKeys() {
debugger;
if(my_username == null){
console.log("No username detected, cancelling key save.");
return;
}
//Obtain user key / cipher
var userKey = getUserKey();
console.log("Obtained user key in SaveKeys()");
var cipher = new sjcl.cipher.aes(userKey);
var keys_en = {}
for(var group in keys)
{
var group_en = KeyEncrypt(cipher, group);
keys_en[group_en] = KeyEncrypt(cipher, keys[group]);
}
var encrypted_str = JSON.stringify(keys_en);
console.log("Finished encrypting key-database");
cs255.localStorage.setItem('facebook-keys-' + my_username, encodeURIComponent(encrypted_str));
console.log("Saved current key-database");
}
// Load the group keys from disk.
function LoadKeys() {
debugger;
if(my_username == null){
console.log("No username detected, cancelling key load.");
return;
}
//obtain keys / reset current key-database
var userKey = getUserKey();
console.log("Obtained user key in LoadKeys()");
keys = {}; // Reset the keys.
var saved = cs255.localStorage.getItem('facebook-keys-' + my_username);
if(saved)
{
var cipher = new sjcl.cipher.aes(userKey); //generate cipher from user key
var keys_en = JSON.parse(decodeURIComponent(saved));
for(var group_en in keys_en)
{
var group = KeyDecrypt(cipher, group_en);
keys[group] = KeyDecrypt(cipher, keys_en[group_en]);
}
var key_str = JSON.stringify(keys);
console.log("Loaded current key-database");
}
else console.log("No group keys detected.");
}
function getUserKey()
{
debugger;
console.log("Getting user key for " + my_username);
//check if user already entered key-database pw
var storeddbKey = sessionStorage.getItem('user-keys-' + my_username);
if (!storeddbKey)
{
//obtain password (assume it is correct for now)
var dbpass = prompt('Enter key database password');
//obtain salt, generate it if not already there
var stored_salt = localStorage.getItem('user-salt-' + my_username);
if (stored_salt)
{
var salt = JSON.parse(decodeURIComponent(stored_salt));
console.log("Retrieved salt.");
}
else
{
console.log("Salt not found, generating now.");
var salt = GetRandomValues(128);
var save_salt = JSON.stringify(salt);
cs255.localStorage.setItem('user-salt-' + my_username,encodeURIComponent(save_salt));
}
var keyArray = sjcl.misc.pbkdf2(dbpass, salt, null, 128);
var key_str = sjcl.codec.base64.fromBits(keyArray);
sessionStorage.setItem('user-keys-' + my_username,encodeURIComponent(key_str));
}
else
{
var key_str = decodeURIComponent(storeddbKey);
var keyArray = sjcl.codec.base64.toBits(key_str);
}
return keyArray;
}
var cs255 = {
localStorage: {
setItem: function(key, value) {
localStorage.setItem(key, value);
var newEntries = {};
newEntries[key] = value;
chrome.storage.local.set(newEntries);
},
getItem: function(key) {
return localStorage.getItem(key);
},
clear: function() {
chrome.storage.local.clear();
}
}
}
if (typeof chrome.storage === "undefined") {
var id = function() {};
chrome.storage = {local: {get: id, set: id}};
}
else {
// See if there are any values stored with the extension.
chrome.storage.local.get(null, function(onDisk) {
for (key in onDisk) {
localStorage.setItem(key, onDisk[key]);
}
});
}
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
//
// Using the AES primitives from SJCL for this assignment.
//
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
/*
Here are the basic cryptographic functions (implemented farther down)
you need to do the assignment:
function sjcl.cipher.aes(key)
This function creates a new AES encryptor/decryptor with a given key.
Note that the key must be an array of 4, 6, or 8 32-bit words for the
function to work. For those of you keeping score, this constructor does
all the scheduling needed for the cipher to work.
encrypt: function(plaintext)
This function encrypts the given plaintext. The plaintext argument
should take the form of an array of four (32-bit) integers, so the plaintext
should only be one block of data.
decrypt: function(ciphertext)
This function decrypts the given ciphertext. Again, the ciphertext argument
should be an array of 4 integers.
A silly example of this in action:
var key1 = new Array(8);
var cipher = new sjcl.cipher.aes(key1);
var dumbtext = new Array(4);
dumbtext[0] = 1; dumbtext[1] = 2; dumbtext[2] = 3; dumbtext[3] = 4;
var ctext = cipher.encrypt(dumbtext);
var outtext = cipher.decrypt(ctext);
Obviously our key is just all zeroes in this case, but this should illustrate
the point.
*/
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
//
// Should not _have_ to change anything below here.
// Helper functions and sample code.
//
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
// Get n 32-bit-integers entropy as an array. Defaults to 1 word
function GetRandomValues(n) {
var entropy = new Int32Array(n);
// This should work in WebKit.
window.crypto.getRandomValues(entropy);
// Typed arrays can be funky,
// so let's convert it to a regular array for our purposes.
var regularArray = [];
for (var i = 0; i < entropy.length; i++) {
regularArray.push(entropy[i]);
}
return regularArray;
}
// From http://aymanh.com/9-javascript-tips-you-may-not-know#Assertion
// Just in case you want an assert() function
function AssertException(message) {
this.message = message;
}
AssertException.prototype.toString = function() {
return 'AssertException: ' + this.message;
}
function assert(exp, message) {
if (!exp) {
throw new AssertException(message);
}
}
// Very primitive encryption.
function rot13(text) {
// JS rot13 from http://jsfromhell.com/string/rot13
return text.replace(/[a-zA-Z]/g,
function(c) {
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
});
}
function SetupUsernames() {
// get who you are logged in as
var meta = document.getElementsByClassName('navItem tinyman')[0];
if (typeof meta !== "undefined") {
var usernameMatched = /www.facebook.com\/(.*?)ref=tn_tnmn/i.exec(meta.innerHTML);
usernameMatched = usernameMatched[1].replace(/&/, '');
usernameMatched = usernameMatched.replace(/\?/, '');
usernameMatched = usernameMatched.replace(/profile\.phpid=/, '');
my_username = usernameMatched; // Update global.
}
}
function getClassName(obj) {
if (typeof obj != "object" || obj === null) return false;
return /(\w+)\(/.exec(obj.constructor.toString())[1];
}
function hasClass(element, cls) {
var r = new RegExp('\\b' + cls + '\\b');
return r.test(element.className);
}
function DocChanged(e) {
if (document.URL.match(/groups/)) {
//Check for adding encrypt button for comments
if (e.target.nodeType != 3) {
decryptTextOfChildNodes(e.target);
decryptTextOfChildNodes2(e.target);
if (!hasClass(e.target, "crypto")) {
addEncryptCommentButton(e.target);
} else {
return;
}
}
tryAddEncryptButton();
}
//Check for adding keys-table
if (document.URL.match('settings')) {
if (!document.getElementById('cs255-keys-table') && !hasClass(e.target, "crypto")) {
AddEncryptionTab();
UpdateKeysTable();
}
}
}
//Decryption of posts
function decryptTextOfChildNodes(e) {
var msgs = e.getElementsByClassName('messageBody');
if (msgs.length > 0) {
var msgs_array = new Array();
for (var i = 0; i < msgs.length; ++i) {
msgs_array[i] = msgs[i];
}
for (var i = 0; i < msgs_array.length; ++i) {
DecryptMsg(msgs_array[i]);
}
}
}
//Decryption of comments
function decryptTextOfChildNodes2(e) {
var msgs = e.getElementsByClassName('UFICommentBody');
if (msgs.length > 0) {
var msgs_array = new Array();
for (var i = 0; i < msgs.length; ++i) {
msgs_array[i] = msgs[i];
}
for (var i = 0; i < msgs_array.length; ++i) {
DecryptMsg(msgs_array[i]);
}
}
}
function RegisterChangeEvents() {
// Facebook loads posts dynamically using AJAX, so we monitor changes
// to the HTML to discover new posts or comments.
var doc = document.addEventListener("DOMNodeInserted", DocChanged, false);
}
function AddEncryptionTab() {
// On the Account Settings page, show the key setups
if (document.URL.match('settings')) {
var div = document.getElementById('contentArea');
if (div) {
var h2 = document.createElement('h2');
h2.setAttribute("class", "crypto");
h2.innerHTML = "CS255 Keys";
div.appendChild(h2);
var table = document.createElement('table');
table.id = 'cs255-keys-table';
table.style.borderCollapse = "collapse";
table.setAttribute("class", "crypto");
table.setAttribute('cellpadding', 3);
table.setAttribute('cellspacing', 1);
table.setAttribute('border', 1);
table.setAttribute('width', "80%");
div.appendChild(table);
var clearSessionStorage = document.createElement('button');
clearSessionStorage.innerHTML = "Clear sessionStorage";
clearSessionStorage.addEventListener("click", function() {
sessionStorage.clear();
console.log("Cleared sessionStorage.");
});
div.appendChild(document.createElement('br'));
div.appendChild(clearSessionStorage);
var clearLocalStorage = document.createElement('button');
clearLocalStorage.innerHTML = "Clear localStorage";
clearLocalStorage.addEventListener("click", function() {
localStorage.clear();
cs255.localStorage.clear();
console.log("Cleared localStorage, including the extension cache.");
});
div.appendChild(document.createElement('br'));
div.appendChild(clearLocalStorage);
}
}
}
//Encrypt button is added in the upper left corner
function tryAddEncryptButton(update) {
// Check if it already exists.
if (document.getElementById('encrypt-button')) {
return;
}
var encryptWrapper = document.createElement("span");
encryptWrapper.style.float = "right";
var encryptLabel = document.createElement("label");
encryptLabel.setAttribute("class", "submitBtn uiButton uiButtonConfirm");
var encryptButton = document.createElement("input");
encryptButton.setAttribute("value", "Encrypt");
encryptButton.setAttribute("type", "button");
encryptButton.setAttribute("id", "encrypt-button");
encryptButton.setAttribute("class", "encrypt-button");
encryptButton.addEventListener("click", DoEncrypt, false);
encryptLabel.appendChild(encryptButton);
encryptWrapper.appendChild(encryptLabel);
var liParent;
try {
liParent = document.getElementsByName("xhpc_message")[0].parentNode;
} catch(e) {
return;
}
liParent.appendChild(encryptWrapper);
decryptTextOfChildNodes(document);
decryptTextOfChildNodes2(document);
}
function addEncryptCommentButton(e) {
var commentAreas = e.getElementsByClassName('textInput UFIAddCommentInput');
for (var j = 0; j < commentAreas.length; j++) {
if (commentAreas[j].parentNode.parentNode.parentNode.parentNode.getElementsByClassName("encrypt-comment-button").length > 0) {
continue;
}
var encryptWrapper = document.createElement("span");
encryptWrapper.setAttribute("class", "");
encryptWrapper.style.cssFloat = "right";
encryptWrapper.style.cssPadding = "2px";
var encryptLabel = document.createElement("label");
encryptLabel.setAttribute("class", "submitBtn uiButton uiButtonConfirm crypto");
var encryptButton = document.createElement("input");
encryptButton.setAttribute("value", "Encrypt");
encryptButton.setAttribute("type", "button");
encryptButton.setAttribute("class", "encrypt-comment-button crypto");
encryptButton.addEventListener("click", DoEncrypt, false);
encryptLabel.appendChild(encryptButton);
encryptWrapper.appendChild(encryptLabel);
commentAreas[j].parentNode.parentNode.parentNode.parentNode.appendChild(encryptWrapper);
}
}
function AddElements() {
if (document.URL.match(/groups/)) {
tryAddEncryptButton();
addEncryptCommentButton(document);
}
AddEncryptionTab()
}
function GenerateKeyWrapper() {
var group = document.getElementById('gen-key-group').value;
if (group.length < 1) {
alert("You need to set a group");
return;
}
GenerateKey(group);
UpdateKeysTable();
}
function UpdateKeysTable() {
var table = document.getElementById('cs255-keys-table');
if (!table) return;
table.innerHTML = '';
// ugly due to events + GreaseMonkey.
// header
var row = document.createElement('tr');
var th = document.createElement('th');
th.innerHTML = "Group";
row.appendChild(th);
th = document.createElement('th');
th.innerHTML = "Key";
row.appendChild(th);
th = document.createElement('th');
th.innerHTML = " ";
row.appendChild(th);
table.appendChild(row);
// keys
for (var group in keys) {
var row = document.createElement('tr');
row.setAttribute("data-group", group);
var td = document.createElement('td');
td.innerHTML = group;
row.appendChild(td);
td = document.createElement('td');
td.innerHTML = keys[group];
row.appendChild(td);
td = document.createElement('td');
var button = document.createElement('input');
button.type = 'button';
button.value = 'Delete';
button.addEventListener("click", function(event) {
DeleteKey(event.target.parentNode.parentNode);
}, false);
td.appendChild(button);
row.appendChild(td);
table.appendChild(row);
}
// add friend line
row = document.createElement('tr');
var td = document.createElement('td');
td.innerHTML = '<input id="new-key-group" type="text" size="8">';
row.appendChild(td);
td = document.createElement('td');
td.innerHTML = '<input id="new-key-key" type="text" size="24">';
row.appendChild(td);
td = document.createElement('td');
button = document.createElement('input');
button.type = 'button';
button.value = 'Add Key';
button.addEventListener("click", AddKey, false);
td.appendChild(button);
row.appendChild(td);
table.appendChild(row);
// generate line
row = document.createElement('tr');
td = document.createElement('td');
td.innerHTML = '<input id="gen-key-group" type="text" size="8">';
row.appendChild(td);
table.appendChild(row);
td = document.createElement('td');
td.colSpan = "2";
button = document.createElement('input');
button.type = 'button';
button.value = 'Generate New Key';
button.addEventListener("click", GenerateKeyWrapper, false);
td.appendChild(button);
row.appendChild(td);
}
function AddKey() {
var g = document.getElementById('new-key-group').value;
if (g.length < 1) {
alert("You need to set a group");
return;
}
var k = document.getElementById('new-key-key').value;
keys[g] = k;
SaveKeys();
UpdateKeysTable();
}
function DeleteKey(e) {
var group = e.getAttribute("data-group");
delete keys[group];
SaveKeys();
UpdateKeysTable();
}
function DoEncrypt(e) {
// triggered by the encrypt button
// Contents of post or comment are saved to dummy node. So updation of contens of dummy node is also required after encryption
if (e.target.className == "encrypt-button") {
var textHolder = document.getElementsByClassName("uiTextareaAutogrow input mentionsTextarea textInput")[0];
var dummy = document.getElementsByName("xhpc_message")[0];
} else {
console.log(e.target);
var dummy = e.target.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("mentionsHidden")[0];
var textHolder = e.target.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("textInput mentionsTextarea")[0];
}
//Get the plain text
//var vntext=textHolder.value;
var vntext = dummy.value;
//Ecrypt
var vn2text = Encrypt(vntext, CurrentGroup());
//Replace with encrypted text
textHolder.value = vn2text;
dummy.value = vn2text;
textHolder.select();
}
// Currently results in a TypeError if we're not on a group page.
function CurrentGroup() {
// Try a few DOM elements that might exist, and would contain the group name.
var domElement = document.getElementById('groupsJumpTitle') || document.getElementById('groupsSkyNavTitleTab');
var groupName = domElement.innerText;
return groupName;
}
function GetMsgText(msg) {
return msg.innerHTML;
}
function getTextFromChildren(parent, skipClass, results) {
var children = parent.childNodes,
item;
var re = new RegExp("\\b" + skipClass + "\\b");
for (var i = 0, len = children.length; i < len; i++) {
item = children[i];
// if text node, collect it's text
if (item.nodeType == 3) {
results.push(item.nodeValue);
} else if (!item.className || !item.className.match(re)) {
// if it has a className and it doesn't match
// what we're skipping, then recurse on it
getTextFromChildren(item, skipClass, results);
}
}
}
function GetMsgTextForDecryption(msg) {
try {
var visibleDiv = msg.getElementsByClassName("text_exposed_root");
if (visibleDiv.length) {
var visibleDiv = document.getElementsByClassName("text_exposed_root");
var text = [];
getTextFromChildren(visibleDiv[0], "text_exposed_hide", text);
var mg = text.join("");
return mg;
} else {
var innerText = msg.innerText;
// Get rid of the trailing newline, if there is one.
if (innerText[innerText.length-1] === '\n') {
innerText = innerText.slice(0, innerText.length-1);
}
return innerText;
}
} catch(err) {
return msg.innerText;
}
}
function wbr(str, num) {
//return str.replace(RegExp("(\\w{" + num + "})(\\w)", "g"), function(all,text,char){
// return text + "<wbr>" + char;
//});
return str.replace(RegExp("(.{" + num + "})(.)", "g"), function(all, text, char) {
return text + "<wbr>" + char;
});
}
function SetMsgText(msg, new_text) {
//msg.innerHTML = wbr(new_text, 50);
msg.innerHTML = new_text;
}
// Rudimentary attack against HTML/JAvascript injection. From mustache.js. https://github.com/janl/mustache.js/blob/master/mustache.js#L53
function escapeHtml(string) {
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
function DecryptMsg(msg) {
// we mark the box with the class "decrypted" to prevent attempting to decrypt it multiple times.
if (!/decrypted/.test(msg.className)) {
var txt = GetMsgTextForDecryption(msg);
var displayHTML;
try {
var group = CurrentGroup();
var decryptedMsg = Decrypt(txt, group);
decryptedMsg = escapeHtml(decryptedMsg);
displayHTML = '<font color="#00AA00">Decrypted message: ' + decryptedMsg + '</font><br><hr>' + txt;
}
catch (e) {
displayHTML = '<font color="#FF88">Could not decrypt (' + e + ').</font><br><hr>' + txt;
}
SetMsgText(msg, displayHTML);
msg.className += " decrypted";
}
}
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
//
// Below here is from other libraries. Here be dragons.
//
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
/** @fileOverview Javascript cryptography implementation.
*
* Crush to remove comments, shorten variable names and
* generally reduce transmission size.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
"use strict"; /*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */
/*global document, window, escape, unescape */
/** @namespace The Stanford Javascript Crypto Library, top-level namespace. */
var sjcl = { /** @namespace Symmetric ciphers. */
cipher: {},
/** @namespace Hash functions. Right now only SHA256 is implemented. */
hash: {},
/** @namespace Block cipher modes of operation. */
mode: {},
/** @namespace Miscellaneous. HMAC and PBKDF2. */
misc: {},
/**
* @namespace Bit array encoders and decoders.
*
* @description
* The members of this namespace are functions which translate between
* SJCL's bitArrays and other objects (usually strings). Because it
* isn't always clear which direction is encoding and which is decoding,
* the method names are "fromBits" and "toBits".
*/
codec: {},
/** @namespace Exceptions. */
exception: { /** @class Ciphertext is corrupt. */
corrupt: function(message) {
this.toString = function() {
return "CORRUPT: " + this.message;
};
this.message = message;
},
/** @class Invalid parameter. */
invalid: function(message) {
this.toString = function() {
return "INVALID: " + this.message;
};
this.message = message;
},
/** @class Bug or missing feature in SJCL. */
bug: function(message) {
this.toString = function() {
return "BUG: " + this.message;
};
this.message = message;
},
// Added by mbarrien to fix an SJCL bug.
/** @class Not ready to encrypt. */
notready: function(message) {
this.toString = function() {
return "NOTREADY: " + this.message;
};
this.message = message;
}
}
};
/** @fileOverview Low-level AES implementation.
*
* This file contains a low-level implementation of AES, optimized for
* size and for efficiency on several browsers. It is based on
* OpenSSL's aes_core.c, a public-domain implementation by Vincent
* Rijmen, Antoon Bosselaers and Paulo Barreto.
*
* An older version of this implementation is available in the public
* domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,
* Stanford University 2008-2010 and BSD-licensed for liability
* reasons.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
/**
* Schedule out an AES key for both encryption and decryption. This
* is a low-level class. Use a cipher mode to do bulk encryption.
*
* @constructor
* @param {Array} key The key as an array of 4, 6 or 8 words.
*
* @class Advanced Encryption Standard (low-level interface)
*/
sjcl.cipher.aes = function(key) {
if (!this._tables[0][0][0]) {
this._precompute();
}
var i, j, tmp, encKey, decKey, sbox = this._tables[0][4],
decTable = this._tables[1],
keyLen = key.length,
rcon = 1;
if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
throw new sjcl.exception.invalid("invalid aes key size");
}
this._key = [encKey = key.slice(0), decKey = []];
// schedule encryption keys
for (i = keyLen; i < 4 * keyLen + 28; i++) {
tmp = encKey[i - 1];
// apply sbox
if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) {
tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
// shift rows and add rcon
if (i % keyLen === 0) {
tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
rcon = rcon << 1 ^ (rcon >> 7) * 283;
}
}
encKey[i] = encKey[i - keyLen] ^ tmp;
}
// schedule decryption keys
for (j = 0; i; j++, i--) {
tmp = encKey[j & 3 ? i : i - 4];
if (i <= 4 || j < 4) {
decKey[j] = tmp;
} else {
decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
}
}
};
sjcl.cipher.aes.prototype = {
// public
/* Something like this might appear here eventually
name: "AES",
blockSize: 4,
keySizes: [4,6,8],
*/
/**
* Encrypt an array of 4 big-endian words.
* @param {Array} data The plaintext.
* @return {Array} The ciphertext.
*/
encrypt: function(data) {
return this._crypt(data, 0);
},
/**