-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
372 lines (346 loc) · 14.7 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TOTP Generator</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
margin: 0 1.2em;
box-sizing: border-box;
}
body {
font-family: 'Helvetica Neue', Helvetica, 'Roboto', Arial, sans-serif;
margin: 1em auto;
font-size: 1.05em;
max-width: 80ch;
line-height: 1.5;
}
p, button, hr, .highlight { margin: .8em 0 }
a {
color: #2f559f;
text-decoration: dashed underline
}
a:hover, a:focus { text-decoration: none }
h2 {
font-weight: 700;
font-size: 1.05em;
line-height: 1.5;
margin: .5em 0 0;
}
.disclaimer {
padding: .5em 1.2em;
background: #fffc5a;
position: relative;
left: -1.2em;
right: -1.2em;
width: calc(100% - 1px);
box-sizing: content-box;
}
#form {
margin: 1em auto;
max-width: 50ch;
}
section {
margin: .5em 0;
padding: .5em .8em;
border: 1px solid #cecece;
border-radius: 6px;
}
.longInput {
width: 95%;
max-width: 50ch;
}
label {
font-style: italic;
margin: .5em 0 0;
font-size: 1em;
}
.highlight, button {
background-color: #eef0e6;
display: inline-block; /* so text can be selected on each individual highlight */
padding: 2px 6px 4px;
margin: 0 2px;
text-align: center;
white-space: nowrap;
border-radius: 8px;
font-size: inherit;
}
.bg-yellow { background-color: #f9e193 }
.bg-red { background-color: #ffa1a1 }
.bg-blue { background-color: #c7e5ff }
</style>
</head>
<body>
<main>
<h1 style="margin-bottom: .2em;">Time-based One-time Password Algorithm</h1>
<div class="disclaimer">
<div>This page is a modified version of <a href="https://jsfiddle.net/russau/ch8PK/">russau's JSFiddle</a>. This website works in the browser and does not transmit any data. <a href="https://github.com/xyr11/totp-generator">Check the GitHub page for more info.</a></div>
</div>
<p>This page contains a JavaScript implementation of the <em>Time-based One-time Password Algorithm</em> used by Google Authenticator and other OTP apps, described in the <a href="http://tools.ietf.org/id/draft-mraihi-totp-timebased-06.html">TOTP RFC Draft</a>.</p>
<p>There are a lot of OTP applications available <a href="https://en.wikipedia.org/wiki/Comparison_of_OTP_applications">(check out Wikipedia's list)</a>. TOTP is an open standard, so you can use these apps to create one-time passwords for your own application. Some apps can add an OTP by scanning a QR code with a valid format.</p>
<p>This page implements the same OTP algorithm these apps use – you would use this same algorithm <em>server-side</em> to verify an OTP. Test it by setting the OTP Label and Base32 secret and scanning the QR code in your app. The OTP on your app should be the same as the one at the bottom of this page. (This browser and your app must be synchronized using an internet time source to generate the same OTP codes.)</p>
<p>The properties used below, as well as the QR code generated, are based on the <a href="https://github.com/google/google-authenticator/wiki/Key-Uri-Format">OTP Key URI format by Google</a>.</p>
<noscript>
<div class="disclaimer">Javascript is needed for this page to work.</div>
</noscript>
<div id="form">
<section>
<h2>OTP properties</h2>
<div>
<label for="label">Label:</label>
<div><input type="text" name="label" class="longInput" id="label" placeholder="GitHub: mail@site.com" oninput="fetchOTP()" /></div>
</div>
<div>
<label for="secret">Secret: (<a href="https://en.wikipedia.org/wiki/Base32">in Base32</a>)</label>
<div><input type="text" name="secret" class="longInput" id="secret" placeholder="A-Z & 2-7" oninput="fetchOTP()" /></div>
</div>
<div>
<label for="issuer">Issuer: (optional)</label>
<div><input type="text" name="issuer" class="longInput" id="issuer" placeholder="GitHub" oninput="fetchOTP()" /></div>
</div>
<details>
<summary>QR Code options</summary>
<fieldset>
<div>
<label for="qrbg">background:</label> <input type="text" size="20" name="qrbg" id="background" placeholder="white" oninput="updateQrCode(this.id, this.value)" />
</div>
<div>
<label for="qrbgalpha">backgroundAlpha:</label> <input type="number" size="3" name="qrbgalpha" id="backgroundAlpha" placeholder="1.00" step="0.01" max="1" min="0" value="1" required oninput="updateQrCode(this.id, this.value)" />
</div>
<div>
<label for="qrfg">foreground:</label> <input type="text" size="20" name="qrfg" id="foreground" placeholder="black" oninput="updateQrCode(this.id, this.value)" />
</div>
<div>
<label for="qrfgalpha">foregroundAlpha:</label> <input type="number" size="3" name="qrfgalpha" id="foregroundAlpha" placeholder="1.0" step="0.01" max="1" min="0" value="1" required oninput="updateQrCode(this.id, this.value)" />
</div>
<div>
Level:
<input type="radio" name="qrlvl" id="lvlL" value="lvlL" checked onchange="updateQrCode('level','L')" /><label for="lvlL">L</label>
<input type="radio" name="qrlvl" id="lvlM" value="lvlM" onchange="updateQrCode('level','M')" /><label for="lvlM">M</label>
<input type="radio" name="qrlvl" id="lvlQ" value="lvlQ" onchange="updateQrCode('level','Q')" /><label for="lvlQ">Q</label>
<input type="radio" name="qrlvl" id="lvlH" value="lvlH" onchange="updateQrCode('level','H')" /><label for="lvlH">H</label>
</div>
<div>
<label for="qrmime">mime:</label> <input type="text" size="32" name="qrmime" id="mime" oninput="updateQrCode(this.id, this.value)" />
</div>
<div>
<label for="qrpadd">padding (pixels):</label> <input type="number" size="4" name="qrpadd" id="padding" placeholder="null" step="1" min="0" oninput="updateQrCode(this.id, this.value)" />
</div>
<div>
<label for="qrsize">size (pixels):</label> <input type="number" size="4" name="qrsize" id="size" placeholder="200" step="1" oninput="updateQrCode(this.id, this.value)" />
</div>
<div>
<label for="qrvalue">value:</label> <input type="text" size="32" name="qrvalue" id="value" placeholder="" readonly />
</div>
</fieldset>
</details>
<button onclick="updateOTP()">Update output</button>
</section>
<section id="output">
<h2>One-time Password</h2>
<div><span id='otp'></span></div>
<p>Updating in <span id='updatingIn'></span>s</p>
<h2>Unix epoch div 30 (padded hex)</h2>
<div>
<span id='epoch'></span>
</div>
<h2>Secret (hex)</h2>
<div>
<span id="secretHex"></span>
<span id='secretHexLength'></span>
</div>
<h2>HMAC (secret, time)</h2>
<div id='hmac'></div>
<h2>QR Code</h2>
<img id="qrcode" alt="QR Code image">
<p id="noticeMsg"></p>
</section>
<section>
<h2>Permalink</h2>
<p id="permalink" onclick="this.select()" style="overflow-x:auto"></p>
</section>
</div>
</main>
<script src="js/sha.js"></script>
<script src="js/qrious.min.js"></script>
<script>
/* global QRious, jsSHA */
// Get html element
function elem (id) {
if (id) return document.getElementById(id)
}
// Encoding stuff
function dec2hex (s) {
return (s < 15.5 ? '0' : '') + Math.round(s).toString(16)
}
function hex2dec (s) {
return parseInt(s, 16)
}
function leftpad (str, len, pad) {
if (len + 1 >= str.length) {
return Array(len + 1 - str.length).join(pad) + str
}
}
function errorMessage (text, color = 'red') {
// Hide the outputs and show a message
elem('qrcode').style.display = 'none'
elem('noticeMsg').innerHTML = `<span class="highlight bg-${color}">${text}</span>`
}
// Initialize QR code generator
const qr = new QRious({ element: elem('qrcode') })
const defaultQROptions = { background: 'white', backgroundAlpha: 1, foreground: 'black', foregroundAlpha: 1, level: 'L', mime: 'image/png', padding: null, size: 200 }
const customQROptions = {}
function updateQrCode (property, value) {
// If the previous value is the same as the given value, you don't need to update the variable
if (customQROptions[property] === value) return
// If the value is the same as the default value, you don't need to put it on customQROptions
if (defaultQROptions[property] === value) delete customQROptions[property]
else customQROptions[property] = value
// The default Qrious options will be overwritten by the custom options
qr.set({ ...defaultQROptions, ...customQROptions })
}
let otpFields = {}
// Fetch value of OTP fields and put to object
function fetchOTP () {
const label = elem('label').value
const secret = elem('secret').value
const issuer = elem('issuer').value
// If there are no changes then don't update
if (otpFields.secret === secret && otpFields.label === label && otpFields.issuer === issuer) return
// Add to otpFields variable
otpFields = { label, secret, issuer }
// Check if user has given the required values
if (!secret) return errorMessage('Fill in the Secret field.')
// Reset message box
elem('qrcode').style.display = ''
elem('noticeMsg').innerHTML = ''
// Don't show qr code if label is absent
if (!label) errorMessage('Fill in the Label field.', 'yellow')
// Update OTP
updateOTP()
}
// Solve for the OTP
function updateOTP () {
const label = otpFields.label
const secret = otpFields.secret.toUpperCase()
const issuer = otpFields.issuer
// Compute the key
const base32chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
let bits = ''
for (let i = 0; i < secret.length; i++) {
const val = base32chars.indexOf(secret.charAt(i))
// Check if there are invalid characters
if (val === -1) return errorMessage('Secret is not in Base32.')
bits += leftpad(val.toString(2), 5, '0')
}
// Convert to hex string
let key = ''
for (let i = 0; i + 4 <= bits.length; i += 4) {
const chunk = bits.substr(i, 4)
key = key + parseInt(chunk, 2).toString(16)
}
// Compute the epoch
const epoch = Math.round(new Date().getTime() / 1000.0)
const time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0')
// Show it
elem('epoch').innerHTML = `<span class="highlight">${time}</span>`
elem('secretHex').innerHTML = `<span class="highlight">${key}</span>`
elem('secretHexLength').innerHTML = ((key.length * 4) + ' bits')
elem('secretHex').innerHTML = `<span class="highlight">${time}</span>`
// Try hashing the key
const shaObj = new jsSHA('SHA-1', 'HEX')
let hmac
try {
shaObj.setHMACKey(key, 'HEX')
shaObj.update(time)
hmac = shaObj.getHMAC('HEX')
} catch (err) {
if (err.message === 'String of HEX type must be in byte increments') {
// Show error and prevent computing HMAC and OTP
elem('hmac').innerHTML = '<span class="highlight bg-red">Secret (hex) must be in byte elements</span>'
elem('otp').innerHTML = '<span class="highlight bg-red">Error</span>'
elem('qrcode').style.display = 'none'
return
}
console.error(err)
}
// Compute HMAC
const offset = hex2dec(hmac.substring(hmac.length - 1))
const part1 = hmac.substr(0, offset * 2)
const part2 = hmac.substr(offset * 2, 8)
const part3 = hmac.substr(offset * 2 + 8, hmac.length - offset)
// Display it
elem('hmac').innerHTML = ''
if (part1.length > 0) elem('hmac').innerHTML += `<span class="highlight">${part1}</span>`
elem('hmac').innerHTML += `<span class="highlight bg-blue">${part2}</span>`
if (part3.length > 0) elem('hmac').innerHTML += `<span class="highlight">${part3}</span>`
// Compute OTP
let otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec('7fffffff')) + ''
otp = (otp).substr(otp.length - 6, 6)
// Display it
elem('otp').innerHTML = `<span class="highlight bg-blue">${otp}</span>`
// Create OTP URI and QR Code
let keyUri = `otpauth://totp/${encodeURIComponent(label)}?secret=${secret}`
if (issuer) keyUri += `&issuer=${encodeURIComponent(issuer)}`
// Update value of QR code
updateQrCode('value', keyUri)
elem('value').value = keyUri
// Combine all the inputted data
let allInputs = ({ ...otpFields, ...customQROptions })
// Remove blank fields
allInputs = Object.fromEntries(Object.entries(allInputs).filter(([prop, value]) => value !== '' && value != null))
const searchParams = new URLSearchParams(allInputs)
searchParams.delete('value')
// Add permalink
const permalink = window.location.origin + window.location.pathname + '?' + searchParams.toString()
elem('permalink').innerHTML = `<a href="${permalink}">${permalink}</a>`
}
// Read query fields / URL params
const query = new URLSearchParams(window.location.search)
if (query.size > 0) {
const otpQueries = ['label', 'secret', 'issuer']
const qriousQueries = ['background', 'backgroundAlpha', 'foreground', 'foregroundAlpha', 'mime', 'padding', 'size']
for (const entry of query.entries()) {
if (entry[1]) { // query must have a value
if (otpQueries.indexOf(entry[0]) > -1) {
// Change the value on the respective <input>s
elem(entry[0]).value = entry[1]
} else if (qriousQueries.indexOf(entry[0]) > -1) {
// Change the value on the respective <input>s
elem(entry[0]).value = entry[1]
updateQrCode(entry[0], entry[1])
}
}
}
// Check if there is a valid 'level' option
if (query.has('level') && ['L', 'M', 'Q', 'H'].indexOf(query.get('level')) > -1) {
// Uncheck the current option that's checked
document.querySelector('input[name="qrlvl"]:checked').removeAttribute('checked')
// Check the option given
elem('lvl' + query.get('level')).setAttribute('checked', 'checked')
updateQrCode('level', query.get('level'))
}
// Scroll to form automatically
elem('form').scrollIntoView()
}
// If there are query fields or cached text on the page, read them and update the OTP
fetchOTP();
// Auto update OTP every 30 seconds
(function updateLoop () {
const time = new Date().getTime()
const epoch = Math.round(time / 1000.0)
const countDown = 30 - (epoch % 30)
if (epoch % 30 === 0) updateOTP()
elem('updatingIn').innerHTML = countDown
// Wait for the precise second to run again
setTimeout(updateLoop, (1000 - time % 1000))
})()
</script>
</body>
</html>