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
use crate::Array;
#[cfg(not(feature = "only-gauth"))]
use crate::*;
#[cfg(feature = "alloc")]
use alloc::{
	string::String,
	vec::Vec,
};
use ring::hmac::{
	sign,
	Key,
};

#[cfg(feature = "only-gauth")]
use ring::hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY;
/// A counter-based one-time passcode implementation
#[derive(Debug, Clone)]
pub struct HOTP<A>
where
	A: Array,
{
	/// A fixed-size or vector type of bytes
	pub(crate) sec: A,
	/// The output length of the algorithm
	#[cfg(not(feature = "only-gauth"))]
	pub(crate) len: u8,
	/// The HMAC algorithm being run
	#[cfg(not(feature = "only-gauth"))]
	pub(crate) alg: Algorithm,
}

#[cfg(test)]
mod test {
	// Test values come from https://tools.ietf.org/html/rfc4226
	use super::{
		HOTP,
		TRUNCATE_TO,
	};
	const DATA: &[u8] = b"12345678901234567890";
	const OUTPUT: [(u32, u32); 10] = [
		(0x4c93cf18, 755224),
		(0x41397eea, 287082),
		(0x082fef30, 359152),
		(0x66ef7655, 969429),
		(0x61c5938a, 338314),
		(0x33c083d4, 254676),
		(0x7256c032, 287922),
		(0x04e5b397, 162583),
		(0x2823443f, 399871),
		(0x2679dc69, 520489),
	];
	#[test]
	fn counting_works() {
		let hotp = HOTP::new(DATA);
		let z = (0u64..10).into_iter().zip(OUTPUT.iter());
		for (i, (long, expected)) in z {
			let otp = hotp.generate(i);
			assert_eq!(otp, *expected);

			#[cfg(not(feature = "only-gauth"))]
			{
				let otp = hotp.clone().set_len(9).generate(i);
				assert_eq!(otp, long % TRUNCATE_TO[9]);
			}
			#[cfg(feature = "only-gauth")]
			{
				assert_eq!(otp, long % TRUNCATE_TO[6]);
			}
		}
	}
}

#[doc(hidden)]
/// Enables equivalence checking in debug and test builds. Do not rely on this for production code.
impl<A: Array, B: Array> PartialEq<HOTP<B>> for HOTP<A> {
	fn eq(
		&self,
		other: &HOTP<B>,
	) -> bool {
		#[cfg(feature = "only-gauth")]
		let stuff = true;
		#[cfg(not(feature = "only-gauth"))]
		let stuff = self.len == other.len && self.alg == other.alg;
		let all_xor = self
			.sec
			.as_slice()
			.iter()
			.zip(other.sec.as_slice())
			.fold(0u8, |v, (a, b)| v | (a ^ b));
		self.sec.as_slice().len() == other.sec.as_slice().len()
			&& 0 == all_xor
			&& stuff
	}
}

/// Length to truncate a counter to, by index.
pub const TRUNCATE_TO: [u32; 10] = [
	1,
	10,
	100,
	1_000,
	10_000,
	100_000,
	1_000_000,
	10_000_000,
	100_000_000,
	1_000_000_000,
];
impl<A: Array> HOTP<A> {
	/// Creates a new HOTP algorithm verifier.
	///
	/// ```rust
	/// use miniotp::HOTP;
	/// let hotp = HOTP::new(b"secret A");
	/// let hotp_other = HOTP::new(b"secret B");
	/// # assert_ne!(hotp, hotp_other, "secrets are different");
	/// ```
	pub fn new(sec: A) -> Self {
		#[cfg(not(feature = "only-gauth"))]
		let new = Self {
			sec,
			len: 6,
			alg: SHA1,
		};
		#[cfg(feature = "only-gauth")]
		let new = Self { sec };
		new
	}

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

	/// Generates a HOTP value.
	///
	/// ```rust
	/// use miniotp::{HOTP};
	/// let hotp = HOTP::new(b"12345678901234567890");
	/// let otp = hotp.generate(1);
	/// assert_eq!(otp, 287_082);
	/// ```
	pub fn generate(
		&self,
		counter: u64,
	) -> u32 {
		let key = self.sec.as_slice();

		#[cfg(feature = "only-gauth")]
		let key = Key::new(HMAC_SHA1_FOR_LEGACY_USE_ONLY, key);
		#[cfg(not(feature = "only-gauth"))]
		let key = Key::new(self.alg.into(), key);

		let counter = counter.to_be_bytes();
		let result = sign(&key, &counter);
		let digest = result.as_ref();

		#[cfg(feature = "only-gauth")]
		let last = 19;
		#[cfg(not(feature = "only-gauth"))]
		let last = match self.alg {
			SHA1 => 19,
			SHA256 => 31,
			SHA512 => 63,
		};

		// SAFETY: this is safe as digest always returns a minimum 20 byte slice when using SHA-1.
		let offset = (unsafe { digest.get_unchecked(last) } & 0x0F) as usize;
		// SAFETY: this is safe as offset always satisfies offset @ 0..16.
		let value = u32::from_be_bytes(unsafe {
			[
				0x7F & *digest.get_unchecked(offset),
				*digest.get_unchecked(offset + 1),
				*digest.get_unchecked(offset + 2),
				*digest.get_unchecked(offset + 3),
			]
		});

		#[cfg(feature = "only-gauth")]
		let len = 6;
		#[cfg(not(feature = "only-gauth"))]
		let len = self.len as usize;

		value % TRUNCATE_TO[len]
	}

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

	/// Verifies a HOTP counter range.
	///
	/// This function consumes `self`.
	pub fn verify_range<I>(
		self,
		counter: u64,
		input: u32,
		diffs: I,
	) -> bool
	where
		I: IntoIterator<Item = i64>,
	{
		let mut ok = false;
		for diff in diffs {
			let new_count = if diff.is_negative() {
				counter + (diff.abs() as u64)
			} else {
				counter - diff as u64
			};
			ok |= self.verify(new_count, input);
		}
		ok
	}
}
#[cfg(not(feature = "only-gauth"))]
impl<A: Array> HOTP<A> {
	/// Sets the algorithm.
	///
	/// ```rust
	/// use miniotp::{HOTP, SHA1, SHA256, SHA512};
	/// let hotp_default = HOTP::new(b"secret");
	/// let hotp_sha1 = HOTP::new(b"secret").set_alg(SHA1);
	/// # assert_eq!(hotp_default, hotp_sha1, "default algorithm is sha1");
	/// let hotp_sha256 = HOTP::new(b"secret").set_alg(SHA256);
	/// let hotp_sha512 = HOTP::new(b"secret").set_alg(SHA512);
	/// # assert_ne!(hotp_sha256, hotp_sha512, "sha256 and sha512 are different algs");
	/// # dbg!((hotp_sha1, hotp_sha256, hotp_sha512));
	/// ```
	pub fn set_alg(
		mut self,
		alg: crate::alg::Algorithm,
	) -> Self {
		self.alg = alg;
		self
	}

	/// Sets the output length.
	///
	/// ```rust
	/// use miniotp::{HOTP};
	/// let hotp_default = HOTP::new(b"secret");
	/// let hotp_len_6 = HOTP::new(b"secret").set_len(6);
	/// # assert_eq!(hotp_default, hotp_len_6, "default len is 6");
	/// let hotp_len_7 = HOTP::new(b"secret").set_len(7);
	/// let hotp_len_8 = HOTP::new(b"secret").set_len(8);
	/// # dbg!((hotp_len_6, hotp_len_7, hotp_len_8));
	/// ```
	pub fn set_len(
		mut self,
		len: u8,
	) -> Self {
		self.len = len;
		self
	}
}
#[cfg(all(feature = "base32", any(feature = "std", feature = "alloc")))]
mod b32 {
	use crate::{
		Array,
		Error,
		B32A,
		HOTP,
	};
	#[cfg(feature = "alloc")]
	use alloc::{
		str::from_utf8_unchecked,
		string::String,
		vec::Vec,
	};
	#[cfg(feature = "cstr")]
	use std::ffi::CStr;
	impl<A: Array> HOTP<A> {
		/// Returns the base32 encoded equivalent of the internal secret.
		///
		/// ```rust
		/// use miniotp::HOTP;
		/// let sec_human = HOTP::new(b"HUMAN").base32_secret();
		/// assert_eq!(sec_human, "JBKU2QKO");
		/// ```
		pub fn base32_secret(&self) -> String {
			base32::encode(B32A, self.sec.as_slice())
		}

		/// Returns an iterator over base32 segments of `chunk` size.
		pub fn base32_segs(
			&self,
			chunk_size: usize,
		) -> crate::Segs {
			let sec = self.base32_secret();
			crate::Segs {
				sec,
				chunk_size,
				curr: 0,
			}
		}

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

		/// Method to take a base32 cstr and use it as an inital vector.
		///
		/// ```rust
		/// # fn main() -> Result<(), miniotp::Error> {
		/// use miniotp::HOTP;
		/// use std::ffi::CString;
		/// let cs = CString::new("AAAAAAAA").expect("cstr");
		/// let otp = HOTP::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> {
			let s = s.as_ref().to_str()?;
			base32::decode(B32A, s)
				.ok_or_else(|| Error::BadEnc)
				.map(|v| Self::new(v))
		}

		/// Method to take a base32 cstr-like and use it as an inital vector.
		///
		/// ```rust
		/// # fn main() -> Result<(), miniotp::Error> {
		/// use miniotp::HOTP;
		/// let otp = HOTP::from_base32b(b"AAAAAAAA\0")?.generate(3);
		/// # dbg!(otp);
		/// # assert!(otp < u32::MAX);
		/// # Ok(())
		/// # }
		/// ```
		pub fn from_base32b<'a, I: IntoIterator<Item = &'a u8>>(
			i: I
		) -> Result<Self, Error> {
			let key: Vec<u8> = i
				.into_iter()
				.copied()
				.take_while(u8::is_ascii_graphic)
				.collect();
			// SAFETY: the key above is always valid ascii. This is actually safe.
			let key = unsafe { String::from_utf8_unchecked(key) };
			Self::from_base32(key)
		}
	}
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<A: Array> HOTP<A> {
	/// Generates the value as a string.
	///
	/// ```rust
	/// use miniotp::HOTP;
	/// let s = HOTP::new(b"12345678901234567890").generate_str(349495);
	/// assert_eq!(s, "000000");
	/// ```
	pub fn generate_str(
		&self,
		counter: u64,
	) -> String {
		let value = self.generate(counter);
		#[cfg(feature = "only-gauth")]
		let len = 6;
		#[cfg(not(feature = "only-gauth"))]
		let len = self.len;
		format!("{v:0<len$}", len = len, v = value)
	}
}