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
use std::ops::Deref; pub use sodiumoxide::crypto::sign::{self, Signature, SecretKey, PublicKey}; pub mod ring; pub use self::ring::{VerifyRing, SignRing}; mod errors { error_chain! { errors { InvalidSignature CorruptedKey } } } pub use self::errors::{Result, Error, ErrorKind}; pub fn gen_keypair() -> (PublicKey, SecretKey) { sign::gen_keypair() } pub fn sign(m: &[u8], sk: &SecretKey) -> Signature { sign::sign_detached(m, sk) } pub fn verify(sig: &Signature, m: &[u8], pk: &PublicKey) -> Result<()> { if sign::verify_detached(sig, m, pk) { Ok(()) } else { Err(ErrorKind::InvalidSignature.into()) } } pub fn to_pubkey(pk: &[u8]) -> Result<PublicKey> { match PublicKey::from_slice(pk) { Some(pk) => Ok(pk), None => Err(ErrorKind::CorruptedKey.into()), } } pub fn to_privkey(sk: &[u8]) -> Result<SecretKey> { match SecretKey::from_slice(sk) { Some(sk) => Ok(sk), None => Err(ErrorKind::CorruptedKey.into()), } } pub trait Signable { fn encode(&self) -> Vec<u8>; } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct Signed<T: Signable>(pub T, pub Signature); impl<T: Signable> Deref for Signed<T> { type Target = T; #[inline] fn deref(&self) -> &T { &self.0 } } impl<T: Signable> Signed<T> { pub fn new(inner: T, signature: Signature) -> Signed<T> { Signed(inner, signature) } pub fn encode(&self) -> Vec<u8> { let mut buf = self.encode_inner(); buf.extend(self.signature().0.iter()); buf } fn encode_inner(&self) -> Vec<u8> { self.0.encode() } pub fn inner(&self) -> &T { &self.0 } pub fn signature(&self) -> &Signature { &self.1 } pub fn verify_session(&self, pubkey: &PublicKey) -> Result<()> { verify(&self.1, &self.0.encode(), pubkey) } } #[derive(Debug, PartialEq, Eq)] pub struct Verified<T>(pub T); impl<T> Deref for Verified<T> { type Target = T; #[inline] fn deref(&self) -> &T { &self.0 } }