/
code.js
92 lines (77 loc) · 2.69 KB
/
code.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
function dec2hex(s) {
return (s < 15.5 ? '0' : '') + Math.round(s).toString(16);
}
function hex2dec(s) {
return parseInt(s, 16);
}
function base32tohex(base32) {
var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
var bits = "";
var hex = "";
for (var i = 0; i < base32.length; i++) {
var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
bits += leftpad(val.toString(2), 5, '0');
}
// leftpad bits with 0 until length is a multiple of 4
while (bits.length % 4 != 0) {
bits = "0" + bits;
}
for (var i = bits.length - 4; i >= 0; i = i - 4) {
var chunk = bits.substr(i, 4);
hex = parseInt(chunk, 2).toString(16) + hex;
}
return hex;
}
function leftpad(str, len, pad) {
if (len + 1 >= str.length) {
str = Array(len + 1 - str.length).join(pad) + str;
}
return str;
}
function updateOtp(secret) {
var key = base32tohex(secret);
var epoch = Math.round(new Date().getTime() / 1000.0);
var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0');
var hmacObj = new jsSHA(time, "HEX");
var hmac = hmacObj.getHMAC(key, "HEX", "SHA-1", "HEX");
if (hmac != 'KEY MUST BE IN BYTE INCREMENTS') {
var offset = hex2dec(hmac.substring(hmac.length - 1));
// Debug
//var part1 = hmac.substr(0, offset * 2);
//var part2 = hmac.substr(offset * 2, 8);
//var part3 = hmac.substr(offset * 2 + 8, hmac.length - offset);
}
var otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec('7fffffff')) + '';
return otp = (otp).substr(otp.length - 6, 6);
}
function timer() {
var epoch = Math.round(new Date().getTime() / 1000.0);
var countDown = 30 - (epoch % 30);
if (epoch % 30 == 0) {
$('#otp').text(updateOtp(localStorage.keySecret));
}
$('#updatingIn').text(countDown);
}
$(function () {
// Check if local storage is supported
if (typeof (Storage) !== "undefined") {
// Set the overview page
$('#otp').text(updateOtp(localStorage.keySecret));
$('#account').text(localStorage.keyAccount);
setInterval(timer, 1000);
// Load from local storage
$('#keySecret').val(localStorage.keySecret);
$('#keyAccount').val(localStorage.keyAccount);
} else {
$('#updatingIn').text("x");
$('#account').text("No Storage support");
}
$('#save').click(function () {
// Save in local storage
localStorage.keySecret = $('#keySecret').val();
localStorage.keyAccount = $('#keyAccount').val();
// Set the overview page
$('#otp').text(updateOtp(localStorage.keySecret));
$('#account').text(localStorage.keyAccount);
});
});