Merge pull request #28 from constantoine/refinement Make otpauth fields optionnal
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml
index be67e20..ee7fe1b 100644
--- a/.github/workflows/rust.yml
+++ b/.github/workflows/rust.yml
@@ -21,8 +21,16 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- - name: Test
+ - name: All features
run: cargo test --all-features
+ - name: No feature
+ run: cargo test
+ - name: otpauth feature
+ run: cargo test --features=otpauth
+ - name: gen_secret feature
+ run: cargo test --features=gen_secret
+ - name: otpauth+gensecret feature
+ run: cargo test --features=gen_secret,otpauth
coverage:
runs-on: ubuntu-latest
diff --git a/Cargo.toml b/Cargo.toml
index c8ace63..0600991 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "totp-rs"
-version = "2.0.1"
+version = "3.0.0"
authors = ["Cleo Rebert <cleo.rebert@gmail.com>"]
edition = "2021"
readme = "README.md"
@@ -33,4 +33,4 @@ constant_time_eq = "~0.2.1"
qrcodegen = { version = "~1.8", optional = true }
image = { version = "~0.24.2", features = ["png"], optional = true, default-features = false}
base64 = { version = "~0.13", optional = true }
-rand = { version = "~0.8.5", optional = true }
\ No newline at end of file
+rand = { version = "~0.8.5", features = ["std_rng", "std"], optional = true, default-features = false }
\ No newline at end of file
diff --git a/README.md b/README.md
index 8ef67f5..39a170c 100644
--- a/README.md
+++ b/README.md
@@ -10,23 +10,48 @@ Be aware that some authenticator apps will accept the `SHA256` and `SHA512` algo
## Features
---
### qr
-With optional feature "qr", you can use it to generate a base64 png qrcode. This will enable feature `otpauth`
+With optional feature "qr", you can use it to generate a base64 png qrcode. This will enable feature `otpauth`.
### otpauth
-With optional feature "otpauth", support parsing the TOTP parameters from an `otpauth` URL, and generating an `otpauth` URL
+With optional feature "otpauth", support parsing the TOTP parameters from an `otpauth` URL, and generating an `otpauth` URL. It adds 2 fields to `TOTP`.
### serde_support
-With optional feature "serde_support", library-defined types `TOTP` and `Algorithm` and will be Deserialize-able and Serialize-able
+With optional feature "serde_support", library-defined types `TOTP` and `Algorithm` and will be Deserialize-able and Serialize-able.
+### gen_secret
+With optional feature "gen_secret", a secret will be generated for you to store in database.
-## How to use
+
+# Examples
+
+## Summarry
+
+0. [Understanding Secret](#understanding-secret)
+1. [Generate a token](#generate-a-token)
+2. [Enable qrcode generation](#with-qrcode-generation)
+3. [Enable serde support](#with-serde-support)
+4. [Enable otpauth url support](#with-otpauth-url-support)
+5. [Enable gen_secret support](#with-gensecret)
+6. [With RFC-6238 compliant default](#with-rfc-6238-compliant-default)
+
+### Understanding Secret
+---
+This new type was added as a disambiguation between Raw and already base32 encoded secrets.
+```Rust
+ Secret::Raw("TestSecretSuperSecret".as_bytes().to_vec())
+```
+Is equivalent to
+```Rust
+ Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string())
+```
+### Generate a token
---
Add it to your `Cargo.toml`:
```toml
[dependencies]
-totp-rs = "^2.0"
+totp-rs = "^3.0"
```
You can then do something like:
```Rust
use std::time::SystemTime;
-use totp_rs::{Algorithm, TOTP};
+use totp_rs::{Algorithm, TOTP, Secret};
fn main() {
let totp = TOTP::new(
@@ -34,26 +59,40 @@ fn main() {
6,
1,
30,
- "supersecret",
- Some("Github".to_string()),
- "constantoine@github.com".to_string(),
+ Secret::Raw("TestSecretSuperSecret".as_bytes().to_vec()).to_bytes().unwrap(),
).unwrap();
let token = totp.generate_current().unwrap();
println!("{}", token);
}
```
+Which is equivalent to:
+```Rust
+use std::time::SystemTime;
+use totp_rs::{Algorithm, TOTP, Secret};
+fn main() {
+ let totp = TOTP::new(
+ Algorithm::SHA1,
+ 6,
+ 1,
+ 30,
+ Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()).to_bytes().unwrap(),
+ ).unwrap();
+ let token = totp.generate_current().unwrap();
+ println!("{}", token);
+}
+```
### With qrcode generation
-
+---
Add it to your `Cargo.toml`:
```toml
[dependencies.totp-rs]
-version = "^2.0"
+version = "^3.0"
features = ["qr"]
```
You can then do something like:
```Rust
-use totp_rs::{Algorithm, TOTP};
+use totp_rs::{Algorithm, TOTP, Secret};
fn main() {
let totp = TOTP::new(
@@ -61,29 +100,30 @@ fn main() {
6,
1,
30,
- "supersecret",
+ Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()).to_bytes().unwrap(),
Some("Github".to_string()),
"constantoine@github.com".to_string(),
).unwrap();
- let code = totp.get_qr("user@example.com", "my-org.com")?;
+ let code = totp.get_qr()?;
println!("{}", code);
}
```
### With serde support
+---
Add it to your `Cargo.toml`:
```toml
[dependencies.totp-rs]
-version = "^2.0"
+version = "^3.0"
features = ["serde_support"]
```
### With otpauth url support
-
+---
Add it to your `Cargo.toml`:
```toml
[dependencies.totp-rs]
-version = "^2.0"
+version = "^3.0"
features = ["otpauth"]
```
You can then do something like:
@@ -91,8 +131,84 @@ You can then do something like:
use totp_rs::TOTP;
fn main() {
- let otpauth = "otpauth://totp/GitHub:constantoine@github.com?secret=ABC&issuer=GitHub";
+ let otpauth = "otpauth://totp/GitHub:constantoine@github.com?secret=KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ&issuer=GitHub";
let totp = TOTP::from_url(otpauth).unwrap();
println!("{}", totp.generate_current().unwrap());
}
+```
+
+### With gen_secret
+---
+Add it to your `Cargo.toml`:
+```toml
+[dependencies.totp-rs]
+version = "^3.0"
+features = ["gen_secret"]
+```
+You can then do something like:
+```Rust
+use totp_rs::{Algorithm, TOTP, Secret};
+
+fn main() {
+ let totp = TOTP::new(
+ Algorithm::SHA1,
+ 6,
+ 1,
+ 30,
+ Secret::default().to_bytes().unwrap(),
+ Some("Github".to_string()),
+ "constantoine@github.com".to_string(),
+ ).unwrap();
+ let code = totp.get_qr()?;
+ println!("{}", code);
+}
+```
+Which is equivalent to
+```Rust
+use totp_rs::{Algorithm, TOTP, Secret};
+
+fn main() {
+ let totp = TOTP::new(
+ Algorithm::SHA1,
+ 6,
+ 1,
+ 30,
+ Secret::generate_secret().to_bytes().unwrap(),
+ Some("Github".to_string()),
+ "constantoine@github.com".to_string(),
+ ).unwrap();
+ let code = totp.get_qr()?;
+ println!("{}", code);
+}
+```
+
+### With RFC-6238 compliant default
+---
+You can do something like this
+```Rust
+use totp_rs::{Algorithm, TOTP, Secret, Rfc6238};
+
+fn main () {
+ let mut rfc = Rfc6238::with_defaults(
+ Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()).to_bytes().unwrap(),
+ )
+ .unwrap();
+
+ // optional, set digits
+ rfc.digits(8).unwrap();
+
+ // create a TOTP from rfc
+ let totp = TOTP::from_rfc6238(rfc).unwrap();
+ let code = totp.generate_current().unwrap();
+ println!("code: {}", code);
+}
+```
+With `gen_secret` feature, you can go even further and have all values by default and a secure secret.
+
+Note: With `otpauth` feature, `TOTP.issuer` will be `None`, and `TOTP.account_name` will be `""`. Be sure to set those fields before generating an URL/QRCode
+```Rust
+fn main() {
+ let totp = TOTP::default();
+ println!("code: {}", code);
+}
```
\ No newline at end of file
diff --git a/examples/gen_secret.rs b/examples/gen_secret.rs
index d8c0878..527fc10 100644
--- a/examples/gen_secret.rs
+++ b/examples/gen_secret.rs
@@ -1,8 +1,7 @@
-#[cfg(not(feature = "gen_secret"))]
-compile_error!("requires feature gen_secret");
-
+#[cfg(all(feature = "gen_secret", feature = "otpauth"))]
use totp_rs::{Secret, TOTP, Algorithm};
+#[cfg(all(feature = "gen_secret", feature = "otpauth"))]
fn main () {
let secret = Secret::generate_secret();
@@ -24,3 +23,6 @@ fn main () {
totp.generate_current().unwrap()
)
}
+
+#[cfg(not(all(feature = "gen_secret", feature = "otpauth")))]
+fn main () {}
\ No newline at end of file
diff --git a/examples/rfc-6238.rs b/examples/rfc-6238.rs
index 12a9d59..4e3975c 100644
--- a/examples/rfc-6238.rs
+++ b/examples/rfc-6238.rs
@@ -1,5 +1,6 @@
use totp_rs::{Rfc6238, TOTP};
+#[cfg(feature = "otpauth")]
fn main () {
let mut rfc = Rfc6238::with_defaults(
"totp-sercret-123"
@@ -15,3 +16,18 @@ fn main () {
let code = totp.generate_current().unwrap();
println!("code: {}", code);
}
+
+#[cfg(not(feature = "otpauth"))]
+fn main () {
+ let mut rfc = Rfc6238::with_defaults(
+ "totp-sercret-123"
+ ).unwrap();
+
+ // optional, set digits, issuer, account_name
+ rfc.digits(8).unwrap();
+
+ // create a TOTP from rfc
+ let totp = TOTP::from_rfc6238(rfc).unwrap();
+ let code = totp.generate_current().unwrap();
+ println!("code: {}", code);
+}
\ No newline at end of file
diff --git a/examples/secret.rs b/examples/secret.rs
index 5ff7276..adf1eaa 100644
--- a/examples/secret.rs
+++ b/examples/secret.rs
@@ -1,5 +1,6 @@
use totp_rs::{Secret, TOTP, Algorithm};
+#[cfg(feature = "otpauth")]
fn main () {
// create TOTP from base32 secret
let secret_b32 = Secret::Encoded(String::from("OBWGC2LOFVZXI4TJNZTS243FMNZGK5BNGEZDG"));
@@ -9,8 +10,8 @@ fn main () {
1,
30,
secret_b32.to_bytes().unwrap(),
- None,
- "account".to_string(),
+ Some("issuer".to_string()),
+ "user-account".to_string(),
).unwrap();
println!("base32 {} ; raw {}", secret_b32, secret_b32.to_raw().unwrap());
@@ -28,10 +29,43 @@ fn main () {
1,
30,
secret_raw.to_bytes().unwrap(),
- None,
- "account".to_string(),
+ Some("issuer".to_string()),
+ "user-account".to_string(),
).unwrap();
println!("raw {} ; base32 {}", secret_raw, secret_raw.to_encoded());
println!("code from raw secret:\t{}", totp_raw.generate_current().unwrap());
}
+
+#[cfg(not(feature = "otpauth"))]
+fn main () {
+ // create TOTP from base32 secret
+ let secret_b32 = Secret::Encoded(String::from("OBWGC2LOFVZXI4TJNZTS243FMNZGK5BNGEZDG"));
+ let totp_b32 = TOTP::new(
+ Algorithm::SHA1,
+ 6,
+ 1,
+ 30,
+ secret_b32.to_bytes().unwrap(),
+ ).unwrap();
+
+ println!("base32 {} ; raw {}", secret_b32, secret_b32.to_raw().unwrap());
+ println!("code from base32:\t{}", totp_b32.generate_current().unwrap());
+
+ // create TOTP from raw binary value
+ let secret = [
+ 0x70, 0x6c, 0x61, 0x69, 0x6e, 0x2d, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x2d, 0x73, 0x65,
+ 0x63, 0x72, 0x65, 0x74, 0x2d, 0x31, 0x32, 0x33,
+ ];
+ let secret_raw = Secret::Raw(secret.to_vec());
+ let totp_raw = TOTP::new(
+ Algorithm::SHA1,
+ 6,
+ 1,
+ 30,
+ secret_raw.to_bytes().unwrap(),
+ ).unwrap();
+
+ println!("raw {} ; base32 {}", secret_raw, secret_raw.to_encoded());
+ println!("code from raw secret:\t{}", totp_raw.generate_current().unwrap());
+}
\ No newline at end of file
diff --git a/examples/ttl.rs b/examples/ttl.rs
index 7554303..ec2c1a8 100644
--- a/examples/ttl.rs
+++ b/examples/ttl.rs
@@ -1,5 +1,6 @@
use totp_rs::{Algorithm, TOTP};
+#[cfg(not(feature = "otpauth"))]
fn main() {
let totp = TOTP::new(
Algorithm::SHA1,
@@ -7,8 +8,30 @@ fn main() {
1,
30,
"my-secret".to_string(),
- None,
- "account".to_string(),
+ ).unwrap();
+
+ loop {
+ println!(
+ "code {}\t ttl {}\t valid until: {}",
+ totp.generate_current().unwrap(),
+ totp.ttl().unwrap(),
+ totp.next_step_current().unwrap()
+ );
+ std::thread::sleep(std::time::Duration::from_secs(1));
+ }
+}
+
+
+#[cfg(feature = "otpauth")]
+fn main() {
+ let totp = TOTP::new(
+ Algorithm::SHA1,
+ 6,
+ 1,
+ 30,
+ "my-secret".to_string(),
+ Some("Github".to_string()),
+ "constantoine@github.com".to_string()
).unwrap();
loop {
diff --git a/src/lib.rs b/src/lib.rs
index c33e800..382585c 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -9,20 +9,22 @@
//! # Examples
//!
//! ```rust
+//! # #[cfg(feature = "otpauth")] {
//! use std::time::SystemTime;
-//! use totp_rs::{Algorithm, TOTP};
+//! use totp_rs::{Algorithm, TOTP, Secret};
//!
//! let totp = TOTP::new(
//! Algorithm::SHA1,
//! 6,
//! 1,
//! 30,
-//! "supersecret_topsecret",
+//! Secret::Raw("TestSecretSuperSecret".as_bytes().to_vec()).to_bytes().unwrap(),
//! Some("Github".to_string()),
//! "constantoine@github.com".to_string(),
//! ).unwrap();
//! let token = totp.generate_current().unwrap();
//! println!("{}", token);
+//! # }
//! ```
//!
//! ```rust
@@ -142,10 +144,12 @@ pub struct TOTP<T = Vec<u8>> {
///
/// non-encoded value
pub secret: T,
+ #[cfg(feature = "otpauth")]
/// The "Github" part of "Github:constantoine@github.com". Must not contain a colon `:`
/// For example, the name of your service/website.
/// Not mandatory, but strongly recommended!
pub issuer: Option<String>,
+ #[cfg(feature = "otpauth")]
/// The "constantoine@github.com" part of "Github:constantoine@github.com". Must not contain a colon `:`
/// For example, the name of your user's account.
pub account_name: String
@@ -171,7 +175,23 @@ impl <T: AsRef<[u8]>> PartialEq for TOTP<T> {
}
}
+#[cfg(all(feature = "gen_secret", not(feature = "otpauth")))]
+impl Default for TOTP {
+ fn default() -> Self {
+ return TOTP::new(Algorithm::SHA1, 6, 1, 30, Secret::generate_secret().to_bytes().unwrap()).unwrap()
+ }
+}
+
+#[cfg(all(feature = "gen_secret", feature = "otpauth"))]
+impl Default for TOTP {
+ fn default() -> Self {
+ return TOTP::new(Algorithm::SHA1, 6, 1, 30, Secret::generate_secret().to_bytes().unwrap(), None, "".to_string()).unwrap()
+ }
+}
+
impl<T: AsRef<[u8]>> TOTP<T> {
+
+ #[cfg(feature = "otpauth")]
/// Will create a new instance of TOTP with given parameters. See [the doc](struct.TOTP.html#fields) for reference as to how to choose those values
///
/// # Description
@@ -210,6 +230,35 @@ impl<T: AsRef<[u8]>> TOTP<T> {
})
}
+ #[cfg(not(feature = "otpauth"))]
+ /// Will create a new instance of TOTP with given parameters. See [the doc](struct.TOTP.html#fields) for reference as to how to choose those values
+ ///
+ /// # Description
+ /// * `secret`: expect a non-encoded value, to pass in base32 string use `Secret::Encoded(String)`
+ ///
+ /// ```rust
+ /// use totp_rs::{Secret, TOTP, Algorithm};
+ /// let secret = Secret::Encoded("OBWGC2LOFVZXI4TJNZTS243FMNZGK5BNGEZDG".to_string());
+ /// let totp = TOTP::new(Algorithm::SHA1, 6, 1, 30, secret.to_bytes().unwrap()).unwrap();
+ /// ```
+ /// * `digits`: MUST be between 6 & 8
+ /// * `secret`: Must have bitsize of at least 128
+ ///
+ /// # Errors
+ ///
+ /// Will return an error in case issuer or label contain the character ':'
+ pub fn new(algorithm: Algorithm, digits: usize,skew: u8, step: u64, secret: T) -> Result<TOTP<T>, TotpUrlError> {
+ crate::rfc::assert_digits(&digits)?;
+ crate::rfc::assert_secret_length(secret.as_ref())?;
+ Ok(TOTP {
+ algorithm,
+ digits,
+ skew,
+ step,
+ secret,
+ })
+ }
+
/// Will create a new instance of TOTP from the given [Rfc6238](struct.Rfc6238.html) struct
///
/// # Errors
@@ -462,6 +511,17 @@ mod tests {
use super::*;
#[test]
+ #[cfg(feature = "gen_secret")]
+ fn default_values() {
+ let totp = TOTP::default();
+ assert_eq!(totp.algorithm, Algorithm::SHA1);
+ assert_eq!(totp.digits, 6);
+ assert_eq!(totp.skew, 1);
+ assert_eq!(totp.step, 30)
+ }
+
+ #[test]
+ #[cfg(feature = "otpauth")]
fn new_wrong_issuer() {
let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github:".to_string()), "constantoine@github.com".to_string());
assert!(totp.is_err());
@@ -469,6 +529,7 @@ mod tests {
}
#[test]
+ #[cfg(feature = "otpauth")]
fn new_wrong_account_name() {
let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine:github.com".to_string());
assert!(totp.is_err());
@@ -476,6 +537,7 @@ mod tests {
}
#[test]
+ #[cfg(feature = "otpauth")]
fn new_wrong_account_name_no_issuer() {
let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", None, "constantoine:github.com".to_string());
assert!(totp.is_err());
@@ -483,6 +545,7 @@ mod tests {
}
#[test]
+ #[cfg(feature = "otpauth")]
fn comparison_ok() {
let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
let test = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
@@ -490,37 +553,42 @@ mod tests {
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn comparison_different_algo() {
- let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
- let test = TOTP::new(Algorithm::SHA256, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret").unwrap();
+ let test = TOTP::new(Algorithm::SHA256, 6, 1, 1, "TestSecretSuperSecret").unwrap();
assert_ne!(reference, test);
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn comparison_different_digits() {
- let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
- let test = TOTP::new(Algorithm::SHA1, 8, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret").unwrap();
+ let test = TOTP::new(Algorithm::SHA1, 8, 1, 1, "TestSecretSuperSecret").unwrap();
assert_ne!(reference, test);
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn comparison_different_skew() {
- let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
- let test = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret").unwrap();
+ let test = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecretSuperSecret").unwrap();
assert_ne!(reference, test);
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn comparison_different_step() {
- let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
- let test = TOTP::new(Algorithm::SHA1, 6, 1, 30, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret").unwrap();
+ let test = TOTP::new(Algorithm::SHA1, 6, 1, 30, "TestSecretSuperSecret").unwrap();
assert_ne!(reference, test);
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn comparison_different_secret() {
- let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
- let test = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretDifferentSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret").unwrap();
+ let test = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretDifferentSecret").unwrap();
assert_ne!(reference, test);
}
@@ -557,20 +625,23 @@ mod tests {
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn returns_base32() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret").unwrap();
assert_eq!(totp.get_secret_base32().as_str(), "KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ");
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn generate_token() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret").unwrap();
assert_eq!(totp.generate(1000).as_str(), "659761");
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn generate_token_current() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret").unwrap();
let time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH).unwrap()
.as_secs();
@@ -578,49 +649,56 @@ mod tests {
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn generates_token_sha256() {
- let totp = TOTP::new(Algorithm::SHA256, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let totp = TOTP::new(Algorithm::SHA256, 6, 1, 1, "TestSecretSuperSecret").unwrap();
assert_eq!(totp.generate(1000).as_str(), "076417");
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn generates_token_sha512() {
- let totp = TOTP::new(Algorithm::SHA512, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let totp = TOTP::new(Algorithm::SHA512, 6, 1, 1, "TestSecretSuperSecret").unwrap();
assert_eq!(totp.generate(1000).as_str(), "473536");
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn checks_token() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let totp = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecretSuperSecret").unwrap();
assert!(totp.check("659761", 1000));
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn checks_token_current() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let totp = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecretSuperSecret").unwrap();
assert!(totp.check_current(&totp.generate_current().unwrap()).unwrap());
assert!(!totp.check_current("bogus").unwrap());
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn checks_token_with_skew() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretSuperSecret").unwrap();
assert!(
totp.check("174269", 1000) && totp.check("659761", 1000) && totp.check("260393", 1000)
);
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn next_step() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 30, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 30, "TestSecretSuperSecret").unwrap();
assert!(totp.next_step(0) == 30);
assert!(totp.next_step(29) == 30);
assert!(totp.next_step(30) == 60);
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn next_step_current() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 30, "TestSecretSuperSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 30, "TestSecretSuperSecret").unwrap();
let t = system_time().unwrap();
assert!(totp.next_step_current().unwrap() == totp.next_step(t));
}
@@ -689,7 +767,7 @@ mod tests {
#[test]
#[cfg(feature = "otpauth")]
fn from_url_query_different_issuers() {
- let totp = TOTP::<Vec<u8>>::from_url("otpauth://totp/GitHub:test?issuer=Gitlab&secret=TestSecretSuperSecret&digits=8&period=60&algorithm=SHA256");
+ let totp = TOTP::<Vec<u8>>::from_url("otpauth://totp/GitHub:test?issuer=Gitlab&secret=KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ&digits=8&period=60&algorithm=SHA256");
assert!(totp.is_err());
assert!(matches!(totp.unwrap_err(), TotpUrlError::IssuerMistmatch(_, _)));
}
diff --git a/src/rfc.rs b/src/rfc.rs
index 808a1e2..f5f763c 100644
--- a/src/rfc.rs
+++ b/src/rfc.rs
@@ -59,8 +59,6 @@ pub fn assert_secret_length(secret: &[u8]) -> Result<(), Rfc6238Error> {
///
/// // optional, set digits, issuer, account_name
/// rfc.digits(8).unwrap();
-/// rfc.issuer("issuer".to_string());
-/// rfc.account_name("user-account".to_string());
///
/// let totp = TOTP::from_rfc6238(rfc).unwrap();
/// ```
@@ -77,10 +75,12 @@ pub struct Rfc6238<T = Vec<u8>> {
step: u64,
/// As per [rfc-4226](https://tools.ietf.org/html/rfc4226#section-4) the secret should come from a strong source, most likely a CSPRNG. It should be at least 128 bits, but 160 are recommended
secret: T,
+ #[cfg(feature = "otpauth")]
/// The "Github" part of "Github:constantoine@github.com". Must not contain a colon `:`
/// For example, the name of your service/website.
/// Not mandatory, but strongly recommended!
issuer: Option<String>,
+ #[cfg(feature = "otpauth")]
/// The "constantoine@github.com" part of "Github:constantoine@github.com". Must not contain a colon `:`
/// For example, the name of your user's account.
account_name: String,
@@ -94,6 +94,7 @@ impl<T: AsRef<[u8]>> Rfc6238<T> {
/// will return a [Rfc6238Error](enum.Rfc6238Error.html) when
/// - `digits` is lower than 6 or higher than 8
/// - `secret` is smaller than 128 bits (16 characters)
+ #[cfg(feature = "otpauth")]
pub fn new(
digits: usize,
secret: T,
@@ -113,6 +114,22 @@ impl<T: AsRef<[u8]>> Rfc6238<T> {
account_name,
})
}
+ #[cfg(not(feature = "otpauth"))]
+ pub fn new(
+ digits: usize,
+ secret: T,
+ ) -> Result<Rfc6238<T>, Rfc6238Error> {
+ assert_digits(&digits)?;
+ assert_secret_length(secret.as_ref())?;
+
+ Ok(Rfc6238 {
+ algorithm: Algorithm::SHA1,
+ digits,
+ skew: 1,
+ step: 30,
+ secret,
+ })
+ }
/// Create an [rfc-6238](https://tools.ietf.org/html/rfc6238) compliant set of options that can be turned into a [TOTP](struct.TOTP.html),
/// with a default value of 6 for `digits`, None `issuer` and an empty account
@@ -122,8 +139,14 @@ impl<T: AsRef<[u8]>> Rfc6238<T> {
/// will return a [Rfc6238Error](enum.Rfc6238Error.html) when
/// - `digits` is lower than 6 or higher than 8
/// - `secret` is smaller than 128 bits (16 characters)
+ #[cfg(feature = "otpauth")]
pub fn with_defaults(secret: T) -> Result<Rfc6238<T>, Rfc6238Error> {
- Rfc6238::new(6, secret, None, "".to_string())
+ Rfc6238::new(6, secret, Some("".to_string()), "".to_string())
+ }
+
+ #[cfg(not(feature = "otpauth"))]
+ pub fn with_defaults(secret: T) -> Result<Rfc6238<T>, Rfc6238Error> {
+ Rfc6238::new(6, secret)
}
/// Set the `digits`
@@ -133,17 +156,36 @@ impl<T: AsRef<[u8]>> Rfc6238<T> {
Ok(())
}
+ #[cfg(feature = "otpauth")]
/// Set the `issuer`
pub fn issuer(&mut self, value: String) {
self.issuer = Some(value);
}
- /// Seet the `account_name`
+ #[cfg(feature = "otpauth")]
+ /// Set the `account_name`
pub fn account_name(&mut self, value: String) {
self.account_name = value;
}
}
+#[cfg(not(feature = "otpauth"))]
+impl<T: AsRef<[u8]>> TryFrom<Rfc6238<T>> for TOTP<T> {
+ type Error = TotpUrlError;
+
+ /// Try to create a [TOTP](struct.TOTP.html) from a [Rfc6238](struct.Rfc6238.html) config
+ fn try_from(rfc: Rfc6238<T>) -> Result<Self, Self::Error> {
+ TOTP::new(
+ rfc.algorithm,
+ rfc.digits,
+ rfc.skew,
+ rfc.step,
+ rfc.secret,
+ )
+ }
+}
+
+#[cfg(feature = "otpauth")]
impl<T: AsRef<[u8]>> TryFrom<Rfc6238<T>> for TOTP<T> {
type Error = TotpUrlError;
@@ -156,30 +198,39 @@ impl<T: AsRef<[u8]>> TryFrom<Rfc6238<T>> for TOTP<T> {
rfc.step,
rfc.secret,
rfc.issuer,
- rfc.account_name,
+ rfc.account_name
)
}
}
#[cfg(test)]
mod tests {
+ #[cfg(feature = "otpauth")]
use crate::TotpUrlError;
- use super::{Rfc6238, Rfc6238Error, TOTP};
+ use super::{Rfc6238, TOTP};
+
+ #[cfg(not(feature = "otpauth"))]
+ use super::Rfc6238Error;
+
+ #[cfg(not(feature = "otpauth"))]
+ use crate::Secret;
const GOOD_SECRET: &str = "01234567890123456789";
+ #[cfg(feature = "otpauth")]
const ISSUER: Option<&str> = None;
+ #[cfg(feature = "otpauth")]
const ACCOUNT: &str = "valid-account";
+ #[cfg(feature = "otpauth")]
const INVALID_ACCOUNT: &str = ":invalid-account";
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn new_rfc_digits() {
for x in 0..=20 {
let rfc = Rfc6238::new(
x,
GOOD_SECRET.to_string(),
- ISSUER.map(str::to_string),
- ACCOUNT.to_string(),
);
if !(6..=8).contains(&x) {
assert!(rfc.is_err());
@@ -191,6 +242,7 @@ mod tests {
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn new_rfc_secret() {
let mut secret = String::from("");
for _ in 0..=20 {
@@ -198,8 +250,6 @@ mod tests {
let rfc = Rfc6238::new(
6,
secret.clone(),
- ISSUER.map(str::to_string),
- ACCOUNT.to_string(),
);
let rfc_default = Rfc6238::with_defaults(secret.clone());
if secret.len() < 16 {
@@ -215,12 +265,11 @@ mod tests {
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
fn rfc_to_totp_ok() {
let rfc = Rfc6238::new(
8,
GOOD_SECRET.to_string(),
- ISSUER.map(str::to_string),
- ACCOUNT.to_string(),
)
.unwrap();
let totp = TOTP::try_from(rfc);
@@ -228,14 +277,29 @@ mod tests {
let otp = totp.unwrap();
assert_eq!(&otp.secret, GOOD_SECRET);
assert_eq!(otp.algorithm, crate::Algorithm::SHA1);
- assert_eq!(&otp.account_name, ACCOUNT);
assert_eq!(otp.digits, 8);
- assert_eq!(otp.issuer, ISSUER.map(str::to_string));
assert_eq!(otp.skew, 1);
assert_eq!(otp.step, 30)
}
#[test]
+ #[cfg(not(feature = "otpauth"))]
+ fn rfc_to_totp_ok_2() {
+ let rfc = Rfc6238::with_defaults(
+ Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()).to_bytes().unwrap(),
+ )
+ .unwrap();
+ let totp = TOTP::try_from(rfc);
+ assert!(totp.is_ok());
+ let otp = totp.unwrap();
+ assert_eq!(otp.algorithm, crate::Algorithm::SHA1);
+ assert_eq!(otp.digits, 6);
+ assert_eq!(otp.skew, 1);
+ assert_eq!(otp.step, 30)
+ }
+
+ #[test]
+ #[cfg(feature = "otpauth")]
fn rfc_to_totp_fail() {
let rfc = Rfc6238::new(
8,
@@ -250,14 +314,23 @@ mod tests {
}
#[test]
+ #[cfg(feature = "otpauth")]
+ fn rfc_to_totp_ok() {
+ let rfc = Rfc6238::new(
+ 8,
+ GOOD_SECRET.to_string(),
+ ISSUER.map(str::to_string),
+ ACCOUNT.to_string(),
+ )
+ .unwrap();
+ let totp = TOTP::try_from(rfc);
+ assert!(!totp.is_err());
+ }
+
+ #[test]
+ #[cfg(not(feature = "otpauth"))]
fn rfc_with_default_set_values() {
- let new_account = "new-account";
- let new_issuer = String::from("new-issuer");
let mut rfc = Rfc6238::with_defaults(GOOD_SECRET.to_string()).unwrap();
- rfc.issuer(new_issuer.clone());
- assert_eq!(rfc.issuer, Some(new_issuer));
- rfc.account_name(new_account.to_string());
- assert_eq!(rfc.account_name, new_account.to_string());
let fail = rfc.digits(4);
assert!(fail.is_err());
assert!(matches!(fail.unwrap_err(), Rfc6238Error::InvalidDigits(_)));
diff --git a/src/secret.rs b/src/secret.rs
index 5bf517b..68ba340 100644
--- a/src/secret.rs
+++ b/src/secret.rs
@@ -1,3 +1,82 @@
+//! Representation of a secret either a "raw" \[u8\] or "base 32" encoded String
+//!
+//! # Examples
+//!
+//! - Create a TOTP from a "raw" secret
+//! ```
+//! # #[cfg(not(feature = "otpauth"))] {
+//! use totp_rs::{Secret, TOTP, Algorithm};
+//!
+//! let secret = [
+//! 0x70, 0x6c, 0x61, 0x69, 0x6e, 0x2d, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x2d, 0x73, 0x65,
+//! 0x63, 0x72, 0x65, 0x74, 0x2d, 0x31, 0x32, 0x33,
+//! ];
+//! let secret_raw = Secret::Raw(secret.to_vec());
+//! let totp_raw = TOTP::new(
+//! Algorithm::SHA1,
+//! 6,
+//! 1,
+//! 30,
+//! secret_raw.to_bytes().unwrap(),
+//! ).unwrap();
+//!
+//! println!("code from raw secret:\t{}", totp_raw.generate_current().unwrap());
+//! # }
+//! ```
+//!
+//! - Create a TOTP from a base32 encoded secret
+//! ```
+//! # #[cfg(not(feature = "otpauth"))] {
+//! use totp_rs::{Secret, TOTP, Algorithm};
+//!
+//! let secret_b32 = Secret::Encoded(String::from("OBWGC2LOFVZXI4TJNZTS243FMNZGK5BNGEZDG"));
+//! let totp_b32 = TOTP::new(
+//! Algorithm::SHA1,
+//! 6,
+//! 1,
+//! 30,
+//! secret_b32.to_bytes().unwrap(),
+//! ).unwrap();
+//!
+//! println!("code from base32:\t{}", totp_b32.generate_current().unwrap());
+//! # }
+//!
+//! ```
+//! - Create a TOTP from a Generated Secret
+//! ```
+//! # #[cfg(all(feature = "gen_secret", not(feature = "otpauth")))] {
+//! use totp_rs::{Secret, TOTP, Algorithm};
+//!
+//! let secret_b32 = Secret::default();
+//! let totp_b32 = TOTP::new(
+//! Algorithm::SHA1,
+//! 6,
+//! 1,
+//! 30,
+//! secret_b32.to_bytes().unwrap(),
+//! ).unwrap();
+//!
+//! println!("code from base32:\t{}", totp_b32.generate_current().unwrap());
+//! # }
+//! ```
+//! - Create a TOTP from a Generated Secret 2
+//! ```
+//! # #[cfg(all(feature = "gen_secret", not(feature = "otpauth")))] {
+//! use totp_rs::{Secret, TOTP, Algorithm};
+//!
+//! let secret_b32 = Secret::generate_secret();
+//! let totp_b32 = TOTP::new(
+//! Algorithm::SHA1,
+//! 6,
+//! 1,
+//! 30,
+//! secret_b32.to_bytes().unwrap(),
+//! ).unwrap();
+//!
+//! println!("code from base32:\t{}", totp_b32.generate_current().unwrap());
+//! # }
+//! ```
+
use std::string::FromUtf8Error;
use base32::{self, Alphabet};
@@ -7,49 +86,6 @@ pub enum SecretParseError {
Utf8Error(FromUtf8Error),
}
-/// Representation of a secret either a "raw" \[u8\] or "base 32" encoded String
-///
-/// # Examples
-///
-/// - Create a TOTP from a "raw" secret
-/// ```
-/// use totp_rs::{Secret, TOTP, Algorithm};
-///
-/// let secret = [
-/// 0x70, 0x6c, 0x61, 0x69, 0x6e, 0x2d, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x2d, 0x73, 0x65,
-/// 0x63, 0x72, 0x65, 0x74, 0x2d, 0x31, 0x32, 0x33,
-/// ];
-/// let secret_raw = Secret::Raw(secret.to_vec());
-/// let totp_raw = TOTP::new(
-/// Algorithm::SHA1,
-/// 6,
-/// 1,
-/// 30,
-/// secret_raw.to_bytes().unwrap(),
-/// None,
-/// "account".to_string(),
-/// ).unwrap();
-///
-/// println!("code from raw secret:\t{}", totp_raw.generate_current().unwrap());
-/// ```
-///
-/// - Create a TOTP from a base32 encoded secret
-/// ```
-/// use totp_rs::{Secret, TOTP, Algorithm};
-///
-/// let secret_b32 = Secret::Encoded(String::from("OBWGC2LOFVZXI4TJNZTS243FMNZGK5BNGEZDG"));
-/// let totp_b32 = TOTP::new(
-/// Algorithm::SHA1,
-/// 6,
-/// 1,
-/// 30,
-/// secret_b32.to_bytes().unwrap(),
-/// None,
-/// "account".to_string(),
-/// ).unwrap();
-///
-/// println!("code from base32:\t{}", totp_b32.generate_current().unwrap());
-/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Secret {
/// represent a non-encoded "raw" secret
@@ -58,6 +94,13 @@ pub enum Secret {
Encoded(String),
}
+#[cfg(feature = "gen_secret")]
+impl Default for Secret {
+ fn default() -> Self {
+ return Secret::generate_secret()
+ }
+}
+
impl Secret {
/// Get the inner String value as a Vec of bytes
@@ -87,7 +130,7 @@ impl Secret {
match self {
Secret::Raw(s) => Secret::Encoded(base32::encode(
Alphabet::RFC4648 { padding: false },
- &s,
+ s,
)),
Secret::Encoded(_) => self.clone(),
}
@@ -108,7 +151,7 @@ impl Secret {
let mut rng = rand::thread_rng();
let mut secret: [u8; 20] = Default::default();
- rng.fill(&mut secret);
+ rng.fill(&mut secret[..]);
Secret::Raw(secret.to_vec())
}
}
@@ -143,7 +186,7 @@ mod tests {
fn secret_display() {
let base32_str = String::from(BASE32);
let secret_raw = Secret::Raw(BYTES.to_vec());
- let secret_base32 = Secret::Encoded(base32_str.clone());
+ let secret_base32 = Secret::Encoded(base32_str);
println!("{}", secret_raw);
assert_eq!(secret_raw.to_string(), BYTES_DISPLAY.to_string());
assert_eq!(secret_base32.to_string(), BASE32.to_string());
@@ -153,7 +196,7 @@ mod tests {
fn secret_convert_base32_raw() {
let base32_str = String::from(BASE32);
let secret_raw = Secret::Raw(BYTES.to_vec());
- let secret_base32 = Secret::Encoded(base32_str.clone());
+ let secret_base32 = Secret::Encoded(base32_str);
assert_eq!(&secret_raw.to_encoded(), &secret_base32);
assert_eq!(&secret_raw.to_raw().unwrap(), &secret_raw);
@@ -170,6 +213,14 @@ mod tests {
}
#[test]
+ fn secret_from_string() {
+ let raw: Secret = Secret::Raw("TestSecretSuperSecret".as_bytes().to_vec());
+ let encoded: Secret = Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string());
+ assert_eq!(raw.to_encoded(), encoded);
+ assert_eq!(raw, encoded.to_raw().unwrap());
+ }
+
+ #[test]
#[cfg(feature = "gen_secret")]
fn secret_gen_secret() {
match Secret::generate_secret() {