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
use crate::{
	Array,
	HOTP,
};

/// A time-based one-time passcode implementation
#[derive(Debug, Clone, PartialEq)]
pub struct TOTP<A>
where
	A: Array,
{
	/// The internal TOTP state. See its documentation for more.
	hotp: HOTP<A>,
	#[cfg(not(feature = "only-gauth"))]
	/// The epoch of the TOTP implementation, in seconds. Almost always zero.
	epoch: u64,
	#[cfg(not(feature = "only-gauth"))]
	/// The period of the TOTP implementation, in seconds.
	period: u64,
}

impl<A: Array> From<HOTP<A>> for TOTP<A> {
	fn from(hotp: HOTP<A>) -> Self {
		#[cfg(not(feature = "only-gauth"))]
		let new = Self {
			hotp,
			epoch: 0,
			period: 30,
		};
		#[cfg(feature = "only-gauth")]
		let new = Self { hotp };
		new
	}
}

// this hacky test doesn't work without std or alloc.
#[cfg(all(test, any(feature = "alloc", feature = "std")))]
mod test {
	// test values come from https://tools.ietf.org/html/rfc6238#appendix-B
	use crate::*;
	#[cfg(feature = "alloc")]
	use alloc::vec::Vec;
	const SHA1_VALUES: [(u64, u32); 6] = [
		(59, 94_287_082),
		(1111111109, 7_081_804),
		(1111111111, 14_050_471),
		(1234567890, 89_005_924),
		(2000000000, 69_279_037),
		(20000000000, 65_353_130),
	];

	#[cfg(not(feature = "only-gauth"))]
	const VALUES: [(Algorithm, [(u64, u32); 6]); 3] = [
		(SHA1, SHA1_VALUES),
		(SHA256, [
			(59, 46_119_246),
			(1111111109, 68_084_774),
			(1111111111, 67_062_674),
			(1234567890, 91_819_424),
			(2000000000, 90_698_825),
			(20000000000, 77_737_706),
		]),
		(SHA512, [
			(59, 90_693_936),
			(1111111109, 25_091_201),
			(1111111111, 99_943_326),
			(1234567890, 93_441_116),
			(2000000000, 38_618_901),
			(20000000000, 47_863_826),
		]),
	];
	#[test]
	fn works_with_std_or_alloc() {
		#[cfg(feature = "only-gauth")]
		let values = Some(((), SHA1_VALUES)).iter();
		#[cfg(not(feature = "only-gauth"))]
		let values = VALUES.iter();
		for (alg, values) in values {
			#[cfg(not(feature = "only-gauth"))]
			let len = match alg {
				SHA1 => 20,
				SHA256 => 32,
				SHA512 => 64,
			};
			#[cfg(feature = "only-gauth")]
			let len = 20;
			let sec: Vec<u8> = (b'0'..=b'9')
				.into_iter()
				.cycle()
				.skip(1)
				.take(len)
				.collect();
			#[cfg(feature = "std")]
			dbg!(String::from_utf8(sec.clone()).unwrap());
			#[cfg(not(feature = "only-gauth"))]
			let totp = TOTP::new(sec).set_alg(*alg).set_len(8);
			#[cfg(feature = "only-gauth")]
			let totp = TOTP::new(sec);
			for (time, expected) in values.iter() {
				#[cfg(feature = "only-gauth")]
				let expected = &(expected % 1_000_000);
				let otp = totp.generate(*time);
				assert_eq!(otp, *expected, "{:?} @ {} fail", alg, time);
				#[cfg(feature = "std")]
				dbg!((otp, expected, alg, time));
			}
		}
	}
}

impl<A: Array> TOTP<A> {
	/// Creates a new TOTP algorithm verifier.
	///
	/// ```rust
	/// use miniotp::TOTP;
	/// let totp = TOTP::new(b"secret A");
	/// let totp_other = TOTP::new(b"secret B");
	/// # assert_ne!(totp, totp_other, "secrets are different");
	/// ```
	pub fn new(a: A) -> Self {
		HOTP::new(a).into()
	}

	/// Verifies a TOTP range from -1 to +1.
	///
	/// This function consumes `self`.
	pub fn verify_range_default(
		self,
		time: u64,
		input: u32,
	) -> bool {
		self.verify_range(time, input, -1..=1)
	}

	/// Generates a HOTP value.
	///
	/// ```rust
	/// use miniotp::{TOTP};
	/// let totp = TOTP::new(b"12345678901234567890");
	/// let gauthkey = totp.generate(30);
	/// assert_eq!(gauthkey, 287_082);
	/// ```
	pub fn generate(
		&self,
		time: u64,
	) -> u32 {
		#[cfg(feature = "only-gauth")]
		let time = time / 30;
		#[cfg(not(feature = "only-gauth"))]
		let time = (time - self.epoch) / self.period;
		self.hotp.generate(time)
	}

	/// Verifies a TOTP value.
	///
	/// ```rust
	/// use miniotp::{TOTP};
	/// let totp = TOTP::new(b"12345678901234567890");
	/// let otp = totp.verify(349495 * 30, 000_000);
	/// assert_eq!(otp, true);
	/// ```
	pub fn verify(
		&self,
		time: u64,
		input: u32,
	) -> bool {
		let value = self.generate(time);
		// input xor value must always return zero, or it is not correct
		(input ^ value) == 0
	}

	/// Verifies a TOTP time range.
	///
	/// This function consumes `self`.
	pub fn verify_range<I>(
		self,
		time: u64,
		input: u32,
		diffs: I,
	) -> bool
	where
		I: IntoIterator<Item = i64>,
	{
		let mut ok = false;
		#[cfg(not(feature = "only-gauth"))]
		let df = |v| self.period * v;
		#[cfg(feature = "only-gauth")]
		let df = |v| 30 * v;
		for diff in diffs {
			let new_count = if diff.is_negative() {
				time + df(diff.abs() as u64)
			} else {
				time - df(diff as u64)
			};
			ok |= self.verify(new_count, input);
		}
		ok
	}
}

#[cfg(feature = "std")]
impl<A: Array> TOTP<A> {
	/// Verifies a TOTP range at the current time with a range of -1..=+1 period.
	///
	/// This function consumes `self`.
	///
	/// ```rust
	/// use miniotp::TOTP;
	/// let totp = TOTP::new(b"AAAAAAAA").verify_range_default_now(123);
	/// # use core::any::Any;
	/// # assert_eq!(totp.type_id(), true.type_id());
	/// ```
	///
	/// ### Panics
	///
	/// This function will panic if system time is less than the unix epoch.
	pub fn verify_range_default_now(
		self,
		input: u32,
	) -> bool {
		use std::time::*;
		let time = SystemTime::now()
			.duration_since(SystemTime::UNIX_EPOCH)
			.expect("System time to be greater than the unix epoch")
			.as_secs();
		self.verify_range_default(time, input)
	}

	/// Generates a TOTP value at the current time.
	///
	/// ### Panics
	///
	/// This function will panic if system time is less than the unix epoch.
	pub fn generate_now(&self) -> u32 {
		use std::time::*;
		let time = SystemTime::now()
			.duration_since(SystemTime::UNIX_EPOCH)
			.expect("System time to be greater than the unix epoch")
			.as_secs();
		self.generate(time)
	}
}

#[cfg(not(feature = "only-gauth"))]
impl<A: Array> TOTP<A> {
	/// Sets the algorithm.
	///
	/// This functions the same as [`HOTP::set_alg`](./struct.HOTP.html#method.set_alg);
	/// see its documentation for more.
	pub fn set_alg(
		mut self,
		alg: crate::alg::Algorithm,
	) -> Self {
		self.hotp.alg = alg;
		self
	}

	/// Sets the output length.
	///
	/// This functions the same as [`HOTP::set_len`](./struct.HOTP.html#method.set_len);
	/// see its documentation for more.
	pub fn set_len(
		mut self,
		len: u8,
	) -> Self {
		self.hotp.len = len;
		self
	}

	/// Sets the period, in seconds.
	///
	/// ```rust
	/// use miniotp::TOTP;
	/// // use a 53 second period for fairly unaligned intervals
	/// let otp = TOTP::new(b"secret")
	///   .set_period(53)
	///   .generate(3);
	/// # dbg!(otp);
	/// ```
	pub fn set_period(
		mut self,
		period: u64,
	) -> Self {
		self.period = period;
		self
	}

	/// Sets the epoch, in seconds.
	///
	/// ```rust
	/// use miniotp::TOTP;
	/// // use 2000-01-01T00:00:00Z as your epoch
	/// let otp = TOTP::new(b"secret")
	///   .set_epoch(946_684_800)
	///   .generate(1_577_836_800);
	/// ```
	///
	/// ### Panics
	///
	/// This function can cause a panic if `generate` or `generate_now` is given a time before the
	/// epoch.
	pub fn set_epoch(
		mut self,
		epoch: u64,
	) -> Self {
		self.epoch = epoch;
		self
	}
}

#[cfg(all(feature = "base32", any(feature = "std", feature = "alloc")))]
pub mod b32 {
	use crate::{
		Array,
		Error,
		HOTP,
		TOTP,
	};
	#[cfg(feature = "alloc")]
	use alloc::{
		string::String,
		vec::Vec,
	};
	#[cfg(feature = "cstr")]
	use std::ffi::CStr;
	impl<A: Array> TOTP<A> {
		/// Returns the base32 encoded equivalent of the internal secret.
		///
		/// ```rust
		/// # fn main() -> Result<(), miniotp::Error> {
		/// use miniotp::TOTP;
		/// let totp = TOTP::new(b"\0\x01\x02\x03\x04");
		/// let b32 = totp.base32_secret();
		/// assert_eq!(b32, "AAAQEAYE");
		/// # Ok(()) }
		/// ```
		pub fn base32_secret(&self) -> String {
			self.hotp.base32_secret()
		}

		/// Returns an iterator over a the encoded secret of a string of `chunk` size.
		pub fn base32_segs(
			&self,
			chunk: usize,
		) -> crate::Segs {
			self.hotp.base32_segs(chunk)
		}

		/// Generates a URI for this TOTP authenticator, given a label and issuer.
		pub fn to_uri<S: AsRef<str>>(
			&self,
			label: S,
			issuer: S,
		) -> String {
			#[cfg(feature = "only-gauth")]
			let (alg, len, per, epoch) = {
				#[derive(Debug)]
				struct SHA1;
				(SHA1, 6, 30, 0)
			};
			#[cfg(not(feature = "only-gauth"))]
			let (alg, len, per, epoch) =
				(self.hotp.alg, self.hotp.len, self.period, self.epoch);
			format!(
				"otpauth://totp/{lbl}?secret={sec}&issuer={iss}&algorithm={alg:?}&digits={len}&period={per}&epoch={T0}",
				sec = self.base32_secret(),
				lbl = label.as_ref(),
				iss = issuer.as_ref(),
				alg = alg,
				len = len,
				per = per,
				T0 = epoch
			)
		}
	}
	impl TOTP<Vec<u8>> {
		/// Method to take a base32 string and use it as an inital vector.
		///
		/// ```rust
		/// # fn main() -> Result<(), miniotp::Error> {
		/// use miniotp::{TOTP};
		/// let otp = TOTP::from_base32("AAAAAAAA")?.generate(3);
		/// # dbg!(otp);
		/// # assert!(otp < u32::MAX);
		/// # Ok(())
		/// # }
		/// ```
		pub fn from_base32<S: AsRef<str>>(s: S) -> Result<Self, Error> {
			HOTP::from_base32(s).map(Into::into)
		}

		/// Method to take a base32 cstr and use it as an inital vector.
		///
		/// ```rust
		/// # fn main() -> Result<(), miniotp::Error> {
		/// use miniotp::TOTP;
		/// use std::ffi::CString;
		/// let cs = CString::new("AAAAAAAA").expect("cstr");
		/// let otp = TOTP::from_base32c(cs)?.generate(3);
		/// # dbg!(otp);
		/// # assert!(otp < u32::MAX);
		/// # Ok(())
		/// # }
		/// ```
		#[cfg(feature = "cstr")]
		pub fn from_base32c<C: AsRef<CStr>>(s: C) -> Result<Self, Error> {
			HOTP::from_base32c(s).map(Into::into)
		}

		/// Method to take a base32 cstr-like and use it as an inital vector.
		///
		/// ```rust
		/// # fn main() -> Result<(), miniotp::Error> {
		/// use miniotp::TOTP;
		/// let otp = TOTP::from_base32b(b"AAAAAAAA\0")?.generate(3);
		/// # dbg!(otp);
		/// # assert!(otp < u32::MAX);
		/// # Ok(())
		/// # }
		/// ```
		pub fn from_base32b<'a, I: IntoIterator<Item = &'a u8>>(
			iter: I
		) -> Result<Self, Error> {
			HOTP::from_base32b(iter).map(Into::into)
		}
	}
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<A: Array> TOTP<A> {
	/// Generates the value as a string.
	///
	/// ```rust
	/// use miniotp::TOTP;
	/// let s = TOTP::new(b"12345678901234567890").generate_str(59);
	/// assert_eq!(s, "287082");
	/// ```
	pub fn generate_str(
		&self,
		time: u64,
	) -> String {
		let value = self.generate(time);
		#[cfg(feature = "only-gauth")]
		let len = 6;
		#[cfg(not(feature = "only-gauth"))]
		let len = self.hotp.len;
		format!("{v:0<len$}", len = len, v = value)
	}
}