-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcryptopost.js
2048 lines (1679 loc) · 75.5 KB
/
cryptopost.js
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
/*
Base code from Stanford CS255 Cryptography course, with all relevant rights. http://crypto.stanford.edu/~dabo/cs255/
Stanford Javascript Crypto Library for AES implementation http://crypto.stanford.edu/sjcl/
Modified by me for a more user friendly experience as well, as well as filling in the missing parts to give it full functionality.
@author Loh Wan Jing
*/
// 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
var keyGenCipher;
var keyGenCounter;
// 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) {
var key64 = keys[group];
var key = sjcl.codec.base64.toBits(key64);
var iv = GetRandomValues(4);
var iv64 = sjcl.codec.base64.fromBits(iv);
var returnData = sjcl.json.encrypt(key, plainText);
return returnData;
}
// 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) {
try {
var key64 = keys[group];
var key = sjcl.codec.base64.toBits(key64);
var data = sjcl.json.decrypt(key, cipherText);
return data;
}
catch(e) {
throw "not encrypted";
}
}
// Generate a new key for the given group. Keys are in base64
//
// @param {String} group Group name.
function GenerateKey(group) {
if (keyGenCipher == null) {
var keyGenKey = GetRandomValues(8);
keyGenCipher = new sjcl.cipher.aes(keyGenKey);
keyGenCounter = GetRandomValues(4);
}
//first 128 bits
//increment counter by 1, TODO should check for carry to next array,
keyGenCounter[3] = keyGenCounter[3] +1;
var keyArray1 = keyGenCipher.encrypt(keyGenCounter);
//2nd 128 bits
//increment counter by 1, TODO should check for carry to next array,
keyGenCounter[3] = keyGenCounter[3] +1;
var keyArray2 = keyGenCipher.encrypt(keyGenCounter);
//concat to 256 bits
var keyArray = sjcl.bitArray.concat(keyArray1, keyArray2);
//convert to base64 for easier reading and copying
var base64str = sjcl.codec.base64.fromBits(keyArray);
var key = base64str;
keys[group] = key;
SaveKeys();
}
// Take the current group keys, and save them in encrypted form to disk.
function SaveKeys() {
if (cs255.localStorage.getItem('facebook-active-' + my_username) == 'true'){
var key_str = JSON.stringify(keys);
var en_keyStr = sjcl.json.encrypt(getPasswordKey(), key_str)
cs255.localStorage.setItem('facebook-keys-' + my_username, en_keyStr);
}
}
//generate 64 bit salt for PKDF
function generatePasswordSalt(){
var salt = GetRandomValues(2);
var saltStr = salt = sjcl.codec.base64.fromBits(salt);
cs255.localStorage.setItem('facebook-dbSalt-' + my_username, saltStr);
}
//get 64 bit salt for PKDF
function getPasswordSalt(){
var saltStr = cs255.localStorage.getItem('facebook-dbSalt-' + my_username);
var salt;
if (!saltStr){
generatePasswordSalt();
saltStr = cs255.localStorage.getItem('facebook-dbSalt-' + my_username); // get just created salt string
}
salt = sjcl.codec.base64.toBits(saltStr);
return salt;
}
// Load the group keys from disk.
function LoadKeys() {
keys = {}; // Reset the keys.
if (cs255.localStorage.getItem('facebook-active-' + my_username) == 'true'){
var saved = cs255.localStorage.getItem('facebook-keys-' + my_username);
if (saved) {
try {
var de_saved = sjcl.json.decrypt(getPasswordKey(), saved);
keys = JSON.parse(de_saved);
}
catch (e) {
sessionStorage.clear();
customAlertRefreshPage("Cannot Decrypt Keys. Please re-enter your password and try again");
//keys = JSON.parse(saved);
//cs255.localStorage.setItem('facebook-active-' + my_username, false);
}
}
}
}
// local storage for extension. This allows it to work (somewhat) between http://www.facebook.com and https://www.facebook.com
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 (var key in onDisk) {
localStorage.setItem(key, onDisk[key]);
}
});
}
// 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);
}
}
//From Stanford CS255 base code - get facebook user name
function SetupUsernames() {
// get who you are logged in as
//var meta = document.getElementsByClassName('navItem tinyman')[0];
var meta = document.getElementsByClassName('fbxWelcomeBoxName')[0];
// If we can't get a username, halt execution.
assert (typeof meta !== "undefined", "CS255 script failed. No username detected. (This is usually harmless.)");
//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.
alert(meta);
alert(meta.innerText);
var usernameMatched = meta.innerText;
my_username = usernameMatched; // Update global.
}
//initialise most needed variables such as passwords, and prompts for first time users
function Initialise() {
// initialise active variable if not present, which defines if extension executes
if (!cs255.localStorage.getItem('facebook-active-' + my_username)){
cs255.localStorage.setItem('facebook-active-' + my_username, true);
}
var initState = cs255.localStorage.getItem('facebook-initState-' + my_username);
if (!initState || initState == 'false' || initState == 'null') {
// user has never used facebook extension before
//alert(my_username);
//alert(initState);
customAlert("Thank you for installing FacebookCrypto.\nPlease proceed to your facebook settings page to set it up.\nIf you have already setup your account, try refreshing the page.");
cs255.localStorage.setItem('facebook-active-' + my_username, false); //disable extension until its set up properly
//cs255.localStorage.setItem('facebook-promptState-' + my_username, 'true'); // so we won't prompt again
GeneralInit();
}
else if (initState == 'true'){ // initialised and working
//get and store password
getPasswordMain();
}
}
function GeneralInit(){
LoadKeys();
AddElements();
UpdateKeysTable();
UpdatePasswordTable();
RegisterChangeEvents();
console.log("CS255 script finished loading.");
}
//main prompt for password & initialisation
function getPasswordMain(reload){
//check if password correctly entered
var diskKey_str = sessionStorage.getItem('facebook-dbKey-' + my_username);
var diskKey;
if (diskKey_str){
// key already present
//initialise everything else
GeneralInit();
}
else { // key not present
if (cs255.localStorage.getItem('facebook-active-' + my_username) == 'true'){
if (reload){
customPromptGenerator("Please enter your encryption password.\nPress cancel to disable FacebookCrypto", PasswordOkWithRefresh, PasswordCancel, 'password' )
}
else {
customPromptGenerator("Please enter your encryption password.\nPress cancel to disable FacebookCrypto", PasswordOk, PasswordCancel, 'password' )
}
}
else {
//Do inactive initialisation (generate table in settings mostly)
GeneralInit();
}
}
}
function PasswordOk(){
//get password entered
var input = document.getElementById('promptpass');
//alert(input);
if (input){
var password = input.value;
// alert(password);
//regenerate derived key
var params ={};
params.salt = getPasswordSalt();
//alert(params.salt);
var diskKeyData = sjcl.misc.cachedPbkdf2(password, params);
var diskKey = diskKeyData.key;
//check if key is correct
var en_correctStr = cs255.localStorage.getItem('facebook-correct-' + my_username);
// alert(en_correctStr);
try {
var de_correctStr = sjcl.json.decrypt(diskKey, en_correctStr);
//alert(de_correctStr);
//alert(de_correctStr == "Correctness Check");
if (de_correctStr == "Correctness Check") {
var diskKey_str = sjcl.codec.base64.fromBits(diskKey);
sessionStorage.setItem('facebook-dbKey-' + my_username, diskKey_str);
//AlertDispose();
GeneralInit();
customAlert("FacebookCrypto is now enabled");
//alert('reached');
//HideCustomAlert();
return;
}
else {
// shouldn't get here, mac correct but plaintext wrong
alert("BUG! MAC Correct but test encryption wrong");
//cs255.localStorage.setItem('facebook-active-' + my_username, false); //disable extension until its set up properly
}
}
catch (e){
//alert(e);
// password is wrong
var customMsgBody = document.getElementById('customAlertMsgBody');
//edit msg
customMsgBody.innerText = 'Wrong Password Entered. Please try again';
}
}
else {
var customMsgBody = document.getElementById('customAlertMsgBody');
//edit msg
customMsgBody.innerText = 'Wrong Password Entered. Please try again';
}
}
function PasswordOkWithRefresh(){
//get password entered
var input = document.getElementById('promptpass');
//alert(input);
if (input){
var password = input.value;
// alert(password);
//regenerate derived key
var params ={};
params.salt = getPasswordSalt();
//alert(params.salt);
var diskKeyData = sjcl.misc.cachedPbkdf2(password, params);
var diskKey = diskKeyData.key;
//check if key is correct
var en_correctStr = cs255.localStorage.getItem('facebook-correct-' + my_username);
// alert(en_correctStr);
try {
var de_correctStr = sjcl.json.decrypt(diskKey, en_correctStr);
//alert(de_correctStr);
//alert(de_correctStr == "Correctness Check");
if (de_correctStr == "Correctness Check") {
var diskKey_str = sjcl.codec.base64.fromBits(diskKey);
sessionStorage.setItem('facebook-dbKey-' + my_username, diskKey_str);
//AlertDispose();
GeneralInit();
customAlertRefreshPage("FacebookCrypto is now enabled");
//alert('reached');
//HideCustomAlert();
return;
}
else {
// shouldn't get here, mac correct but plaintext wrong
alert("BUG! MAC Correct but test encryption wrong");
//cs255.localStorage.setItem('facebook-active-' + my_username, false); //disable extension until its set up properly
}
}
catch (e){
//alert(e);
// password is wrong
var customMsgBody = document.getElementById('customAlertMsgBody');
//edit msg
customMsgBody.innerText = 'Wrong Password Entered. Please try again';
}
}
else {
var customMsgBody = document.getElementById('customAlertMsgBody');
//edit msg
customMsgBody.innerText = 'Wrong Password Entered. Please try again';
}
}
function PasswordCancel(){
cs255.localStorage.setItem('facebook-active-' + my_username, false);
GeneralInit();
HideCustomAlert();
}
//checks if password has been entered previously and if the password is correct
function getPassword(){
//check if password correctly entered
var diskKey_str = sessionStorage.getItem('facebook-dbKey-' + my_username);
var diskKey;
if (diskKey_str){
// key already present
//do nothing
}
else {
alert('Bug! Somehow initialised without a password');
}
}
//use PKDF to get the derived key from the password
function getPasswordKey(){
getPassword();
var diskKey_str = sessionStorage.getItem('facebook-dbKey-' + my_username);
// alert("Should Prompt for password" + diskKey_str);
var diskKey;
if (diskKey_str){
// key already present // should be always true
//alert("Disk Key Generated: " + diskKey);
diskKey = sjcl.codec.base64.toBits(diskKey_str);
}
else {
alert("BUG! "); // should not ever happen
}
return diskKey;
}
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/)){
if (!document.getElementById('active-button')) {
AddActivateButton();
}
}
if (document.URL.match(/groups/) && cs255.localStorage.getItem('facebook-active-' + my_username) == 'true'){
if (!document.getElementById('keygen-wrapper')) {
AddKeyWrapper();
}
}
//AddKeyWrapper();
//}
if (document.URL.match(/groups/) && cs255.localStorage.getItem('facebook-active-' + my_username) == 'true') {
//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();
UpdatePasswordTable();
}
}
}
//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('UFICommentContent');
if (msgs.length > 0) {
var msgs_array = new Array();
var childrenArray = new Array();
for (var i = 0; i < msgs.length; ++i) {
var children = msgs[i].childNodes;
for(var j=0; j < children.length; j++) {
if (children[j].nodeType == 1)
childrenArray.push(children[j]);
}
}
for (var i = 0; i < childrenArray.length; ++i) {
// only want greatgrandchildren
var grandchildren = childrenArray[i].childNodes;
for(var j=0; j < grandchildren.length; j++) {
if (grandchildren[j].nodeType == 1)
msgs_array.push(grandchildren[j]);
}
}
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 = "Facebook Crypto - Key Management";
div.appendChild(h2);
var table = document.createElement('table');
table.id = 'cs255-Password-table';
table.style.borderCollapse = "collapse";
table.setAttribute("class", "uiInfoTable crypto");
table.setAttribute('cellpadding', 3);
table.setAttribute('cellspacing', 1);
table.setAttribute('border', 1);
table.setAttribute('width', "80%");
div.appendChild(table);
//h2 = document.createElement('h2');
//h2.setAttribute("class", "crypto");
//h2.innerHTML = "Group Keys";
//div.appendChild(h2);
table = document.createElement('table');
table.id = 'cs255-keys-table';
table.style.borderCollapse = "collapse";
table.setAttribute("class", "uiInfoTable crypto");
table.setAttribute('cellpadding', 3);
table.setAttribute('cellspacing', 1);
table.setAttribute('border', 1);
table.setAttribute('width', "80%");
div.appendChild(table);
}
}
}
//Table to allow the user to set the password for the extension
function UpdatePasswordTable() {
var table = document.getElementById('cs255-Password-table');
if (!table) return;
table.innerHTML = '';
// ugly due to events + GreaseMonkey.
// header
var row = document.createElement('tr');
var th = document.createElement('th');
if (cs255.localStorage.getItem('facebook-active-' + my_username) == 'true'){
th.innerHTML = "Facebook Crypto is enabled";
row.appendChild(th);
th = document.createElement('th');
th.innerHTML = " ";
row.appendChild(th);
th = document.createElement('th');
th.innerHTML = " ";
row.appendChild(th);
table.appendChild(row);
// add generation line
row = document.createElement('tr');
var td = document.createElement('td');
td.innerHTML = 'Facebook Crypto works by encrypting your Facebook Groups messages.\n'
+ 'To start using it, please add in the Group name and click on "Generate Key" to generate a shared cryptographic key for use in the group.\n'
+ 'If you have obtained a key from a friend, fill in the details and use "Add Key" to update the database.' ;
row.appendChild(td);
td = document.createElement('td');
row.appendChild(td);
var button = document.createElement('input');
button.type = 'button';
button.value = 'Disable';
button.addEventListener("click", Deactivate, false);
td.appendChild(button);
row.appendChild(td);
td = document.createElement('td');
row.appendChild(td);
button = document.createElement('input');
button.type = 'button';
button.value = 'Reset Account Data';
button.addEventListener("click", ClearUserData, false);
td.appendChild(button);
row.appendChild(td);
table.appendChild(row);
}
else {
th.innerHTML = "Enter your Facebook Crypto Password";
row.appendChild(th);
th = document.createElement('th');
th.innerHTML = " ";
row.appendChild(th);
th = document.createElement('th');
th.innerHTML = " ";
row.appendChild(th);
table.appendChild(row);
// add generation line
row = document.createElement('tr');
var td = document.createElement('td');
td.innerHTML = '<input id="new-pass" type="password" size="30">';
row.appendChild(td);
td = document.createElement('td');
var button = document.createElement('input');
button.type = 'button';
if (cs255.localStorage.getItem('facebook-initState-' + my_username) == null || cs255.localStorage.getItem('facebook-initState-' + my_username) == 'false' ){
button.value = 'Set Up Main Password';
}
else {
button.value = 'Enable';
}
button.addEventListener("click", AddDBKey, false);
td.appendChild(button);
row.appendChild(td);
td = document.createElement('td');
row.appendChild(td);
button = document.createElement('input');
button.type = 'button';
button.value = 'Reset Account Data';
button.addEventListener("click", ClearUserData, false);
td.appendChild(button);
row.appendChild(td);
table.appendChild(row);
}
}
//deletes all user data for the currently logged in user
function ClearUserData(){
customConfirmGenerator("This will delete all stored data for this user.\nDo you wish to proceed?", ClearUserDataConfirm, HideCustomAlert);
}
function ClearUserDataConfirm(){
cs255.localStorage.setItem('facebook-initState-' + my_username, false);
cs255.localStorage.setItem('facebook-active-' + my_username, false);
keys = {};
cs255.localStorage.setItem('facebook-correct-' + my_username, null);
cs255.localStorage.setItem('facebook-keys-' + my_username, null);
sessionStorage.clear();
location.reload(true);
}
//deactivates the extension
function Deactivate(){
cs255.localStorage.setItem('facebook-active-' + my_username, false);
sessionStorage.clear();
LoadKeys(); //clear keys
UpdateKeysTable();
UpdatePasswordTable();
}
//sets keys to empty set
function resetKeys(){
keys = {};
SaveKeys();
LoadKeys();
}
//sets up main password
function AddDBKey() {
var g = document.getElementById('new-pass').value;
if (g.length < 1) {
customAlert("Please enter a password");
return;
}
var params ={};
params.salt = getPasswordSalt();
var diskKeyData = sjcl.misc.cachedPbkdf2(g, params);
var diskKey = diskKeyData.key;
var diskKey_str = sjcl.codec.base64.fromBits(diskKey);
//var key_str = JSON.stringify(keys);
//var en_keyStr =
var en_keyStr = sjcl.json.encrypt(diskKey, "Correctness Check")
if (cs255.localStorage.getItem('facebook-initState-' + my_username) == null || cs255.localStorage.getItem('facebook-initState-' + my_username) == 'false' ){
// totally clean state
cs255.localStorage.setItem('facebook-correct-' + my_username, en_keyStr);
cs255.localStorage.setItem('facebook-initState-' + my_username, 'true'); // properly initialised
cs255.localStorage.setItem('facebook-active-' + my_username, true); //disable extension until its set up properly
sessionStorage.setItem('facebook-dbKey-' + my_username, diskKey_str); // save password to session to avoid reprompt;
resetKeys();
UpdateKeysTable();
UpdatePasswordTable();
}
else {
//check if password is correctly entered
var en_correctStr = cs255.localStorage.getItem('facebook-correct-' + my_username);
try {
var de_correctStr = sjcl.json.decrypt(diskKey, en_correctStr);
if (de_correctStr == "Correctness Check") {
//alert("Facebook Crypto Activated");
diskKey_str = sjcl.codec.base64.fromBits(diskKey);
sessionStorage.setItem('facebook-dbKey-' + my_username, diskKey_str);
cs255.localStorage.setItem('facebook-active-' + my_username, true);
LoadKeys();
UpdateKeysTable();
UpdatePasswordTable();
return;
}
else {
// shouldn't get here, mac correct but plaintext wrong
alert("BUG! MAC Correct but test encryption wrong");
return;
//cs255.localStorage.setItem('facebook-active-' + my_username, false); //disable extension until its set up properly
}
}
catch (e){
// password is wrong
customAlert("Wrong Password Entered");
return;
}
}
}
//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() {
AddEncryptionTab();
if (document.URL.match(/groups/) && cs255.localStorage.getItem('facebook-active-' + my_username) == 'true') {
tryAddEncryptButton();
addEncryptCommentButton(document);
}
if (document.URL.match(/groups/)){
AddActivateButton();
//AddKeyWrapper();
}
if (document.URL.match(/groups/)&& cs255.localStorage.getItem('facebook-active-' + my_username) == 'true'){
//AddActivateButton();
AddKeyWrapper();
}
}
function AddActivateButton(){
// Check if it already exists.
if (document.getElementById('active-button')) {
return;
}
var activeWrapper = document.createElement("span");
activeWrapper.style.float = "right";
var activeLabel = document.createElement("label");
activeLabel.setAttribute("class", "uiButton");
var activeButton = document.createElement("input");
if (!cs255.localStorage.getItem('facebook-active-' + my_username) || cs255.localStorage.getItem('facebook-active-' + my_username) == 'false'){
activeButton.setAttribute("value", "Enable FB Crypto");
}
else {
activeButton.setAttribute("value", "Disable FB Crypto");
}
activeButton.setAttribute("type", "button");
activeButton.setAttribute("id", "active-button");
activeButton.setAttribute("class", "active-button");
activeButton.addEventListener("click", DoActive, false);
activeLabel.appendChild(activeButton);
activeWrapper.appendChild(activeLabel);
var listItem = document.createElement("li");
listItem.appendChild(activeWrapper);
var liParent;
var ulParent;
try {
liParent = document.getElementById("u_0_6");
ulParent = liParent.getElementsByTagName("ul")[0];
ulParent.appendChild(listItem);
} catch(e) {
//alert(e);
return;
}
}
function AddKeyWrapper(){
// Check if it already exists.
if (document.getElementById('keygen-wrapper')) {
return;
}
var group = CurrentGroup();
//look for menu
var menudiv = document.getElementById('pagelet_group_actions')
var menu = getElementsByClassName(menudiv,"uiMenuInner")[0];
//add separator
var separator = document.createElement("li");
separator.setAttribute("id", "keygen-wrapper");
separator.setAttribute("class", "uiMenuSeparator");
menu.appendChild(separator);
var viewText = "View CryptoKey";
var genText = "Generate New CryptoKey";
var addText = "Add CryptoKey";
if (group in keys){
addText = "Edit Existing CryptoKey";
}
//add keyview
var keyViewer = generateCustomListElement(viewText, DoKeyView);
//add keygen element
var keygen = generateCustomListElement(genText, DoKeyGen);
//keygen.setAttribute("class", "uiMenuItem");
//keygen.setAttribute("id", "keygen-wrapper");
//keygen.setAttribute("data-label", "Generate New Key");
//keygen.appendChild(generateCustomAnchor("Generate New CryptoKey", DoKeyGen));
var keyAdder = generateCustomListElement(addText, DoKeyChange);
menu.appendChild(separator);
menu.appendChild(keyViewer);
menu.appendChild(keygen);
menu.appendChild(keyAdder);
}
function generateAnchor(){
var anchor = document.createElement("a");
anchor.setAttribute("class", "itemAnchor");
anchor.setAttribute("role", "menuItem");
anchor.setAttribute("tabIndex", -1);
var span = document.createElement("span");
span.setAttribute("class", "itemLabel fsm");
span.innerHTML = "Generate Group CryptoKey";
anchor.appendChild(span);
span.addEventListener("click", DoKeyGen, false);
return anchor;
}
function generateCustomAnchor(label, listener){
var anchor = document.createElement("a");
anchor.setAttribute("class", "itemAnchor");
anchor.setAttribute("role", "menuItem");
anchor.setAttribute("tabIndex", -1);
var span = document.createElement("span");