selenite 0.6.0

A Crate For Post-Quantum Cryptography Certificates Built on PQcrypto
Documentation
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
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
//! # Selenite: A Core Crypto Module
//! 
//! Lacuna's Core Crypto Module consists of the structs of keypairs (FALCON512,FALCON1024,SPHINCS+), the signature struct, and most importantly the implemented traits.
//!
//! When viewing documentation for a struct, make sure to look at the documentation for the traits **Keypairs** and **Signatures** as these contain the implemented methods.
//!
//! ## Security Warning
//! 
//! This code **is not** audited and just recomended for **educational purposes**. Feel free to look through the code and help me out with it as the code is a bit... rusty.
//! 
//! ## Example Usage
//!
//! ```
//! use selenite::crypto::*;
//! 
//! fn main() {
//!     // Generates The Respected Keypair
//!     let keypair = SphincsKeypair::new();
//! 
//!     // Signs The Message as a UTF-8 Encoded String
//!     let mut sig = keypair.sign("message_to_sign");
//!     
//!     // Returns a boolean representing whether the signature is valid or not
//!     let is_verified = sig.verify();
//! }
//! ```
//! ## How To Use
//! 
//! This is based upon my beliefs. You may choose yourself.
//! 
//! **SPHINCS+** should be used for code signing as it is quite slow at signing/verifying but is based on some high security assumptions and has a high security bit level.
//! 
//! **FALCON512/FALCON1024** is comparable to **RSA2048/RSA4096** and is fast at signing/verifying. It produces much smaller signatures but has a larger public key size (but still quite small).
//! 
//! 
//! ## Serialization
//! 
//! Serde-yaml is implemented by default for the serialization/deserialization of the data to the human-readable .yaml format.
//! 
//! ## More Information
//! 
//! This library is built on bindings to **pqcrypto**, a portable, post-quantum, cryptographic library.
//! 
//! SPHINCS+ reaches a security bit level of **255 bytes** which is well over what is needed and is **Level 5**. I have plans in the future to reduce this so the signature size is smaller.
//! 
//! ## References
//! 
//! [pqcrypto-rust](https://github.com/rustpq/pqcrypto)
//! 
//! [SPHINCS+](https://sphincs.org/)
//! 
//! [SPHINCS+ REPO](https://github.com/sphincs/sphincsplus)
//! 
//! [Falcon-Sign](https://falcon-sign.info/)

// Errors
use std::path::Path;
use blake2_rfc::blake2b::Blake2bResult;
use crate::sel_errors::SeleniteErrors;

// Encodings
use base64;
use hex;

// Logging
use log::{warn,info,debug,error};

// Serialization
use serde::{Serialize, Deserialize};
use bincode;

// PQcrypto Digital Signatures
use pqcrypto_traits::sign::{PublicKey,SecretKey,DetachedSignature,VerificationError};
use pqcrypto_falcon::falcon512;
use pqcrypto_falcon::falcon1024;
use pqcrypto_sphincsplus::sphincsshake256256srobust;

extern crate rand;
extern crate ed25519_dalek;

use rand::rngs::OsRng;
use ed25519_dalek::Keypair;

use bls_signatures::*;
use bls_signatures::Serialize as Ser;

use blake2_rfc::blake2b::{Blake2b,blake2b};

use ed25519_dalek::*;

use std::io;
use std::io::Read;
use std::io::BufReader;
use std::fs::File;
use std::fs::read;

use crate::random::OsRandom;


use std::convert::TryInto;

pub use zeroize::Zeroize;



//===INFORMATION===
// All Serialization can be done through YAML
// Serialization For Signatures can be done through bincode

// [Keypair Structs]
// All Keypair Structs come with three fields all being strings
// - algorithm {FALCON512,FALCON1024,SPHINCS+}
// - public_key
// - private_key

// - Public Keys and Private Keys are encoded in hexadecimal;
// - The Signature of the Signatures struct is encoded in base64

//TODO
// - Fix bincode serialization parameter

//=============================================================================================================================
/// # Algorithms
/// This enum lists the algorithms implemented in the crate.
/// - `SPHINCS_PLUS` uses SPHINCS+ (SHAKE256) (256s) (Robust). The algorithm itself is highly secure and reaches Level 5.
pub enum KeypairAlgorithms {
    FALCON512,
    FALCON1024,
    SPHINCS_PLUS,

    ED25519,
    BLS,
}

pub enum SignatureType {
    String,
    Bytes,
}
/// # Traits For Keypairs
/// 
/// These traits are required to access the methods of the Keypair Structs. They implement basic functionality like conversion from hexadecimal to bytes, serializing/deserializing content, and signing inputs.
pub trait Keypairs {    
    /// ## Algorithm
    /// Shows the Algorithm For The Keypair Being Used
    const ALGORITHM: &'static str;
    /// ## Version
    /// Returns The Version. 0 for unstable test. 1 for first implementation.
    const VERSION: usize;
    const PUBLIC_KEY_SIZE: usize;
    const SECRET_KEY_SIZE: usize;
    const SIGNATURE_SIZE: usize;

    
    /// ## Generate A New Keypair
    /// Creates A New Keypair From Respected Struct Being Called.
    /// 
    /// Keypair Options:
    /// - FALCON512
    /// - FALCON1024
    /// - SPHINCS+
    fn new() -> Self;
    /// ## Serializes To YAML
    /// This will serialize the contents of the keypair to YAML Format, which can be read with the import function.
    fn serialize(&self) -> String;
    /// ## Construct Keypair From YAML
    /// This function will deserialize the keypair into its respected struct.
    fn deserialize(yaml: &str) -> Self;
    /// Return As Bytes
    fn public_key_as_bytes(&self) -> Vec<u8>;
    fn secret_key_as_bytes(&self) -> Vec<u8>;

    fn return_public_key_as_hex(&self) -> String;
    fn return_secret_key_as_hex(&self) -> String;

    fn decode_from_hex(s: String) -> Result<Vec<u8>,SeleniteErrors>;
    /// ## Keypair Signing
    /// Allows Signing of an Input Using The Keyholder's Secret Key and Returns The Struct Signature.
    fn sign(&self,message: &str) -> Signature;

    /// ## Sign (with Hash)
    /// 
    /// Signing bytes using `sign_data()` with Hash takes as input a slice of bytes. It then signs the hash of the bytes as opposed to signing the actual bytes.
    fn sign_data<T: AsRef<[u8]>>(&self, data: T) -> Signature;

    /// ## Sign File
    /// 
    /// This method lets you sign a file by signing the file's hash.
    fn sign_file<T: AsRef<Path>>(&self, path: T) -> Result<Signature,SeleniteErrors>;

    /// ## Data as Hexadecimal Hash
    /// 
    /// This function takes the data as a vector of bytes
    fn data_as_hexadecimal_hash(data: &[u8]) -> String;
    /// ## Data as Hash (in bytes)
    /// 
    /// This function returns the hash of the data as a vector of bytes
    fn data_as_hash(data: &[u8]) -> Vec<u8>;

    /// ## From
    /// 
    /// Converts from hexadecimal public key + private key to the respected struct. Also requires the algorithm to be known.
    fn construct_from<T: AsRef<str>>(pk: T, sk: T) -> Self;
}
/// # Traits For Signatures
/// 
/// These traits are required for properly handling signatures. They allow the serialization/deserialization of signatures, the conversion into bytes, and the verification of signatures.
pub trait Signatures {
    fn new(algorithm: &str, pk: &str, signature: &str, message: &str) -> Self;
    // bincode implementations
    fn serialize_to_bincode(&self) -> Vec<u8>;
        // TODO: Think about changing the type to &[u8] for import
    fn deserialize_from_bincode(serde_bincode: Vec<u8>) -> Self;
    /// Serializes To YAML
    fn serialize(&self) -> String;
    /// Deserializes From YAML
    fn deserialize(yaml: &str) -> Self;
    /// Verifies a Signature
    fn verify(&self) -> bool;
    fn signature_as_bytes(&self) -> Vec<u8>;
    fn message_as_bytes(&self) -> &[u8];
    /// # [Security] Compare Public Key
    /// This will match the public key in the struct to another public key you provide to make sure they are the same. The Public Key **must** be in **upperhexadecimal format**.
    fn compare_public_key(&self, pk: String) -> bool;
    /// # [Security] Compare Message
    /// This will match the message in the struct to the message you provide to make sure they are the same.
    fn compare_message(&self,msg: String) -> bool;
    /// # [Security] Matches Signatures
    /// This will match the signature in the struct with a provided signature (in base64 format)
    fn compare_signature(&self,signature: String) -> bool;
}

pub struct BLSAggregatedSignature {
    pk: Vec<String>,
    messages: Vec<String>,
    signature: String,
}

/// ## SPHINCS+ (SHAKE256) Keypair
/// 
/// When using this keypair or looking at its documentation, please look at its implemented trait **Keypairs** for its methods.
/// 
/// ```
/// use selenite::crypto::*;
/// 
/// fn main() {
///     // Generates The Respected Keypair
///     let keypair = SphincsKeypair::new();
/// 
///     // Signs The Message as a UTF-8 Encoded String
///     let mut sig = keypair.sign_str("message_to_sign");
///     
///     // Returns a boolean representing whether the signature is valid or not
///     let is_verified = sig.verify();
/// }
/// ```
#[derive(Serialize,Deserialize,Clone,Debug,PartialEq,PartialOrd,Hash,Default)]
pub struct SphincsKeypair {
    pub algorithm: String,
    pub public_key: String,
    pub private_key: String,
}
/// ## ED25519 Keypair
/// 
/// ED25519 is an elliptic-curve based digital signature scheme that is used for signing messages securely.
/// 
/// It is not post-quantum cryptography but due to its small keypair/signatures and speed, it has been included in the library.
/// 
/// ```
/// use selenite::crypto::*;
/// 
/// fn main() {
///     let keypair = ED25519::new();
///     
///     let signature = keypair.sign_str("This message is being signed.");
/// 
///     let is_valid = signature.verify();
/// 
///     assert!(is_valid);
/// 
/// }
/// ```
#[derive(Serialize,Deserialize,Clone,Debug,PartialEq,PartialOrd,Hash,Default,Zeroize)]
#[zeroize(drop)]
pub struct ED25519Keypair {
    pub algorithm: String,
    pub public_key: Vec<u8>,
    pub private_key: Vec<u8>,
}

/// ## BLS Curve
/// ### Description
/// 
/// The BLS Curve is an elliptic curve based crypto that is not post-quantum cryptography but provides **signature aggregation** that is useful in many applications.
/// ### Developer Notes
/// 
/// Instead of storing itself in a Hexadecimal String, the private key and public key is stored as a byte array
#[derive(Serialize,Deserialize,Clone,Debug,PartialEq,PartialOrd,Hash,Default,Zeroize)]
#[zeroize(drop)]
pub struct BLSKeypair {
    pub algorithm: String,
    pub public_key: Vec<u8>,
    pub private_key: Vec<u8>,
}

/// ## Falcon1024 Keypair
/// 
/// When using this keypair or looking at its documentation, please look at its implemented trait **Keypairs** for its methods.
/// 
/// ```
/// use selenite::crypto::*;
/// 
/// fn main() {
///     // Generates The Respected Keypair
///     let keypair = Falcon1024Keypair::new();
/// 
///     // Signs The Message as a UTF-8 Encoded String
///     let mut sig = keypair.sign("message_to_sign");
///     
///     // Returns a boolean representing whether the signature is valid or not
///     let is_verified = sig.verify();
/// }
/// ```
#[derive(Serialize,Deserialize,Clone,Debug,PartialEq,PartialOrd,Hash,Default,Zeroize)]
#[zeroize(drop)]
pub struct Falcon1024Keypair {
    pub algorithm: String,
    pub public_key: String,
    pub private_key: String,
}
/// ## Falcon512 Keypair
/// 
/// When using this keypair or looking at its documentation, please look at its implemented trait **Keypairs** for its methods.
/// 
/// ```
/// use selenite::crypto::*;
/// 
/// fn main() {
///     // Generates The Respected Keypair
///     let keypair = Falcon512Keypair::new();
/// 
///     // Signs The Message as a UTF-8 Encoded String
///     let mut sig = keypair.sign("message_to_sign");
///     
///     // Returns a boolean representing whether the signature is valid or not
///     let is_verified = sig.verify();
/// }
/// ```
#[derive(Serialize,Deserialize,Clone,Debug,PartialEq,PartialOrd,Hash,Default,Zeroize)]
#[zeroize(drop)]
pub struct Falcon512Keypair {
    pub algorithm: String,
    pub public_key: String,
    pub private_key: String,
}
/// ## The Signature Struct
/// 
/// This struct contains the fields for signatures and implements the Signatures trait to allow methods on the struct.
#[derive(Serialize,Deserialize,Clone,Debug,PartialEq,PartialOrd,Hash,Default,Zeroize)]
#[zeroize(drop)]
pub struct Signature {
    pub algorithm: String,
    pub public_key: String,
    pub message: String,
    pub signature: String,

    pub is_str: bool,
}

pub struct Verify;

impl BLSKeypair {
    /// # Aggregation Function
    /// 
    /// **Note:** Signatures must be in Base64 format.
    /// 
    /// **Info:** Aggregation is only allowed for BLS (BLSKeypair).
    /// 
    /// ---
    /// 
    /// ### Description
    /// 
    /// This function aggregates (or combines) Base64-encoded signatures for BLS (`BLSKeypair`). This can be used to reduce the number of signatures into a single signature.
    /// 
    /// ---
    /// ### Errors
    /// 
    /// The function returns `SeleniteErrors::BLSAggregationFailed` if an error occurs. It will panic if no signatures are passed to the function. It will also panic if conversion and decoding fails.
    pub fn aggregate(signatures: Vec<String>) -> Result<bls_signatures::Signature, SeleniteErrors> {
        let num_of_signatures = signatures.len();
        let mut v: Vec<bls_signatures::Signature> = vec![];

        log::info!("[INFO] BLS: Aggregating Digital Signatures.");
        log::info!("[INFO] BLS: Aggregating {} Signatures Into A Single Signature.",num_of_signatures);

        if num_of_signatures == 0 {
            log::error!("[ERROR] BLS: No Signatures Provided To Aggregation Function. Operating Failed.");
            panic!("[BLS|0x0002] No Signatures Provided To Aggregation Function");
        }


        for sig in signatures {
            let decoded_sig = base64::decode(sig).expect("[BLS|0x0000] Failed To Decode From Base64 During Aggregation of Signatures");
            let final_signature = bls_signatures::Signature::from_bytes(&decoded_sig).expect("[BLS|0x0001] Failed To Convert To `bls_signature::Signature` when converting from bytes.");
            v.push(final_signature);
        }
        let aggregated_signature = bls_signatures::aggregate(&v);

        match aggregated_signature {
            Ok(bls_sig) => {
                log::info!("[INFO] BLS: Finished Aggregation of Signatures. No Problems Detected.");
                return Ok(bls_sig)
            }
            Err(_) => {
                log::error!("[ERROR] Failed To Aggregate Signatures For BLS Signatures.");
                return Err(SeleniteErrors::BLSAggregationFailed)
            }
        }
    }
}

impl Keypairs for BLSKeypair {
    const VERSION: usize = 0;
    const ALGORITHM: &'static str = "BLS";
    const PUBLIC_KEY_SIZE: usize = 48usize;
    const SECRET_KEY_SIZE: usize = 32usize;
    const SIGNATURE_SIZE: usize = 96usize;

    fn new() -> Self {
        let randomness = OsRandom::rand_64().expect("Failed To Get Randomness");
        let secret_key = bls_signatures::PrivateKey::new(randomness);

        let secret_key_bytes = secret_key.as_bytes();

        let public_key = secret_key.public_key().as_bytes();

        return Self {
            algorithm: String::from(Self::ALGORITHM),
            public_key: public_key,
            private_key: secret_key_bytes,
        }
    }
    fn serialize(&self) -> String {
        return serde_yaml::to_string(&self).unwrap()
    }
    fn deserialize(yaml: &str) -> Self {
        let result: BLSKeypair = serde_yaml::from_str(yaml).unwrap();
        return result
    }
    fn public_key_as_bytes(&self) -> Vec<u8> {
        return self.public_key.clone()
    }
    fn secret_key_as_bytes(&self) -> Vec<u8> {
        log::warn!("[WARN|0x1004] The Secret Key For a BLS Keypair Was Just Returned In Bytes Form");
        return self.private_key.clone()
    }
    fn return_public_key_as_hex(&self) -> String {
        return hex::encode_upper(&self.public_key)
    }
    fn return_secret_key_as_hex(&self) -> String {
        log::warn!("[WARN|0x1004] The Secret Key For a BLS Keypair Was Just Returned In Hexadecimal Form");
        return hex::encode_upper(&self.private_key)
    }
    fn decode_from_hex(s: String) -> Result<Vec<u8>,SeleniteErrors> {
        let h = hex::decode(s);
        match h {
            Ok(v) => return Ok(v),
            Err(_) => return Err(SeleniteErrors::DecodingFromHexFailed)
        }
    }
    fn sign(&self,message: &str) -> Signature {
        let key = bls_signatures::PrivateKey::from_bytes(&self.private_key).expect("Failed To Deserialize Private Key For BLS");
        let signature = key.sign(message.as_bytes());

        // Encoded In Hexadecimal
        let final_signature = base64::encode(signature.as_bytes());
        let pk = hex::encode_upper(&self.public_key);

        return Signature {
            algorithm: self.algorithm.clone(),
            public_key: pk,
            message: String::from(message),
            signature: final_signature,
            is_str: true,
        }

    }
    // Signs hexadecimal string
    fn sign_data<T: AsRef<[u8]>>(&self,data: T) -> Signature {
        let key = bls_signatures::PrivateKey::from_bytes(&self.private_key).expect("[BLS|0x0003] Failed To Deserialize Private Key For BLS");
        let final_hash = Self::data_as_hexadecimal_hash(data.as_ref());

        // Sign Hash of Data
        let signature = key.sign(final_hash.clone());

        // Encoded In Hexadecimal and Base64
        let final_signature = base64::encode(signature.as_bytes());
        let pk = hex::encode_upper(&self.public_key);


        return Signature {
            algorithm: String::from(Self::ALGORITHM),
            public_key: pk,
            message: final_hash,
            signature: final_signature,
            is_str: false,
        }

    }
    // Signs hexadecimal string
    fn sign_file<T: AsRef<Path>>(&self, path: T) -> Result<Signature,SeleniteErrors> {
        let does_file_exist: bool = path.as_ref().exists();

        if does_file_exist == false {
            return Err(SeleniteErrors::FileDoesNotExist)
        }

        let key = bls_signatures::PrivateKey::from_bytes(&self.private_key).expect("Failed To Deserialize Private Key For BLS");

        
        let fbuffer = std::fs::read(path).expect("[Error] failed to open file");
        let hash = Self::data_as_hexadecimal_hash(&fbuffer);

        let signature = key.sign(&hash);

        return Ok(Signature {
            algorithm: String::from(Self::ALGORITHM),
            public_key: self.return_public_key_as_hex(),
            message: hash,
            signature: base64::encode(&signature.as_bytes()),
            is_str: false
        })

    }
    fn data_as_hexadecimal_hash(data: &[u8]) -> String {
        let hash: Blake2bResult = blake2b(64, &[], data);
        let hex_hash: String = hex::encode_upper(hash.as_bytes());
        return hex_hash
    }
    fn data_as_hash(data: &[u8]) -> Vec<u8> {
        let hash: Blake2bResult = blake2b(64, &[], data);
        let bytes: Vec<u8> = hash.as_bytes().to_vec();
        return bytes
    }
    fn construct_from<T: AsRef<str>>(pk: T, sk: T) -> Self {
        return Self {
            algorithm: String::from(Self::ALGORITHM),
            public_key: hex::decode(pk.as_ref()).expect("[Error] Failed To Decode Public Key From Hex"),
            private_key: hex::decode(sk.as_ref()).expect("[Error] Failed To Decode Secret Key From Hex"),
        }
    }
}

impl Keypairs for ED25519Keypair{
    const VERSION: usize = 0;
    const ALGORITHM: &'static str = "ED25519";
    const PUBLIC_KEY_SIZE: usize = 32;
    const SECRET_KEY_SIZE: usize = 32;
    const SIGNATURE_SIZE: usize = 64;

    fn new() -> Self {
        let mut csprng = OsRng{};
        let keypair: ed25519_dalek::Keypair = ed25519_dalek::Keypair::generate(&mut csprng);
        let bytes: [u8; 64] = keypair.to_bytes();

        let sk = &bytes[0..32];
        let pk = &bytes[32..64];

        return Self {
            algorithm: String::from("ED25519"),
            public_key: pk.to_vec(),
            private_key: sk.to_vec(),
        }
    }
    fn serialize(&self) -> String {
        return serde_yaml::to_string(&self).unwrap()
    }
    fn deserialize(yaml: &str) -> Self {
        let result: ED25519Keypair = serde_yaml::from_str(yaml).unwrap();
        return result
    }
    fn public_key_as_bytes(&self) -> Vec<u8> {
        return self.public_key.clone()
    }
    fn secret_key_as_bytes(&self) -> Vec<u8> {
        log::warn!("[WARN|0x1003] The Secret Key For a ED25519 Keypair Was Just Returned In Bytes Form");
        return self.private_key.clone()
    }
    fn return_public_key_as_hex(&self) -> String {
        return hex::encode_upper(&self.public_key)
    }
    fn return_secret_key_as_hex(&self) -> String {
        log::warn!("[WARN|0x1003] The Secret Key For a ED25519 Keypair Was Just Returned In Hexadecimal Form");
        return hex::encode_upper(&self.private_key)
    }
    fn sign(&self, message: &str) -> Signature {
        let mut vector1: Vec<u8> = self.private_key.clone();
        let mut vector2: Vec<u8> = self.public_key.clone();

        let mut vector_keypair: Vec<u8> = vec![];

        vector_keypair.append(&mut vector1);
        vector_keypair.append(&mut vector2);

        let keypair = ed25519_dalek::Keypair::from_bytes(&vector_keypair).unwrap();
        let sig: ed25519_dalek::Signature = keypair.sign(message.as_bytes());


        return Signature {
            algorithm: String::from(Self::ALGORITHM),
            public_key: hex::encode_upper(self.public_key.clone()),
            message: String::from(message),
            signature: base64::encode(sig),
            is_str: true,
        }
    }
    // Signs Hexadecimal String
    fn sign_data<T: AsRef<[u8]>>(&self, data: T) -> Signature {
        // Hash Message As Blake2b (64 bytes)
        let final_message_hash = Self::data_as_hexadecimal_hash(data.as_ref());

        // Public Keys and Private Keys
        let mut vector1: Vec<u8> = self.private_key.clone();
        let mut vector2: Vec<u8> = self.public_key.clone();

        // Init Keypair Vector
        let mut vector_keypair: Vec<u8> = vec![];

        // Append To Vector
        vector_keypair.append(&mut vector1);
        vector_keypair.append(&mut vector2);

        // Keypair
        let keypair = ed25519_dalek::Keypair::from_bytes(&vector_keypair).unwrap();
        let sig: ed25519_dalek::Signature = keypair.sign(&final_message_hash.as_bytes());


        return Signature {
            algorithm: String::from(Self::ALGORITHM),
            public_key: hex::encode_upper(self.public_key.clone()),
            message: final_message_hash,
            signature: base64::encode(sig),

            is_str: false,
        }
    }
    // Signs Hexadecimal String
    fn sign_file<T: AsRef<Path>>(&self, path: T) -> Result<Signature,SeleniteErrors> {
        let does_file_exist: bool = path.as_ref().exists();

        if does_file_exist == false {
            return Err(SeleniteErrors::FileDoesNotExist)
        }

        let mut vector1: Vec<u8> = self.private_key.clone();
        let mut vector2: Vec<u8> = self.public_key.clone();

        // Init Keypair Vector
        let mut vector_keypair: Vec<u8> = vec![];
        // Append To Vector
        vector_keypair.append(&mut vector1);
        vector_keypair.append(&mut vector2);

        let keypair = ed25519_dalek::Keypair::from_bytes(&vector_keypair).unwrap();
        
        let fbuffer = std::fs::read(path).expect("[Error] failed to open file");
        let hash = Self::data_as_hexadecimal_hash(&fbuffer);

        let sig: ed25519_dalek::Signature = keypair.sign(&hash.as_bytes());


        return Ok(Signature {
            algorithm: String::from(Self::ALGORITHM),
            public_key: self.return_public_key_as_hex(),
            message: hash,
            signature: base64::encode(sig),
            is_str: false
        })
    }
    fn decode_from_hex(s: String) -> Result<Vec<u8>,SeleniteErrors> {
        let h = hex::decode(s);
        match h {
            Ok(v) => return Ok(v),
            Err(_) => return Err(SeleniteErrors::DecodingFromHexFailed)
        }
    }
    fn data_as_hexadecimal_hash(data: &[u8]) -> String {
        let hash: Blake2bResult = blake2b(64, &[], data);
        let hex_hash: String = hex::encode_upper(hash.as_bytes());
        return hex_hash
    }
    fn data_as_hash(data: &[u8]) -> Vec<u8> {
        let hash: Blake2bResult = blake2b(64, &[], data);
        let bytes = hash.as_bytes().to_vec();
        return bytes
    }
    fn construct_from<T: AsRef<str>>(pk: T, sk: T) -> Self {
        return Self {
            algorithm: String::from(Self::ALGORITHM),
            public_key: hex::decode(pk.as_ref()).expect("[Error] Failed To Decode Public Key From Hex"),
            private_key: hex::decode(sk.as_ref()).expect("[Error] Failed To Decode Secret Key From Hex"),
        }
    }
}

impl Keypairs for Falcon512Keypair {
    const VERSION: usize = 0;
    const ALGORITHM: &'static str = "FALCON512";
    const PUBLIC_KEY_SIZE: usize = 897;
    const SECRET_KEY_SIZE: usize = 1281;
    const SIGNATURE_SIZE: usize = 660;
    
    fn new() -> Self {
        let (pk,sk) = falcon512::keypair();
        //let hash = blake2b(64,&[],hex::encode_upper(pk.as_bytes()).as_bytes());

        Falcon512Keypair {
            algorithm: String::from(Self::ALGORITHM),
            public_key: hex::encode_upper(pk.as_bytes()),
            private_key: hex::encode_upper(sk.as_bytes()),
        }
    }
    fn serialize(&self) -> String {
        return serde_yaml::to_string(&self).unwrap();
    }
    // Add Error-Checking
    fn deserialize(yaml: &str) -> Self {
        let result: Falcon512Keypair = serde_yaml::from_str(yaml).unwrap();
        return result
    }
    fn public_key_as_bytes(&self) -> Vec<u8> {
        return hex::decode(&self.public_key).unwrap()
    }
    fn secret_key_as_bytes(&self) -> Vec<u8> {
        log::warn!("[WARN|0x1001] The Secret Key For a FALCON512 Keypair Was Just Returned In Bytes Form");
        return hex::decode(&self.private_key).unwrap()
    }
    fn sign(&self,message: &str) -> Signature {
        let x = falcon512::detached_sign(message.as_bytes(), &falcon512::SecretKey::from_bytes(&self.secret_key_as_bytes()).unwrap());
        
        return Signature {
            algorithm: String::from(Self::ALGORITHM), // String
            public_key: self.public_key.clone(), // Public Key Hex
            message: String::from(message), // Original UTF-8 Message
            signature: base64::encode(x.as_bytes()), // Base64-Encoded Detatched Signature
            is_str: true,
        }
    }
    // Signs Hexadecimal Hash (as bytes)
    fn sign_data<T: AsRef<[u8]>>(&self,data: T) -> Signature {
        let hex_hash = Self::data_as_hexadecimal_hash(data.as_ref());
        let signature = falcon512::detached_sign(hex_hash.as_bytes(), &falcon512::SecretKey::from_bytes(&self.secret_key_as_bytes()).unwrap());

        return Signature {
            algorithm: String::from(Self::ALGORITHM),
            public_key: self.public_key.clone(),
            message: hex_hash,
            signature: base64::encode(signature.as_bytes()),
            is_str: false,
        }
    }
    // Signs hexadecimal hash (as bytes)
    fn sign_file<T: AsRef<Path>>(&self,path: T) -> Result<Signature,SeleniteErrors> {
        let does_file_exist: bool = path.as_ref().exists();

        if does_file_exist == false {
            return Err(SeleniteErrors::FileDoesNotExist)
        }

        let fbuffer = std::fs::read(path.as_ref()).expect("[Error] failed to open file");
        let hash = Self::data_as_hexadecimal_hash(&fbuffer);

        let signature = falcon512::detached_sign(hash.as_bytes(), &falcon512::SecretKey::from_bytes(&self.secret_key_as_bytes()).unwrap());

        return Ok(Signature {
            algorithm: String::from(Self::ALGORITHM),
            public_key: self.return_public_key_as_hex(),
            message: hash,
            signature: base64::encode(signature.as_bytes()),
            is_str: false,
        })
    }
    fn decode_from_hex(s: String) -> Result<Vec<u8>,SeleniteErrors> {
        let h = hex::decode(s);
        match h {
            Ok(v) => return Ok(v),
            Err(_) => return Err(SeleniteErrors::DecodingFromHexFailed)
        }
    }
    fn return_public_key_as_hex(&self) -> String {
        return self.public_key.clone()
    }
    fn return_secret_key_as_hex(&self) -> String {
        log::warn!("[WARN|0x1001] The Secret Key For a FALCON512 Keypair Was Just Returned In Hexadecimal Form");
        return self.private_key.clone()
    }
    fn data_as_hexadecimal_hash(data: &[u8]) -> String {
        let hash: Blake2bResult = blake2b(64, &[], data);
        let hex_hash: String = hex::encode_upper(hash.as_bytes());
        return hex_hash
    }
    fn data_as_hash(data: &[u8]) -> Vec<u8> {
        let hash: Blake2bResult = blake2b(64, &[], data);
        let bytes = hash.as_bytes();
        return bytes.to_vec()
    }
    fn construct_from<T: AsRef<str>>(pk: T, sk: T) -> Self {
        return Self {
            algorithm: String::from(Self::ALGORITHM),
            public_key: pk.as_ref().to_string(),
            private_key: sk.as_ref().to_string(),
        }
    }
}
impl Keypairs for Falcon1024Keypair {
    const VERSION: usize = 0;
    const ALGORITHM: &'static str = "FALCON1024";
    const PUBLIC_KEY_SIZE: usize = 1793;
    const SECRET_KEY_SIZE: usize = 2305;
    const SIGNATURE_SIZE: usize = 1280;
    
    fn new() -> Self {
        let (pk,sk) = falcon1024::keypair();
        //let hash = blake2b(64,&[],hex::encode_upper(pk.as_bytes()).as_bytes());

        Falcon1024Keypair {
            algorithm: String::from(Self::ALGORITHM),
            public_key: hex::encode_upper(pk.as_bytes()),
            private_key: hex::encode_upper(sk.as_bytes()),
        }
    }
    fn serialize(&self) -> String {
        return serde_yaml::to_string(&self).unwrap();
    }
    // Add Error-Checking
    fn deserialize(yaml: &str) -> Self {
        let result: Falcon1024Keypair = serde_yaml::from_str(yaml).unwrap();
        return result
    }
    fn public_key_as_bytes(&self) -> Vec<u8> {
        return hex::decode(&self.public_key).unwrap()
    }
    fn secret_key_as_bytes(&self) -> Vec<u8> {
        log::warn!("[WARN|0x1002] The Secret Key For a FALCON1024 Keypair Was Just Returned In Bytes Form");
        return hex::decode(&self.private_key).unwrap()
    }
    fn sign(&self,message: &str) -> Signature {
        let x = falcon1024::detached_sign(message.as_bytes(), &falcon1024::SecretKey::from_bytes(&self.secret_key_as_bytes()).unwrap());
        
        return Signature {
            algorithm: String::from(Self::ALGORITHM), // String
            public_key: self.public_key.clone(), // Public Key Hex
            message: String::from(message), // Original UTF-8 Message
            signature: base64::encode(x.as_bytes()), // Base64-Encoded Detatched Signature
            is_str: true,
        }
    }
    fn sign_data<T: AsRef<[u8]>>(&self,data: T) -> Signature {
        let hex_hash = Self::data_as_hexadecimal_hash(data.as_ref());
        let signature = falcon1024::detached_sign(hex_hash.as_bytes(), &falcon1024::SecretKey::from_bytes(&self.secret_key_as_bytes()).unwrap());

        return Signature {
            algorithm: String::from(Self::ALGORITHM),
            public_key: self.public_key.clone(),
            message: hex_hash,
            signature: base64::encode(signature.as_bytes()),
            is_str: false,
        }
    }
    fn sign_file<T: AsRef<Path>>(&self,path: T) -> Result<Signature,SeleniteErrors> {
        let does_file_exist: bool = path.as_ref().exists();

        if does_file_exist == false {
            return Err(SeleniteErrors::FileDoesNotExist)
        }

        let fbuffer = std::fs::read(path.as_ref()).expect("[Error] failed to open file");
        let hash = Self::data_as_hexadecimal_hash(&fbuffer);

        let signature = falcon1024::detached_sign(hash.as_bytes(), &falcon1024::SecretKey::from_bytes(&self.secret_key_as_bytes()).unwrap());

        return Ok(Signature {
            algorithm: String::from(Self::ALGORITHM),
            public_key: self.return_public_key_as_hex(),
            message: hash,
            signature: base64::encode(signature.as_bytes()),
            is_str: false,
        })
    }
    fn decode_from_hex(s: String) -> Result<Vec<u8>,SeleniteErrors> {
        let h = hex::decode(s);
        match h {
            Ok(v) => return Ok(v),
            Err(_) => return Err(SeleniteErrors::DecodingFromHexFailed)
        }
    }
    fn return_public_key_as_hex(&self) -> String {
        return self.public_key.clone()
    }
    fn return_secret_key_as_hex(&self) -> String {
        log::warn!("[WARN|0x1002] The Secret Key For a FALCON1024 Keypair Was Just Returned In Hexadecimal Form");
        return self.private_key.clone()
    }
    fn data_as_hexadecimal_hash(data: &[u8]) -> String {
        let hash: Blake2bResult = blake2b(64, &[], data);
        let hex_hash: String = hex::encode_upper(hash.as_bytes());
        return hex_hash
    }
    fn data_as_hash(data: &[u8]) -> Vec<u8> {
        let hash: Blake2bResult = blake2b(64, &[], data);
        let bytes = hash.as_bytes();
        return bytes.to_vec()
    }
    fn construct_from<T: AsRef<str>>(pk: T, sk: T) -> Self {
        return Self {
            algorithm: String::from(Self::ALGORITHM),
            public_key: pk.as_ref().to_string(),
            private_key: sk.as_ref().to_string(),
        }
    }
}
impl Keypairs for SphincsKeypair {
    const VERSION: usize = 0;
    const ALGORITHM: &'static str = "SPHINCS+";
    const PUBLIC_KEY_SIZE: usize = 64;
    const SECRET_KEY_SIZE: usize = 128;
    const SIGNATURE_SIZE: usize = 29_792;
    
    fn new() -> Self {
        let (pk,sk) = sphincsshake256256srobust::keypair();
        //let hash = blake2b(64,&[],hex::encode_upper(pk.as_bytes()).as_bytes());

        SphincsKeypair {
            algorithm: String::from(Self::ALGORITHM),
            public_key: hex::encode_upper(pk.as_bytes()),
            private_key: hex::encode_upper(sk.as_bytes()),
        }
    }
    fn serialize(&self) -> String {
        return serde_yaml::to_string(&self).unwrap();
    }
    // Add Error-Checking
    fn deserialize(yaml: &str) -> Self {
        let result: SphincsKeypair = serde_yaml::from_str(yaml).unwrap();
        return result
    }
    fn public_key_as_bytes(&self) -> Vec<u8> {
        return hex::decode(&self.public_key).unwrap()
    }
    fn secret_key_as_bytes(&self) -> Vec<u8> {
        log::warn!("[WARN|0x1000] The Secret Key For a SPHINCS+ Keypair Was Just Returned In Byte Form");
        return hex::decode(&self.private_key).unwrap()
    }
    fn sign(&self,message: &str) -> Signature {
        let x = sphincsshake256256srobust::detached_sign(message.as_bytes(), &sphincsshake256256srobust::SecretKey::from_bytes(&self.secret_key_as_bytes()).unwrap());
        return Signature {
            algorithm: String::from(Self::ALGORITHM), // String
            public_key: self.public_key.clone(), // Public Key Hex
            message: String::from(message), // Original UTF-8 Message
            signature: base64::encode(x.as_bytes()), // Base64-Encoded Detatched Signature
            is_str: true,
        }
    }
    fn sign_data<T: AsRef<[u8]>>(&self,data: T) -> Signature {
        let hex_hash = Self::data_as_hexadecimal_hash(data.as_ref());
        let signature = sphincsshake256256srobust::detached_sign(hex_hash.as_bytes(), &sphincsshake256256srobust::SecretKey::from_bytes(&self.secret_key_as_bytes()).unwrap());

        return Signature {
            algorithm: String::from(Self::ALGORITHM),
            public_key: self.public_key.clone(),
            message: hex_hash,
            signature: base64::encode(signature.as_bytes()),
            is_str: false,
        }
    }
    fn sign_file<T: AsRef<Path>>(&self,path: T) -> Result<Signature,SeleniteErrors> {
        let does_file_exist: bool = path.as_ref().exists();

        if does_file_exist == false {
            return Err(SeleniteErrors::FileDoesNotExist)
        }

        let fbuffer = std::fs::read(path.as_ref()).expect("[Error] failed to open file");
        let hash = Self::data_as_hexadecimal_hash(&fbuffer);

        let signature = sphincsshake256256srobust::detached_sign(hash.as_bytes(), &sphincsshake256256srobust::SecretKey::from_bytes(&self.secret_key_as_bytes()).unwrap());

        return Ok(Signature {
            algorithm: String::from(Self::ALGORITHM),
            public_key: self.return_public_key_as_hex(),
            message: hash,
            signature: base64::encode(signature.as_bytes()),
            is_str: false,
        })
    }
    fn decode_from_hex(s: String) -> Result<Vec<u8>,SeleniteErrors> {
        let h = hex::decode(s);
        match h {
            Ok(v) => return Ok(v),
            Err(_) => return Err(SeleniteErrors::DecodingFromHexFailed)
        }
    }
    fn return_public_key_as_hex(&self) -> String {
        return self.public_key.clone()
    }
    fn return_secret_key_as_hex(&self) -> String {
        log::warn!("[WARN|0x1000] The Secret Key For a SPHINCS+ Keypair Was Just Returned In Hexadecimal Form");
        return self.private_key.clone()
    }
    fn data_as_hexadecimal_hash(data: &[u8]) -> String {
        let hash: Blake2bResult = blake2b(64, &[], data);
        let hex_hash: String = hex::encode_upper(hash.as_bytes());
        return hex_hash
    }
    fn data_as_hash(data: &[u8]) -> Vec<u8> {
        let hash: Blake2bResult = blake2b(64, &[], data);
        let bytes = hash.as_bytes();
        return bytes.to_vec()
    }
    fn construct_from<T: AsRef<str>>(pk: T, sk: T) -> Self {
        return Self {
            algorithm: String::from(Self::ALGORITHM),
            public_key: pk.as_ref().to_string(),
            private_key: sk.as_ref().to_string(),
        }
    }
}

impl Signatures for Signature {
    fn new(algorithm: &str, pk: &str, signature: &str, message: &str) -> Self {
        if algorithm == "SPHINCS+" || algorithm == "FALCON512" || algorithm == "FALCON1024" || algorithm == "ED25519" || algorithm == "BLS" {
            return Signature {
                algorithm: algorithm.to_owned(),
                public_key: pk.to_owned(),
                message: message.to_owned(),
                signature: signature.to_owned(),
                is_str: true,
            }
        }
        else {
            panic!("AlgorithmWrong")
        }
    }
    fn verify(&self) -> bool {
        if self.algorithm == "FALCON512" {
            let v: Result<(),VerificationError> = falcon512::verify_detached_signature(&falcon512::DetachedSignature::from_bytes(&base64::decode(&self.signature).unwrap()).unwrap(), &self.message.as_bytes(), &falcon512::PublicKey::from_bytes(&hex::decode(&self.public_key).unwrap()).unwrap());
            if v.is_err() {
                return false
            }
            else {
                return true
            }
        }
        else if self.algorithm == "FALCON1024" {
            let v: Result<(),VerificationError> = falcon1024::verify_detached_signature(&falcon1024::DetachedSignature::from_bytes(&base64::decode(&self.signature).unwrap()).unwrap(), &self.message.as_bytes(), &falcon1024::PublicKey::from_bytes(&hex::decode(&self.public_key).unwrap()).unwrap());
            if v.is_err() {
                return false
            }
            else {
                return true
            }
        }
        else if self.algorithm == "SPHINCS+" {
            let v: Result<(),VerificationError> = sphincsshake256256srobust::verify_detached_signature(&sphincsshake256256srobust::DetachedSignature::from_bytes(&base64::decode(&self.signature).unwrap()).unwrap(), &self.message.as_bytes(), &sphincsshake256256srobust::PublicKey::from_bytes(&hex::decode(&self.public_key).unwrap()).unwrap());
            if v.is_err() {
                return false
            }
            else {
                return true
            }
        }
        else if self.algorithm == "ED25519" {
            let base64_decoded = base64::decode(self.signature.clone()).unwrap();
            let hex_decoded = hex::decode(self.public_key.clone()).unwrap();
            
            let pk: ed25519_dalek::PublicKey = ed25519_dalek::PublicKey::from_bytes(&hex_decoded).unwrap();

            if base64_decoded.len() == 64 {
                let mut sig: [u8;64] = [0u8;64];
                let mut counter = 0usize;

                for i in base64_decoded {
                    sig[counter] = i;
                    counter += 1;
                }

                let signature = ed25519_dalek::Signature::new(sig);
                let output = pk.verify_strict(self.message.as_bytes(), &signature);
                
                match output {
                    Ok(_v) => return true,
                    Err(_e) => return false,
                }
            }
            else {
                return false
            }
        }
        else if self.algorithm == "BLS" {
            let base64_decoded = base64::decode(&self.signature).expect("Failed To Decoded Base64 For BLS");
            let hex_decoded = hex::decode(&self.public_key).expect("Failed To Decode Hexadecimal");

            let pk = bls_signatures::PublicKey::from_bytes(&hex_decoded).expect("Failed To Convert From Bytes To Signature In Verification Function For Public Key");
            let signature = bls_signatures::Signature::from_bytes(&base64_decoded).expect("Failed To Convert From Bytes To Signature In Verification Function For Signature");

            let is_valid: bool = bls_signatures::verify_messages(&signature, &vec![self.message.as_bytes()], &[pk]);

            return is_valid
        }
        else {
            panic!("[Verification|0x0000] Invalid Algorithm Type")
        }
    }
    fn deserialize(yaml: &str) -> Self {
        let result: Signature = serde_yaml::from_str(yaml).unwrap();
        return result
    }
    fn serialize(&self) -> String {
        return serde_yaml::to_string(&self).unwrap();
    }
    fn deserialize_from_bincode(serde_bincode: Vec<u8>) -> Self {
        return bincode::deserialize(&serde_bincode[..]).unwrap();
    }
    fn serialize_to_bincode(&self) -> Vec<u8> {
        return bincode::serialize(&self).unwrap();
    }
    // Returns message as a byte array
    fn message_as_bytes(&self) -> &[u8] {
        return self.message.as_bytes()
    }
    // Returns Base64 decoded signature as a vector of bytes
    fn signature_as_bytes(&self) -> Vec<u8> {
        return base64::decode(&self.signature).unwrap()
    }
    fn compare_public_key(&self, pk: String) -> bool {
        if self.public_key == pk {
            return true
        }
        else {
            return false
        }
    }
    // Message is a UTF-8 Message / String
    fn compare_message(&self, msg: String) -> bool {
        if self.message == msg {
            return true
        }
        else {
            return false
        }
    }
    // Signature Is Encoded in Base64
    fn compare_signature(&self, signature: String) -> bool {
        if self.signature == signature {
            return true
        }
        else {
            return false
        }
    }
}

impl Verify {
    /// ## Verification
    /// Verifies Signatures by constructing them and returns a boolean.
    /// 
    /// Currently does not allow verification of ED25519 (non pq crypto)
    pub fn new(algorithm: KeypairAlgorithms,pk: &str,signature: &str,message: &str) -> bool {
        
        let alg = match algorithm {
            KeypairAlgorithms::FALCON512 => "FALCON512",
            KeypairAlgorithms::FALCON1024 => "FALCON1024",
            KeypairAlgorithms::SPHINCS_PLUS => "SPHINCS+",
            
            // Not Post-Quantum
            KeypairAlgorithms::ED25519 => "ED25519",
            KeypairAlgorithms::BLS => "BLS",
        };

        log::info!("[INFO] Verifying Digital Signature: {}",&alg);
        log::info!("Public Key: {}",pk);
        log::info!("Signature: {}",signature);
        log::info!("Message: {}",message);

        // PK (HEX) | SIG (BASE64) | MESSAGE 
        let pk_bytes = hex::decode(pk).unwrap();
        let signature_bytes = base64::decode(signature).unwrap();
        let message_bytes = message.as_bytes();

        if alg == "FALCON512" {
            let v: Result<(),VerificationError> = falcon512::verify_detached_signature(&falcon512::DetachedSignature::from_bytes(&signature_bytes).unwrap(), message_bytes, &falcon512::PublicKey::from_bytes(&pk_bytes).unwrap());
            if v.is_err() {
                return false
            }
            else {
                return true
            }
        }
        if alg == "FALCON1024" {
            let v: Result<(),VerificationError> = falcon1024::verify_detached_signature(&falcon1024::DetachedSignature::from_bytes(&signature_bytes).unwrap(), message_bytes, &falcon1024::PublicKey::from_bytes(&pk_bytes).unwrap());
            if v.is_err() {
                return false
            }
            else {
                return true
            }
        }
        else if alg == "SPHINCS+" {
            let v: Result<(),VerificationError> = sphincsshake256256srobust::verify_detached_signature(&sphincsshake256256srobust::DetachedSignature::from_bytes(&signature_bytes).unwrap(), message_bytes, &sphincsshake256256srobust::PublicKey::from_bytes(&pk_bytes).unwrap());
            if v.is_err() {
                return false
            }
            else {
                return true
            }
        }
        else if alg  == "ED25519" {
            let mut sig_array: [u8;64] = [0;64];

            let pk = hex::decode(pk).expect("Failed To Decode Public Key For ED25519");
            let sig = base64::decode(signature).expect("Failed To Decode Signature From Base64 For ED25519");
            let message_as_bytes = message.as_bytes();

            for x in 0..sig.len() {
                sig_array[x] = sig[x];
            }

            let pk: ed25519_dalek::PublicKey = ed25519_dalek::PublicKey::from_bytes(&pk).expect("Failed To Convert To Public Key For ED25519");
            let signature: ed25519_dalek::Signature = ed25519_dalek::Signature::new(sig_array);

            let is_valid = pk.verify_strict(&message_as_bytes, &signature);
            match is_valid {
                Ok(_) => return true,
                Err(_) => return false,
            }
        }
        else if alg == "BLS" {
            let pk = hex::decode(pk).expect("Failed To Decode Public Key For BLS");
            let sig = base64::decode(signature).expect("Failed To Decode Signature From Base64");
            let message_as_bytes = message.as_bytes();

            let final_pk = bls_signatures::PublicKey::from_bytes(&pk).expect("Failed To Convert To Public Key For BLS");
            let final_sig = bls_signatures::Signature::from_bytes(&sig).expect("Failed To Convert To Signature For BLS");

            let is_valid: bool = bls_signatures::verify_messages(&final_sig, &vec![message_as_bytes], &[final_pk]);

            return is_valid
        }
        else {
            panic!("Cannot Read Algorithm Type")
        }
    }
    /// ## Determines Public Key Algorithm
    /// This determines the public key algorithm based on its key size (in hexadecimal) and returns a `KeypairAlgorithm` enum.
    pub fn determine_algorithm(pk: &str) -> KeypairAlgorithms {
        let length = pk.len();

        if length == 128 {
            return KeypairAlgorithms::SPHINCS_PLUS
        }
        else if length > 1500 && length < 2000 {
            return KeypairAlgorithms::FALCON512
        }
        else {
            return KeypairAlgorithms::FALCON1024
        }
    }
}

#[test]
fn generate(){
    let mut keypair = BLSKeypair::new();
    keypair.zeroize();
}