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
use crate::constants::*;
use crate::crypto::util::fixed_time_eq;
use crate::errors::*;
use crate::helpers::*;
use crate::keynum::*;
use std::cmp;
use std::fmt::Write as fmtWrite;
use std::fs::OpenOptions;
use std::io::{Cursor, Read};
use std::path::Path;

/// A public key and its metadata.
///
/// A `PublicKeyBox` represents a raw public key, along with a key
/// identifier and an untrusted description.
///
/// This is what usually gets exported to disk.
///
/// A `PublicKeyBox` can be directly converted to/from a single-line string.
#[derive(Clone, Debug)]
pub struct PublicKeyBox(String);

impl Into<String> for PublicKeyBox {
    fn into(self) -> String {
        self.0
    }
}

impl Into<PublicKeyBox> for String {
    fn into(self) -> PublicKeyBox {
        PublicKeyBox(self)
    }
}

impl ToString for PublicKeyBox {
    fn to_string(&self) -> String {
        self.0.to_string()
    }
}

impl Into<PublicKey> for PublicKeyBox {
    fn into(self) -> PublicKey {
        self.into_public_key().unwrap()
    }
}

impl PublicKeyBox {
    /// Create a new `PublicKeyBox` from a string.
    pub fn from_string(s: &str) -> Result<PublicKeyBox> {
        Ok(s.to_string().into())
    }

    /// Return a `PublicKeyBox` for a string, for storage.
    pub fn into_string(self) -> String {
        self.into()
    }

    /// Convert a `PublicKeyBox` to a string, for storage.
    pub fn into_public_key(self) -> Result<PublicKey> {
        PublicKey::from_box(self)
    }

    /// Return a byte representation of the public key, for storage.
    pub fn to_bytes(&self) -> Vec<u8> {
        self.to_string().as_bytes().to_vec()
    }
}

/// A `PublicKey` is used to verify signatures.
#[derive(Clone, Debug)]
pub struct PublicKey {
    pub(crate) sig_alg: [u8; TWOBYTES],
    pub(crate) keynum_pk: KeynumPK,
}

impl PublicKey {
    /// Deserialize a `PublicKey`.
    ///
    /// For storage, a `PublicKeyBox` is usually what you need instead.
    pub fn from_bytes(buf: &[u8]) -> Result<PublicKey> {
        let mut buf = Cursor::new(buf);
        let mut sig_alg = [0u8; TWOBYTES];
        let mut keynum = [0u8; KEYNUM_BYTES];
        let mut pk = [0u8; PUBLICKEY_BYTES];
        buf.read_exact(&mut sig_alg)?;
        buf.read_exact(&mut keynum)?;
        buf.read_exact(&mut pk)?;
        Ok(PublicKey {
            sig_alg,
            keynum_pk: KeynumPK { keynum, pk },
        })
    }

    /// Serialize a `PublicKey`.
    ///
    /// For storage, a `PublicKeyBox` is usually what you want to use instead.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut iters = Vec::new();
        iters.push(self.sig_alg.iter());
        iters.push(self.keynum_pk.keynum.iter());
        iters.push(self.keynum_pk.pk.iter());
        let v: Vec<u8> = iters
            .iter()
            .flat_map(|b| {
                let b = b.clone();
                b.cloned()
            })
            .collect();
        v
    }

    /// Convert a `PublicKeyBox` to a `PublicKey`.
    pub fn from_box(pk_box: PublicKeyBox) -> Result<PublicKey> {
        let s = pk_box.0;
        let mut lines = s.lines();
        lines.next().ok_or_else(|| {
            PError::new(ErrorKind::Io, "Missing comment in public key".to_string())
        })?;
        let encoded_pk = lines.next().ok_or_else(|| {
            PError::new(
                ErrorKind::Io,
                "Missing encoded key in public key".to_string(),
            )
        })?;
        if encoded_pk.len() != PK_B64_ENCODED_LEN {
            return Err(PError::new(
                ErrorKind::Io,
                "Base64 conversion failed - was an actual public key given?".to_string(),
            ));
        }
        let decoded_buf = base64::decode(encoded_pk.trim()).map_err(|e| {
            PError::new(
                ErrorKind::Io,
                format!(
                    "Base64 conversion failed - was an actual public key given?: {}",
                    e
                ),
            )
        })?;
        Ok(PublicKey::from_bytes(&decoded_buf)?)
    }

    /// Convert a `PublicKey` to a `PublicKeyBox`.
    pub fn to_box(&self) -> Result<PublicKeyBox> {
        let mut s = String::new();
        write!(s, "{}minisign public key: ", COMMENT_PREFIX)?;
        writeln!(s, "{:X}", load_u64_le(&self.keynum_pk.keynum[..]))?;
        writeln!(s, "{}", self.to_base64())?;
        Ok(s.into())
    }

    /// Create a minimal public key from a base64-encoded string.
    pub fn from_base64(pk_string: &str) -> Result<PublicKey> {
        let encoded_string = pk_string.to_string();
        if encoded_string.trim().len() != PK_B64_ENCODED_LEN {
            return Err(PError::new(
                ErrorKind::Io,
                "base64 conversion failed - was an actual public key given?".to_string(),
            ));
        }
        let decoded_string = base64::decode(encoded_string.as_bytes()).map_err(|e| {
            PError::new(
                ErrorKind::Io,
                format!(
                    "base64 conversion failed - was an actual public key given?: {}",
                    e
                ),
            )
        })?;
        PublicKey::from_bytes(&decoded_string)
    }

    /// Encode a public key as a base64-encoded string.
    pub fn to_base64(&self) -> String {
        base64::encode(self.to_bytes().as_slice())
    }

    /// Load a `PublicKeyBox` from a file, and returns a `PublicKey` from it.
    pub fn from_file<P>(pk_path: P) -> Result<PublicKey>
    where
        P: AsRef<Path>,
    {
        let pk_path = pk_path.as_ref();
        let mut file = OpenOptions::new().read(true).open(pk_path).map_err(|e| {
            PError::new(
                ErrorKind::Io,
                format!(
                    "couldn't retrieve public key from {}: {}",
                    pk_path.display(),
                    e
                ),
            )
        })?;
        let mut s = String::new();
        file.read_to_string(&mut s)?;
        PublicKey::from_box(s.into())
    }
}

impl cmp::PartialEq for PublicKey {
    fn eq(&self, other: &PublicKey) -> bool {
        fixed_time_eq(&self.keynum_pk.pk, &other.keynum_pk.pk)
    }
}

impl cmp::Eq for PublicKey {}