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
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
#![no_std]
extern crate no_std_compat as std;
extern crate alloc;

use std::prelude::v1::*;

#[cfg(feature = "certificates")]
pub mod certificates;

#[cfg(feature = "certificates_custom")]
pub mod certificates_custom;

#[cfg(feature = "certificates_custom")]
mod x509_cert;

#[cfg(any(feature = "auth_verify", feature = "diffie_hellman_key_store", feature = "diffie_hellman_client_server_key_store"))]
use std::collections::BTreeMap;

#[cfg(any(feature = "hash", feature = "hasher", feature = "mac"))]
use blake2::digest::{ Mac, FixedOutput, Digest };


#[cfg(feature = "public_private_sign_verify")]
use ring::{
    signature::KeyPair
};

#[cfg(feature = "password_hash")]
use argon2::{
    password_hash::{ PasswordHasher, PasswordVerifier }
};

#[cfg(any(feature = "generator", feature = "symmetric_encrypt_decrypt"))]
pub use product_os_random::{ RandomGenerator, RandomGeneratorTemplate };

#[cfg(feature = "jwt_encrypt_decrypt")]
use base64::{ Engine as _, engine::general_purpose as base64GP };

#[cfg(feature = "jwt_auth_verify")]
use jwt_compact::{ prelude::*, alg::{ Hs256, Hs256Key } };

#[cfg(feature = "jwt_auth_verify")]
use serde::{Serialize, Deserialize};

#[cfg(feature = "default")]
use product_os_random::SeedableRng;



#[cfg(any(feature = "auth_verify", feature = "byte_vector"))]
pub trait AsByteVector {
    fn as_byte_vector(&self) -> Vec<u8>;
}

#[cfg(any(feature = "auth_verify", feature = "byte_vector"))]
impl AsByteVector for serde_json::Value {
    fn as_byte_vector(&self) -> Vec<u8> {
        self.to_string().into_bytes()
    }
}

#[cfg(feature = "auth_verify")]
pub fn create_auth_request<T>(query: Option<&BTreeMap<String, String>>, encoded: bool, payload: Option<T>,
                              headers: Option<&BTreeMap<String, String>>, exclude_headers: &[&str], key: Option<&[u8]>) -> String
where T: AsByteVector
{
    let mut representation: Vec<u8> = vec!();

    match query {
        Some(q) => representation.extend_from_slice(create_auth_query(q, encoded, key).as_bytes()),
        None => ()
    }

    match headers {
        Some(h) => representation.extend_from_slice(create_auth_headers(h, exclude_headers, key).as_bytes()),
        None => ()
    }

    match payload {
        Some(p) => representation.extend_from_slice(create_auth_payload(p, key).as_slice()),
        None => ()
    }

    hex_encode(create_auth(representation.as_slice(), key, None))
}

#[cfg(feature = "auth_verify")]
pub fn verify_auth_request<T>(query: Option<&BTreeMap<String, String>>, encoded: bool, payload: Option<T>,
                           headers: Option<&BTreeMap<String, String>>, exclude_headers: &[&str], tag: String, key: Option<&[u8]>) -> bool
where T: AsByteVector
{
    let auth = create_auth_request(query, encoded, payload, headers, exclude_headers, key);
    auth == tag
}

#[cfg(feature = "auth_verify")]
pub fn create_auth_request_json(query: Option<&BTreeMap<String, String>>, encoded: bool, json: Option<&serde_json::Value>,
                              headers: Option<&BTreeMap<String, String>>, exclude_headers: &[&str], key: Option<&[u8]>) -> String
{
    let mut representation: Vec<u8> = vec!();

    match query {
        Some(q) => representation.extend_from_slice(create_auth_query(q, encoded, key).as_bytes()),
        None => ()
    }

    match headers {
        Some(h) => representation.extend_from_slice(create_auth_headers(h, exclude_headers, key).as_bytes()),
        None => ()
    }

    match json {
        Some(v) => representation.extend_from_slice(create_auth_json(&v, key).as_slice()),
        None => ()
    }

    hex_encode(create_auth(representation.as_slice(), key, None))
}

#[cfg(feature = "auth_verify")]
pub fn verify_auth_request_json(query: Option<&BTreeMap<String, String>>, encoded: bool, json: Option<&serde_json::Value>,
                              headers: Option<&BTreeMap<String, String>>, exclude_headers: &[&str], tag: String, key: Option<&[u8]>) -> bool
{
    let auth = create_auth_request_json(query, encoded, json, headers, exclude_headers, key);
    auth == tag
}


#[cfg(feature = "auth_verify")]
pub fn create_auth_query(query: &BTreeMap<String, String>, encoded: bool, key: Option<&[u8]>) -> String {
    let mut representation: Vec<u8> = vec!();

    for (key, value) in query {

        if encoded {
            representation.extend_from_slice(product_os_urlencoding::decode(key.as_str()).unwrap().to_string().as_bytes());
            representation.extend_from_slice(product_os_urlencoding::decode(value.as_str()).unwrap().to_string().as_bytes());
        }
        else {
            representation.extend_from_slice(key.as_bytes());
            representation.extend_from_slice(value.as_bytes());
        }
    }

    hex_encode(create_auth(representation.as_slice(), key, None))
}

#[cfg(feature = "auth_verify")]
pub fn verify_auth_query(query: &BTreeMap<String, String>, encoded: bool, tag: String, key: Option<&[u8]>) -> bool
{
    let auth = create_auth_query(query, encoded, key);
    auth == tag
}

#[cfg(feature = "auth_verify")]
pub fn create_auth_headers(headers: &BTreeMap<String, String>, exclude_headers: &[&str], key: Option<&[u8]>) -> String {
    let mut representation: Vec<u8> = vec!();

    for (key, value) in headers {
        if !exclude_headers.contains(&key.as_str()) {
            representation.extend_from_slice(key.as_bytes());
            representation.extend_from_slice(value.as_bytes());
        }
    }

    hex_encode(create_auth(representation.as_slice(), key, None))
}

#[cfg(feature = "auth_verify")]
pub fn verify_auth_headers(headers: &BTreeMap<String, String>, encoded: bool, tag: String, key: Option<&[u8]>) -> bool
{
    let auth = create_auth_query(headers, encoded, key);
    auth == tag
}

#[cfg(feature = "auth_verify")]
pub fn create_auth_payload<T>(payload: T, key: Option<&[u8]>) -> Vec<u8>
where T: AsByteVector
{
    let byte_representation = payload.as_byte_vector();
    create_auth(byte_representation.as_slice(), key, None)
}

#[cfg(feature = "auth_verify")]
pub fn verify_auth_payload<T>(payload: T, tag: &[u8], key: Option<&[u8]>) -> bool
    where T: AsByteVector
{
    let auth = create_auth_payload(payload, key);
    verify_auth(auth, tag, key, None)
}

#[cfg(feature = "auth_verify")]
pub fn create_auth_json(json: &serde_json::Value, key: Option<&[u8]>) -> Vec<u8>
{
    let byte_representation = json.to_string();
    create_auth(byte_representation.as_bytes(), key, None)
}

#[cfg(feature = "auth_verify")]
pub fn verify_auth_json(json: &serde_json::Value, tag: &[u8], key: Option<&[u8]>) -> bool
{
    let auth = create_auth_json(json, key);
    verify_auth(auth, tag, key, None)
}



#[cfg(feature = "auth_verify")]
pub fn create_auth(data: &[u8], key: Option<&[u8]>, algorithm: Option<&str>) -> Vec<u8> {
    match key {
        Some(k) => {
            if k.len() == 0 { return Vec::from([]); } // Bad key length
            match algorithm {
                Some(alg) => {
                    match alg {
                        // "jwt" => { jwt_auth(data, k).into_bytes() },
                        "blake2" => blake2_mac(data, k),
                        _ => blake2_mac(data, k)
                    }
                },
                None => blake2_mac(data, k)
            }
        },
        None => {
            match algorithm {
                Some(alg) => {
                    match alg {
                        "blake2" => blake2_hash(data),
                        _ => blake2_hash(data)
                    }
                },
                None => blake2_hash(data)
            }
        }
    }
}


#[cfg(feature = "auth_verify")]
pub fn verify_auth(data: Vec<u8>, tag: &[u8], key: Option<&[u8]>, algorithm: Option<&str>) -> bool {
    match key {
        Some(k) => {
            if k.len() == 0 { return false; } // Bad key length
            match algorithm {
                Some(alg) => {
                    match alg {
                        "blake2" => blake2_verify_mac(data, tag, k),
                        _ => blake2_verify_mac(data, tag, k)
                    }
                },
                None => blake2_verify_mac(data, tag, k)
            }
        },
        None => {
            match algorithm {
                Some(alg) => {
                    match alg {
                        "blake2" => blake2_hash(data.as_slice()).as_slice() == tag,
                        _ => blake2_hash(data.as_slice()).as_slice() == tag
                    }
                },
                None => blake2_hash(data.as_slice()).as_slice() == tag
            }
        }
    }
}


#[cfg(feature = "hash")]
pub fn create_salted_hash(data: &[u8], generator: &mut RandomGenerator, algorithm: Option<&str>) -> (Vec<u8>, Vec<u8>) {
    let salt = generator.get_random_string(16).as_bytes().to_vec();
    let mut input = data.to_vec();
    input.append(&mut salt.to_vec());

    match algorithm {
        Some(alg) => {
            match alg {
                "paranoid_hash" => (create_string_hash(std::str::from_utf8(input.as_slice()).unwrap().to_string()).into_bytes(), salt),
                "blake2" => (blake2_hash(input.as_slice()), salt),
                _ => (blake2_hash(input.as_slice()), salt)
            }
        },
        None => (blake2_hash(input.as_slice()), salt)
    }
}


#[cfg(feature = "hash")]
pub fn create_hash(data: &[u8], algorithm: Option<&str>) -> Vec<u8> {
    match algorithm {
        Some(alg) => {
            match alg {
                "paranoid_hash" => create_string_hash(std::str::from_utf8(data).unwrap().to_string()).into_bytes(),
                "blake2" => blake2_hash(data),
                _ => blake2_hash(data)
            }
        },
        None => blake2_hash(data)
    }
}


#[cfg(feature = "hash")]
pub fn verify_hash(data: &[u8], original_hash: &[u8], stored_salt: Option<&[u8]>, algorithm: Option<&str>) -> bool {
    let mut input = data.to_vec();
    match stored_salt {
        None => (),
        Some(salt) => input.append(&mut salt.to_vec())
    }

    let hash = create_hash(input.as_slice(), algorithm);

    if hash.as_slice() == original_hash { true }
    else { false }
}



#[cfg(feature = "auth_verify")]
pub fn hex_encode(data: Vec<u8>) -> String {
    hex::encode(data)
}

#[cfg(feature = "auth_verify")]
pub fn hex_decode(value: String) -> Vec<u8> {
    hex::decode(value).unwrap()
}



#[cfg(feature = "jwt_encrypt_decrypt")]
pub fn base64_encode(data: Vec<u8>) -> String {
    base64GP::URL_SAFE_NO_PAD.encode(data)
}

#[cfg(feature = "jwt_encrypt_decrypt")]
pub fn base64_decode(value: String) -> Vec<u8> {
    match base64GP::URL_SAFE_NO_PAD.decode(value) {
        Ok(output) => output,
        Err(_) => vec![]
    }
}


#[cfg(feature = "hash")]
pub fn create_string_hash(data: String) -> String {
    let mut hasher = blake2::Blake2b512::new();

    hasher.update(data.as_bytes());
    let hash = hasher.finalize();
    String::from_utf8_lossy(&hash[..]).to_string()
}


#[cfg(feature = "hash")]
fn blake2_hash(data: &[u8]) -> Vec<u8> {
    let mut hasher = blake2::Blake2b512::new();

    hasher.update(data);
    let hash = hasher.finalize();
    hash[..].to_vec()
}


#[cfg(feature = "hasher")]
#[derive(Clone)]
pub struct ProductOSHasher {
    hasher: blake2::Blake2b<blake2::digest::typenum::U8>
}

#[cfg(feature = "hasher")]
impl ProductOSHasher {
    pub fn new() -> Self {
        Self {
            hasher: blake2::Blake2b::default()
        }
    }
}

#[cfg(feature = "hasher")]
impl std::hash::Hasher for ProductOSHasher {
    fn finish(&self) -> u64 {
        u64::from_be_bytes(self.hasher.clone().finalize().into())
    }

    fn write(&mut self, bytes: &[u8]) {
        self.hasher.update(bytes)
    }
}

#[cfg(feature = "hasher")]
impl std::hash::BuildHasher for ProductOSHasher {
    type Hasher = ProductOSHasher;

    fn build_hasher(&self) -> Self::Hasher {
        ProductOSHasher::default()
    }
}

#[cfg(feature = "hasher")]
impl Default for ProductOSHasher {
    fn default() -> Self {
        ProductOSHasher::new()
    }
}



#[cfg(feature = "mac")]
fn blake2_mac(data: &[u8], key: &[u8]) -> Vec<u8> {
    match blake2::Blake2bMac512::new_from_slice(key) {
        Ok(mut mac) => {
            mac.update(data);
            let hash = mac.finalize_fixed();
            hash.to_vec()
        },
        Err(e) => panic!("Invalid key length provided to blake2 auth: {}", e)
    }
}

#[cfg(feature = "mac")]
fn blake2_verify_mac(msg: Vec<u8>, tag: &[u8], key: &[u8]) -> bool {
    let auth = blake2_mac(msg.as_slice(), key);
    auth == tag
}




#[cfg(feature = "jwt_auth_verify")]
pub struct JWTGenerator {
    issuer: String,
    default_until: i64,
    default_audience: String,
    jti_length: usize,
    random_generator: RandomGenerator,
    time_generator: product_os_async_executor::moment::Moment
}

#[cfg(feature = "jwt_auth_verify")]
pub trait TokenClaims<'a, T>: Clone
{
    fn verify(&self, verify_map: T) -> bool;
}

#[cfg(feature = "jwt_auth_verify")]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct DefaultClaims {
    #[serde(rename = "iss")]
    issuer: String,
    #[serde(rename = "sub")]
    subject: String,
    #[serde(rename = "aud")]
    audience: String,
    #[serde(rename = "jti")]
    jwt_id: String
}


#[cfg(feature = "jwt_auth_verify")]
impl TokenClaims<'_, DefaultClaims> for DefaultClaims {
    fn verify(&self, verify_map: DefaultClaims) -> bool {
        self.issuer == verify_map.issuer && self.subject == verify_map.subject &&
            self.audience == verify_map.audience && self.jwt_id == verify_map.jwt_id
    }
}



#[cfg(feature = "jwt_auth_verify")]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct EmptyClaims {}

impl EmptyClaims {
    pub fn new() -> Self {
        EmptyClaims {}
    }
}

#[cfg(feature = "jwt_auth_verify")]
impl TokenClaims<'_, EmptyClaims> for EmptyClaims {
    fn verify(&self, verify_map: EmptyClaims) -> bool {
        true
    }
}



#[cfg(feature = "jwt_auth_verify")]
pub enum JWTError {
    InvalidSignature,
    InvalidKey,
    EncodeFailure,
    DecodeFailure,
    InvalidClaims,
    InvalidNonce
}

#[cfg(feature = "jwt_auth_verify")]
impl JWTGenerator where {
    pub fn new(gen: Option<product_os_random::RNG>, func: Option<fn() -> chrono::DateTime<chrono::Utc>>, issuer: String, default_until: i64, default_audience: String, jti_length: usize) -> Self {
        let time_gen = product_os_async_executor::moment::Moment::new(func);

        Self {
            issuer,
            default_until,
            default_audience,
            jti_length,
            random_generator: RandomGenerator::new(gen),
            time_generator: time_gen
        }
    }

    pub fn get_default_until(&self) -> &i64 {
        &self.default_until
    }

    pub fn get_default_audience(&self) -> String {
        self.default_audience.to_owned()
    }

    pub fn generate_default_claims(&self, subject: String, audience: Option<String>, jwt_id: String) -> DefaultClaims {
        let audience = match audience {
            Some(a) => a,
            None => self.default_audience.to_owned()
        };

        DefaultClaims {
            issuer: self.issuer.to_owned(),
            subject,
            audience,
            jwt_id
        }
    }

    /*
        iss (issuer): Issuer of the JWT
        sub (subject): Subject of the JWT (the user)
        aud (audience): Recipient for which the JWT is intended
        exp (expiration time): Time after which the JWT expires
        nbf (not before time): Time before which the JWT must not be accepted for processing
        iat (issued at time): Time at which the JWT was issued; can be used to determine age of the JWT
        jti (JWT ID): Unique identifier; can be used to prevent the JWT from being replayed (allows a token to be used only once)
    */
    pub fn jwt_auth<'a, T: TokenClaims<'a, T> + Serialize>(&mut self, subject: String, audience: Option<String>, until: Option<chrono::DateTime<chrono::Utc>>, custom_claims: Option<T>, custom_header: Option<Header>, jwt_secret: &[u8], encryption_key: Option<Vec<u8>>, gen: &mut Option<impl product_os_random::RngCore>) -> Result<(String, String), JWTError> {
        let header = match custom_header {
            None => jwt_compact::Header::empty(),
            Some(h) => h
        };

        let now = self.time_generator.now();

        let time_func = self.time_generator.get_function();
        let time_options = jwt_compact::TimeOptions::new(chrono::Duration::seconds(5), time_func);

        let until = match until {
            None => chrono::Duration::seconds(self.default_until.to_owned()),
            Some(u) => chrono::Duration::seconds(u.timestamp() - now.timestamp())
        };

        match encryption_key {
            None => {
                let jti = self.random_generator.get_random_string(self.jti_length.into());

                match custom_claims {
                    None => {
                        let claims = jwt_compact::Claims::new(self.generate_default_claims(subject, audience,jti.to_owned()))
                            .set_duration_and_issuance(&time_options, until)
                            .set_not_before(now);

                        let key = Hs256Key::new(jwt_secret);

                        match Hs256.token(&header, &claims, &key) {
                            Ok(jwt) => Ok((jwt, jti)),
                            Err(_) => Err(JWTError::EncodeFailure)
                        }
                    },
                    Some(custom) => {
                        let claims = jwt_compact::Claims::new(custom)
                            .set_duration_and_issuance(&time_options, until)
                            .set_not_before(now);

                        let key = Hs256Key::new(jwt_secret);

                        match Hs256.token(&header, &claims, &key) {
                            Ok(jwt) => Ok((jwt, jti)),
                            Err(_) => Err(JWTError::EncodeFailure)
                        }
                    }
                }
            },
            Some(enc_secret) => {
                #[cfg(feature = "jwt_encrypt_decrypt")]
                {
                    let nonce = {
                        #[cfg(feature = "jwt_encrypt_decrypt_std")] {
                            orion::hazardous::stream::xchacha20::Nonce::generate()
                        }
                        #[cfg(not(feature = "jwt_encrypt_decrypt_std"))] {
                            let bytes = product_os_random::RandomGenerator::get_random_bytes_one_time(24, gen);
                            orion::hazardous::aead::xchacha20poly1305::Nonce::from_slice(bytes.as_slice()).unwrap()
                        }
                    };
                    let jti = base64GP::URL_SAFE_NO_PAD.encode(nonce.to_owned());

                    match custom_claims {
                        None => {
                            let claims = jwt_compact::Claims::new(self.generate_default_claims(subject, audience, jti.to_owned()))
                                .set_duration_and_issuance(&time_options, until)
                                .set_not_before(now);

                            let key = Hs256Key::new(jwt_secret);

                            match Hs256.token(&header, &claims, &key) {
                                Ok(jwt) => {
                                    match orion::hazardous::aead::xchacha20poly1305::SecretKey::from_slice(enc_secret.as_slice()) {
                                        Ok(secret) => {
                                            let mut output = vec![];
                                            match orion::hazardous::aead::xchacha20poly1305::seal(&secret, &nonce, jwt.as_bytes(), None, &mut output) {
                                                Ok(_) => Ok((base64GP::URL_SAFE_NO_PAD.encode(output), jti)),
                                                Err(e) => panic!("Error encrypting value {}", e)
                                            }
                                        },
                                        Err(e) => panic!("Invalid key {}", e)
                                    }
                                }
                                Err(_) => Err(JWTError::EncodeFailure)
                            }
                        },
                        Some(custom) => {
                            let claims = jwt_compact::Claims::new(custom)
                                .set_duration_and_issuance(&time_options, until)
                                .set_not_before(now);

                            let key = Hs256Key::new(jwt_secret);

                            match Hs256.token(&header, &claims, &key) {
                                Ok(jwt) => {
                                    match orion::hazardous::aead::xchacha20poly1305::SecretKey::from_slice(enc_secret.as_slice()) {
                                        Ok(secret) => {
                                            let mut output = vec![];
                                            match orion::hazardous::aead::xchacha20poly1305::seal(&secret, &nonce, jwt.as_bytes(), None, &mut output) {
                                                Ok(_) => Ok((base64GP::URL_SAFE_NO_PAD.encode(output), jti)),
                                                Err(e) => panic!("Error encrypting value {}", e)
                                            }
                                        },
                                        Err(e) => panic!("Invalid key {}", e)
                                    }
                                }
                                Err(_) => Err(JWTError::EncodeFailure)
                            }
                        }
                    }
                }
                #[cfg(not(feature = "jwt_encrypt_decrypt"))]
                {
                    panic!("JWT Encryption not enabled - add feature jwt_encrypt_decrypt to product_os_security");
                }
            }
        }
    }

    #[cfg(feature = "jwt_auth_verify")]
    pub fn jwt_get_token_claims<'a, T: TokenClaims<'a, T> + serde::de::DeserializeOwned>(&self, token: String, jwt_secret: &[u8], nonce: &[u8], decryption_key: Option<Vec<u8>>) -> Result<(String, Token<T>), JWTError>
    {
        let token_string = match decryption_key {
            None => token,
            Some(dec_secret) => {
                #[cfg(feature = "jwt_encrypt_decrypt")]
                {
                    match base64GP::URL_SAFE_NO_PAD.decode(token) {
                        Ok(decoded) => {
                            match orion::hazardous::aead::xchacha20poly1305::SecretKey::from_slice(dec_secret.as_slice()) {
                                Ok(secret) => {
                                    match orion::hazardous::aead::xchacha20poly1305::Nonce::from_slice(nonce) {
                                        Ok(nonce) => {
                                            let mut output = vec![];
                                            match orion::hazardous::aead::xchacha20poly1305::open(&secret, &nonce, decoded.as_slice(), None, &mut output) {
                                                Ok(_) => match String::from_utf8(output) {
                                                    Ok(v) => v,
                                                    Err(_) => return Err(JWTError::InvalidSignature)
                                                },
                                                Err(_) => return Err(JWTError::InvalidSignature)
                                            }
                                        }
                                        Err(_) => return Err(JWTError::InvalidNonce)
                                    }
                                },
                                Err(_) => return Err(JWTError::InvalidKey)
                            }
                        }
                        Err(_) => return Err(JWTError::InvalidSignature)
                    }
                }
                #[cfg(not(feature = "jwt_encrypt_decrypt"))]
                {
                    panic!("JWT Decryption not enabled - add feature jwt_encrypt_decrypt to product_os_security");
                }
            }
        };

        let token = match jwt_compact::UntrustedToken::new(&token_string) {
            Ok(ut) => ut,
            Err(e) => return Err(JWTError::DecodeFailure)
        };

        let key = Hs256Key::new(jwt_secret);

        let token_claims: Token<T> = match Hs256.validator(&key).validate(&token) {
            Ok(claims) => claims,
            Err(_) => return Err(JWTError::InvalidSignature)
        };

        Ok((token_string, token_claims))
    }


    #[cfg(feature = "jwt_auth_verify")]
    pub fn jwt_verify_auth<'a, T: TokenClaims<'a, T> + serde::de::DeserializeOwned>(&self, verify_claims: T, token: String, jwt_secret: &[u8], nonce: &[u8], decryption_key: Option<Vec<u8>>) -> Result<(String, T), JWTError> {
        match self.jwt_get_token_claims::<T>(token, jwt_secret, nonce, decryption_key) {
            Ok((token_string, token_claims)) => {
                let time_func = self.time_generator.get_function();
                let time_options = jwt_compact::TimeOptions::new(chrono::Duration::seconds(5), time_func);

                let claims = token_claims.claims();

                match claims.validate_expiration(&time_options) {
                    Ok(_) => {}
                    Err(_) => return Err(JWTError::InvalidClaims)
                }

                match claims.validate_maturity(&time_options) {
                    Ok(_) => {}
                    Err(_) => return Err(JWTError::InvalidClaims)
                }

                let custom_claims: T = claims.custom.to_owned();

                match custom_claims.verify(verify_claims) {
                    true => Ok((token_string, custom_claims)),
                    false => return Err(JWTError::InvalidClaims)
                }
            }
            Err(e) => Err(e)
        }
    }
}


#[cfg(feature = "public_private_sign_verify")]
pub enum KeyError {
    KeyRejected(String),
}

#[cfg(feature = "public_private_sign_verify")]
pub fn generate_public_private_keys() -> Result<ring::pkcs8::Document, ring::error::Unspecified> {
    let rng = ring::rand::SystemRandom::new();
    ring::signature::Ed25519KeyPair::generate_pkcs8(&rng)
}

#[cfg(feature = "public_private_sign_verify")]
pub fn get_public_key(key_pair: ring::pkcs8::Document) -> Result<Vec<u8>, KeyError> {
    match ring::signature::Ed25519KeyPair::from_pkcs8(key_pair.as_ref()) {
        Ok(key_pair) => {
            Ok(key_pair.public_key().as_ref().to_vec())
        },
        Err(_) => Err(KeyError::KeyRejected(String::from("No public key found")))
    }
}

#[cfg(feature = "public_private_sign_verify")]
pub fn private_key_sign(key_pair: ring::pkcs8::Document, message: &[u8]) -> Result<ring::signature::Signature, KeyError> {
    match ring::signature::Ed25519KeyPair::from_pkcs8(key_pair.as_ref()) {
        Ok(key_pair) => Ok(key_pair.sign(message)),
        Err(_) => Err(KeyError::KeyRejected(String::from("Failed to sign with key")))
    }
}

#[cfg(feature = "public_private_sign_verify")]
pub fn public_key_verify(public_key_bytes: &[u8], signature: &[u8], message: &[u8]) -> bool {
    let peer_public_key = ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key_bytes);
    match peer_public_key.verify(message, signature) {
        Ok(_) => true,
        Err(_) => false
    }
}



#[cfg(feature = "symmetric_encrypt_decrypt")]
pub enum CryptoError {
    Unknown(String),
}

#[cfg(feature = "symmetric_encrypt_decrypt")]
pub fn symmetric_encrypt(key: &[u8], message: &[u8], gen: &mut Option<impl product_os_random::RngCore>) -> Result<(Vec<u8>, Vec<u8>), CryptoError> {
    match orion::hazardous::aead::xchacha20poly1305::SecretKey::from_slice(key) {
        Ok(secret) => {
            let nonce = {
                #[cfg(feature = "jwt_encrypt_decrypt_std")] {
                    orion::hazardous::stream::xchacha20::Nonce::generate()
                }
                #[cfg(not(feature = "jwt_encrypt_decrypt_std"))] {
                    let bytes = product_os_random::RandomGenerator::get_random_bytes_one_time(24, gen);
                    orion::hazardous::aead::xchacha20poly1305::Nonce::from_slice(bytes.as_slice()).unwrap()
                }
            };
            let mut output = vec![];
            match orion::hazardous::aead::xchacha20poly1305::seal(&secret, &nonce, message, None, &mut output) {
                Ok(_) => Ok((output, nonce.as_ref().to_vec())),
                Err(e) => Err(CryptoError::Unknown(e.to_string()))
            }
        },
        Err(e) => panic!("Invalid key {}", e)
    }
}

#[cfg(feature = "symmetric_encrypt_decrypt")]
pub fn symmetric_decrypt(key: &[u8], nonce: &[u8], cipher: &[u8]) -> Result<Vec<u8>, CryptoError> {
    match orion::hazardous::aead::xchacha20poly1305::SecretKey::from_slice(key) {
        Ok(secret) => {
            match orion::hazardous::aead::xchacha20poly1305::Nonce::from_slice(nonce) {
                Ok(nonce) => {
                    let mut output = vec![];
                    match orion::hazardous::aead::xchacha20poly1305::open(&secret, &nonce,cipher, None, &mut output) {
                        Ok(_) => Ok(output),
                        Err(e) => Err(CryptoError::Unknown(e.to_string()))
                    }
                }
                Err(e) => Err(CryptoError::Unknown(e.to_string()))
            }
        },
        Err(e) => panic!("Invalid key {}", e)
    }
}



#[cfg(feature = "public_private_encrypt_decrypt")]
pub struct RSA {
    bit_count: usize,
    private_key: Vec<u8>,
    public_key: Vec<u8>,
    rng: product_os_random::ThreadRng
}


#[cfg(feature = "public_private_encrypt_decrypt")]
impl RSA {
    pub fn new() -> Self {
        let bit_count = 2048;

        let rng = product_os_random::thread_rng();
        let private_key = vec!();

        let public_key = vec!();

        Self {
            bit_count,
            private_key,
            public_key,
            rng,
        }
    }

    fn generate_keys(&self) -> (Vec<u8>, Vec<u8>) {
        let private_key = vec!();

        let public_key = vec!();

        (private_key, public_key)
    }

    pub fn generate_new_keys(&mut self) -> Vec<u8> {
        todo!()
    }

    pub fn get_public_key(&self) -> Vec<u8> {
        todo!()
    }

    pub fn import_public_key(&mut self, public_key: &[u8]) {
        todo!()
    }

    pub fn self_encrypt(&self, data: &[u8]) -> Vec<u8> {
        todo!()
    }

    pub fn encrypt(public_key: &[u8], data: &[u8]) -> Vec<u8> {
        todo!()
    }

    pub fn decrypt(&self, cipher: &[u8]) -> Vec<u8> {
        todo!()
    }
}





#[cfg(feature = "diffie_hellman_key_store")]
pub struct DHKeyStore {
    keys: BTreeMap<String, [u8; 32]>,
    sessions: BTreeMap<String, x25519_dalek::EphemeralSecret>,
}

#[cfg(feature = "diffie_hellman_key_store")]
impl DHKeyStore {
    pub fn new() -> Self {
        let keys = BTreeMap::new();
        let sessions = BTreeMap::new();

        Self {
            keys,
            sessions
        }
    }


    pub fn create_session(&mut self, #[cfg(not(feature = "default"))] crypto_rng: impl product_os_random::RngCrypto + 'static) -> (String, [u8; 32]) {
        let identifier = uuid::Uuid::new_v4().to_string();

        let secret =
        {
            #[cfg(feature = "default")]
            {
                x25519_dalek::EphemeralSecret::random_from_rng(product_os_random::CryptoRNG::Std(product_os_random::StdRng::from_entropy()))
            }
            #[cfg(not(feature = "default"))]
            {
                x25519_dalek::EphemeralSecret::random_from_rng(product_os_random::CustomCryptoRng::new(crypto_rng))
            }
        };

        let key = x25519_dalek::PublicKey::from(&secret);
        self.sessions.insert(identifier.clone(), secret);
        (identifier, key.to_bytes())
    }

    pub fn generate_key(&mut self, session_identifier: String, remote_public_key: &[u8], association: String, remote_session_identifier: Option<String>) {
        let identifier = session_identifier.as_str();

        if self.sessions.contains_key(identifier) {
            match self.sessions.remove(session_identifier.as_str()) {
                Some(session) => {
                    let remote_public_key_bytes: [u8; 32] = match remote_public_key.try_into() {
                        Ok(rpkb) => rpkb,
                        Err(_) => [0; 32]
                    };

                    let remote_key = x25519_dalek::PublicKey::from(remote_public_key_bytes);
                    let key= session.diffie_hellman(&remote_key);

                    let ikm = key.as_bytes();
                    let salt = None;
                    let info = match remote_session_identifier {
                        None => session_identifier.into_bytes(),
                        Some(rsi) => rsi.into_bytes()
                    };

                    let mut output_key = [0u8; 32];
                    let key_derive = hkdf::Hkdf::<sha2::Sha512>::new(salt, ikm);
                    match key_derive.expand(info.as_slice(), &mut output_key) {
                        Ok(_) => self.keys.insert(association, output_key),
                        Err(e) => panic!("{}", e)
                    };
                },
                None => ()
            }
        }
    }

    pub fn get_key(&self, association: String) -> Option<&[u8]> {
        match self.keys.get(association.as_str()) {
            Some(keys) => {
                Some(keys)
            },
            None => None
        }
    }
}





#[cfg(feature = "diffie_hellman_client_server_key_store")]
pub enum DHClientServerSessionKind {
    Client,
    Server
}

#[cfg(feature = "diffie_hellman_client_server_key_store")]
pub struct DHClientServerKeyStore {
    keys: BTreeMap<String, orion::kex::SessionKeys>,
    client_sessions: BTreeMap<String, orion::kex::EphemeralClientSession>,
    server_sessions: BTreeMap<String, orion::kex::EphemeralServerSession>
}


#[cfg(feature = "diffie_hellman_client_server_key_store")]
impl DHClientServerKeyStore {
    pub fn new() -> Self {
        let keys = BTreeMap::new();
        let client_sessions = BTreeMap::new();
        let server_sessions = BTreeMap::new();

        Self {
            keys,
            client_sessions,
            server_sessions
        }
    }

    pub fn create_session(&mut self, kind: DHClientServerSessionKind) -> (String, [u8; 32]) {
        let identifier = uuid::Uuid::new_v4().to_string();

        match kind {
            DHClientServerSessionKind::Client => {
                let session = orion::kex::EphemeralClientSession::new().unwrap();
                let key = session.public_key().clone();
                self.client_sessions.insert(identifier.clone(), session);
                (identifier, key.to_bytes())
            }
            DHClientServerSessionKind::Server => {
                let session = orion::kex::EphemeralServerSession::new().unwrap();
                let key = session.public_key().clone();
                self.server_sessions.insert(identifier.clone(), session);
                (identifier, key.to_bytes())
            }
        }
    }

    pub fn generate_keys(&mut self, session_identifier: String, remote_public_key: &[u8], association: String) {
        let identifier = session_identifier.as_str();

        if self.client_sessions.contains_key(identifier) {
            match self.client_sessions.remove(session_identifier.as_str()) {
                Some(session) => {
                    let remote_key = orion::kex::PublicKey::from_slice(remote_public_key).unwrap();
                    match session.establish_with_server(&remote_key) {
                        Ok(keys) => {
                            self.keys.insert(association, keys);
                        },
                        Err(_) => ()
                    }
                },
                None => ()
            }
        }
        else if self.server_sessions.contains_key(identifier) {
            match self.server_sessions.remove(session_identifier.as_str()) {
                Some(session) => {
                    let remote_key = orion::kex::PublicKey::from_slice(remote_public_key).unwrap();
                    match session.establish_with_client(&remote_key) {
                        Ok(keys) => {
                            self.keys.insert(association, keys);
                        },
                        Err(_) => ()
                    }
                },
                None => ()
            }
        }
    }

    pub fn get_receiving_key(&self, association: String) -> Option<&[u8]> {
        match self.keys.get(association.as_str()) {
            Some(keys) => {
                Some(keys.receiving().unprotected_as_bytes())
            },
            None => None
        }
    }

    pub fn get_sending_key(&self, association: String) -> Option<&[u8]> {
        match self.keys.get(association.as_str()) {
            Some(keys) => {
                Some(keys.transport().unprotected_as_bytes())
            },
            None => None
        }
    }
}




#[cfg(feature = "time_otp")]
struct TimeOTP {
    step: u64,
    digits: u32,
    time_generator: product_os_async_executor::moment::Moment
}

#[cfg(feature = "time_otp")]
impl TimeOTP {
    pub fn new(step: Option<u16>, digits: Option<u8>, func: Option<fn() -> chrono::DateTime<chrono::Utc>>) -> Self {
        Self {
            step: match step {
                None => 30,
                Some(s) => match u64::try_from(s) {
                    Ok(s64) => s64,
                    Err(_) => 0
                }
            },
            digits: match digits {
                None => 6,
                Some(d) => match u32::try_from(d) {
                    Ok(d32) => d32,
                    Err(_) => 0
                }
            },
            time_generator: product_os_async_executor::moment::Moment::new(func)
        }
    }

    pub fn generate_time_otp(&self, secret: &[u8]) -> String {
        let now = self.time_generator.unwrap().now();

        let seconds = now.timestamp().unsigned_abs();
        TimeOTP::totp_custom(self.step.to_owned(), self.digits.to_owned(), secret, seconds)
    }

    pub fn verify_time_otp(&self, secret: &[u8], code: String) -> bool {
        let now = self.time_generator.unwrap().now();

        let seconds = now.timestamp().unsigned_abs();
        code == TimeOTP::totp_custom(self.step.to_owned(), self.digits.to_owned(), secret, seconds)
    }

    pub const DEFAULT_STEP: u64 = 30;

    pub const DEFAULT_DIGITS: u32 = 8;

    pub fn totp(secret: &[u8], time: u64) -> String {
        TimeOTP::totp_custom(TimeOTP::DEFAULT_STEP, TimeOTP::DEFAULT_DIGITS, secret, time)
    }

    pub fn totp_custom(step: u64, digits: u32, secret: &[u8], time: u64) -> String {
        // Hash the secret and the time together.
        let mac = blake2_mac(&(time / step).to_be_bytes(), secret);
        let hash = mac.as_slice();
        /*
        let mut mac = <Hmac<H> as Mac>::new_from_slice(secret).unwrap();
        <Hmac<H> as Update>::update(&mut mac, &to_bytes(time / step));
        let hash: &[u8] = &mac.finalize().into_bytes();
        */

        // Magic from the RFC.
        let offset: usize = (hash.last().unwrap() & 0xf) as usize;
        let binary: u64 = (((hash[offset].to_owned() & 0x7f) as u64) << 24)
            | ((hash[offset.to_owned() + 1].to_owned() as u64) << 16)
            | ((hash[offset.to_owned() + 2].to_owned() as u64) << 8)
            | (hash[offset.to_owned() + 3].to_owned() as u64);

        format!("{:01$}", binary % (10_u64.pow(digits)), digits as usize)
    }

    fn to_bytes(n: u64) -> [u8; 8] {
        let mask = 0x00000000000000ff;
        let mut bytes: [u8; 8] = [0; 8];
        (0..8).for_each(|i| bytes[7 - i] = (mask & (n >> (i.to_owned() * 8))) as u8);
        bytes
    }
}


/*
#[cfg(feature = "password_hash")]
use argon2::{
    password_hash::{
        rand_core::OsRng as ArgonOsRng,
        PasswordHasher, PasswordVerifier
    },
    Argon2, Algorithm as ArgonAlgorithm, Params, Version
}
 */

#[cfg(feature = "password_hash")]
pub fn password_hash(password: &[u8], #[cfg(not(feature = "default"))] crypto_rng: impl product_os_random::RngCrypto + 'static) -> Result<Vec<u8>, argon2::password_hash::errors::Error> {
    let argon2 = argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, argon2::Params::new(15000, 2, 1, None).unwrap());
    let salt = {
        #[cfg(feature = "default")]
        {
            argon2::password_hash::SaltString::generate(product_os_random::CryptoRNG::Std(product_os_random::StdRng::from_entropy()))
        }
        #[cfg(not(feature = "default"))]
        {
            argon2::password_hash::SaltString::generate(product_os_random::CustomCryptoRng::new(crypto_rng))
        }
    };

    let password_hash = match argon2.hash_password(password, &salt) {
        Ok(res) => res,
        Err(e) => return Err(e)
    };

    Ok(password_hash.to_string().as_bytes().to_vec())
}

#[cfg(feature = "password_hash")]
pub fn password_verify(hash: &[u8], input: &[u8]) -> bool {
    let hash_str = String::from_utf8_lossy(hash);
    match argon2::PasswordHash::new(hash_str.as_ref()) {
        Ok(password_hash) => {
            match argon2::Argon2::default().verify_password( input, &password_hash) {
                Ok(_) => true,
                Err(_) => false
            }
        }
        Err(_) => false
    }
}


#[cfg(feature = "string_safe")]
pub fn encode_uri_component(value: String) -> String {
    product_os_urlencoding::encode(value.as_str()).to_string()
}

#[cfg(feature = "string_safe")]
pub fn decode_uri_component(value: String) -> String {
    product_os_urlencoding::decode(value.as_str()).unwrap().to_string()
}