├── .gitignore ├── examples ├── props │ ├── data.txt │ ├── sig.txt │ └── key.txt ├── print.rs ├── round_trip.rs ├── read_sig.rs └── verify_sig.rs ├── Cargo.toml ├── README.md ├── LICENSE-MIT ├── src ├── packet.rs ├── lib.rs ├── ascii_armor.rs ├── key.rs └── sig.rs ├── CODE_OF_CONDUCT.md └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /examples/props/data.txt: -------------------------------------------------------------------------------- 1 | tree 01ea054cde7d42a706d3e1734014e4c2aadd2a3b 2 | parent 170bc1aece1c5dc0c9e02150fbc430750a90ef8e 3 | author Without Boats 1512095290 -0800 4 | committer Without Boats 1512095290 -0800 5 | 6 | Update README. 7 | -------------------------------------------------------------------------------- /examples/props/sig.txt: -------------------------------------------------------------------------------- 1 | -----BEGIN PGP SIGNATURE----- 2 | 3 | iHUEABYIAB0WIQS2NbX7Xtnqc/lTXwocxwMQvjkS1QUCWiC+PgAKCRAcxwMQvjkS 4 | 1Y5IAQDNk4Bu4sCAHTlvUSS9ioOo9yWDqIvliE1aBvZeZCzDLgEAgQSsQtP8Rqq/ 5 | f+SHxLV2cgZpFLcKEIg0odi8Uxv4WAk= 6 | =uBdw 7 | -----END PGP SIGNATURE----- 8 | -------------------------------------------------------------------------------- /examples/props/key.txt: -------------------------------------------------------------------------------- 1 | -----BEGIN PGP PUBLIC KEY BLOCK----- 2 | 3 | mDMEWh36qhYJKwYBBAHaRw8BAQdAOHEGR6r6ulmlAiaaH4e+OHzhxLrDX7S5GXZZ 4 | HJwDLze0IHdpdGhvdXRib2F0cyA8Ym9hdHNAbW96aWxsYS5jb20+iJAEExYIADgW 5 | IQS2NbX7Xtnqc/lTXwocxwMQvjkS1QUCWh36qgIbAwULCQgHAgYVCAkKCwIEFgID 6 | AQIeAQIXgAAKCRAcxwMQvjkS1RPlAP48cIZPgy6wPlfydr8CoPMEYy9n9grbmCDw 7 | KxxTmKyWHAD+LZiHpQ3LCYuUidQYYbr/+4GhtuJUNLiIbSwxtgBdVAQ= 8 | =P0tw 9 | -----END PGP PUBLIC KEY BLOCK----- 10 | -------------------------------------------------------------------------------- /examples/print.rs: -------------------------------------------------------------------------------- 1 | extern crate rand; 2 | extern crate sha2; 3 | extern crate ed25519_dalek as dalek; 4 | extern crate pbp; 5 | 6 | use rand::OsRng; 7 | use sha2::{Sha256, Sha512}; 8 | use dalek::Keypair; 9 | use pbp::{PgpKey, KeyFlags}; 10 | 11 | fn main() { 12 | let mut cspring = OsRng::new().unwrap(); 13 | let keypair = Keypair::generate::(&mut cspring); 14 | 15 | let key = PgpKey::from_dalek::(&keypair, KeyFlags::NONE, "withoutboats"); 16 | println!("{}", key); 17 | } 18 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | cargo-features = ["edition"] 2 | 3 | [package] 4 | authors = ["Without Boats "] 5 | description = "bridge non-PGP system to PGP data format" 6 | edition = "2018" 7 | license = "MIT OR Apache-2.0" 8 | readme = "README.md" 9 | name = "pbp" 10 | version = "0.4.0" 11 | repository = "https://github.com/withoutboats/pbp" 12 | 13 | [dependencies] 14 | base64 = "0.9.2" 15 | byteorder = "1.1.0" 16 | digest = "0.7.0" 17 | sha1 = "0.2.0" 18 | typenum = "1.9.0" 19 | failure = "0.1.1" 20 | bitflags = "1.0.1" 21 | 22 | [dependencies.ed25519-dalek] 23 | version = "0.7.0" 24 | optional = true 25 | 26 | [features] 27 | dalek = ["ed25519-dalek"] 28 | 29 | [dev-dependencies] 30 | rand = "0.5.4" 31 | sha2 = "0.6.0" 32 | -------------------------------------------------------------------------------- /examples/round_trip.rs: -------------------------------------------------------------------------------- 1 | extern crate rand; 2 | extern crate sha2; 3 | extern crate ed25519_dalek as dalek; 4 | extern crate pbp; 5 | 6 | use rand::OsRng; 7 | use sha2::{Sha256, Sha512}; 8 | use dalek::Keypair; 9 | use pbp::{PgpKey, PgpSig, SigType, KeyFlags}; 10 | 11 | const DATA: &[u8] = b"How will I ever get out of this labyrinth?"; 12 | 13 | fn main() { 14 | let mut cspring = OsRng::new().unwrap(); 15 | let keypair = Keypair::generate::(&mut cspring); 16 | 17 | let key = PgpKey::from_dalek::(&keypair, KeyFlags::SIGN, "withoutboats"); 18 | let sig = PgpSig::from_dalek::(&keypair, DATA, key.fingerprint(), SigType::BinaryDocument); 19 | if sig.verify_dalek::(DATA, &keypair.public) { 20 | println!("Verified successfully."); 21 | } else { 22 | println!("Could not verify."); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /examples/read_sig.rs: -------------------------------------------------------------------------------- 1 | extern crate rand; 2 | extern crate sha2; 3 | extern crate ed25519_dalek as dalek; 4 | extern crate pbp; 5 | 6 | use std::io::{self, BufRead}; 7 | 8 | use pbp::PgpSig; 9 | 10 | fn main() { 11 | let stdin = io::stdin(); 12 | let mut stdin = stdin.lock(); 13 | 14 | let mut armor = String::new(); 15 | 16 | let mut in_armor = false; 17 | 18 | loop { 19 | let mut buf = String::new(); 20 | stdin.read_line(&mut buf).unwrap(); 21 | if buf.trim().starts_with("-----") && buf.trim().ends_with("-----") { 22 | armor.push_str(&buf); 23 | if in_armor { break } 24 | else { in_armor = true; } 25 | } else if in_armor { 26 | armor.push_str(&buf); 27 | } 28 | } 29 | 30 | if PgpSig::from_ascii_armor(&armor).is_some() { 31 | println!("Valid PGP Signature"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /examples/verify_sig.rs: -------------------------------------------------------------------------------- 1 | #![feature(fs_read_write)] 2 | 3 | extern crate pbp; 4 | extern crate sha2; 5 | 6 | use std::env; 7 | use std::fs; 8 | use std::path::PathBuf; 9 | 10 | use sha2::{Sha256, Sha512}; 11 | use pbp::{PgpKey, PgpSig}; 12 | 13 | fn main() { 14 | let root = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); 15 | let props = root.join("examples").join("props"); 16 | 17 | let sig: String = fs::read_string(props.join("sig.txt")).unwrap(); 18 | let key: String = fs::read_string(props.join("key.txt")).unwrap(); 19 | let data: String = fs::read_string(props.join("data.txt")).unwrap(); 20 | 21 | let sig = PgpSig::from_ascii_armor(&sig).unwrap(); 22 | let key = PgpKey::from_ascii_armor(&key).unwrap(); 23 | 24 | if sig.verify_dalek::(data.as_bytes(), &key.to_dalek().unwrap()) { 25 | println!("Verified signature."); 26 | } else { 27 | println!("Could not verify signature."); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pbp - Pretty Bad Protocol 2 | 3 | This crate lets you generate OpenPGP datagrams from ed25519 keys and 4 | signatures; it is intended to bridge from a non-PGP system to a transport 5 | medium that expects PGP data. 6 | 7 | ```rust 8 | fn print_key(keypair: KeyPair) { 9 | let pgp_key = PgpKey::new(&keypair.public[..], "user id string", |data| { 10 | keypair.sign(data).to_bytes() 11 | }); 12 | println!("{}", pgp_key); 13 | } 14 | ``` 15 | 16 | It's agnostic about what library you use to implement ed25519, but it has a 17 | feature which integrates with [ed25519-dalek][dalek] 18 | 19 | Thanks to isis lovecruft and Henry de Valence for assistance with the dalek API 20 | and understanding the OpenPGP specification. 21 | 22 | ## Demonstration 23 | 24 | The "print" example prints an ASCII armored OpenPGP public key to stdout; you 25 | can check that using: 26 | 27 | ``` 28 | $ cargo run --features dalek --example print 29 | ``` 30 | 31 | [dalek]: https://github.com/isislovecruft/ed25519-dalek 32 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /src/packet.rs: -------------------------------------------------------------------------------- 1 | use std::ops::Range; 2 | use std::u16; 3 | 4 | use byteorder::{ByteOrder, BigEndian}; 5 | 6 | pub(crate) type BigEndianU32 = [u8; 4]; 7 | pub(crate) type BigEndianU16 = [u8; 2]; 8 | 9 | pub(crate) fn write_packet)>(data: &mut Vec, tag: u8, write: F) -> Range { 10 | let init = data.len(); 11 | let header_tag = (tag << 2) | 0b_1000_0001; 12 | data.extend(&[header_tag, 0, 0]); 13 | write(data); 14 | let len = data.len() - init - 3; 15 | assert!(len < u16::MAX as usize); 16 | BigEndian::write_u16(&mut data[(init+1)..(init+3)], len as u16); 17 | init..data.len() 18 | } 19 | 20 | pub(crate) fn prepare_packet)>(tag: u8, write: F) -> Vec { 21 | let mut packet = vec![0, 0, 0]; 22 | write(&mut packet); 23 | packet[0] = (tag << 2) | 0b_1000_0001; 24 | let len = packet.len() - 3; 25 | BigEndian::write_u16(&mut packet[1..3], len as u16); 26 | packet 27 | } 28 | 29 | pub(crate) fn write_subpackets(packet: &mut Vec, write_each_subpacket: F) where 30 | F: Fn(&mut Vec) 31 | { 32 | packet.extend(&[0, 0]); 33 | let init = packet.len(); 34 | write_each_subpacket(packet); 35 | let len = packet.len() - init; 36 | assert!(len < u16::MAX as usize); 37 | BigEndian::write_u16(&mut packet[(init - 2)..init], len as u16); 38 | } 39 | 40 | pub(crate) fn write_single_subpacket)>(packet: &mut Vec, tag: u8, write: F) { 41 | packet.extend(&[0, tag]); 42 | let init = packet.len() - 1; 43 | write(packet); 44 | let len = packet.len() - init; 45 | assert!(len < 191); 46 | packet[init - 1] = len as u8; 47 | } 48 | 49 | pub(crate) fn write_mpi(data: &mut Vec, mpi: &[u8]) { 50 | assert!(mpi.len() < (u16::MAX / 8) as usize); 51 | assert!(mpi.len() > 0); 52 | let len = bigendian_u16((mpi.len() * 8 - (mpi[0].leading_zeros() as usize)) as u16); 53 | data.extend(&len); 54 | data.extend(mpi); 55 | } 56 | 57 | pub(crate) fn bigendian_u32(data: u32) -> BigEndianU32 { 58 | let mut out = BigEndianU32::default(); 59 | BigEndian::write_u32(&mut out, data); 60 | out 61 | } 62 | 63 | pub(crate) fn bigendian_u16(data: u16) -> BigEndianU16 { 64 | let mut out = BigEndianU16::default(); 65 | BigEndian::write_u16(&mut out, data); 66 | out 67 | } 68 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This library is designed to integrate non-PGP generated and verified keys 2 | //! and signatures with channels that expect PGP data. It specifically only 3 | //! supports the ed25519 signature scheme. 4 | //! 5 | //! Sometimes you want to be able to sign data, and the only reasonable channel 6 | //! to transmit signatures and public keys available to you expects them to be 7 | //! PGP formatted. If you don't want to use a heavyweight dependency like gpg, 8 | //! this library supports only the minimal necessary components of the PGP 9 | //! format to transmit your keys and signatures. 10 | #![feature(rust_2018_preview)] 11 | #![deny(missing_docs, missing_debug_implementations)] 12 | 13 | #[macro_use] extern crate failure; 14 | #[macro_use] extern crate bitflags; 15 | 16 | #[cfg(feature = "dalek")] 17 | extern crate ed25519_dalek as dalek; 18 | 19 | mod ascii_armor; 20 | mod packet; 21 | 22 | mod key; 23 | mod sig; 24 | 25 | pub use crate::key::PgpKey; 26 | pub use crate::sig::{PgpSig, SubPacket, SigType}; 27 | 28 | /// An OpenPGP public key fingerprint. 29 | pub type Fingerprint = [u8; 20]; 30 | /// An ed25519 signature. 31 | pub type Signature = [u8; 64]; 32 | 33 | bitflags! { 34 | /// The key flags assigned to this key. 35 | pub struct KeyFlags: u8 { 36 | /// No key flags. 37 | const NONE = 0x00; 38 | /// The Certify flag. 39 | const CERTIFY = 0x01; 40 | /// The Sign flag. 41 | const SIGN = 0x02; 42 | /// The Encrypt Communication flag. 43 | const ENCRYPT_COMS = 0x04; 44 | /// The Encrypt Storage flag. 45 | const ENCRYPT_STORAGE = 0x08; 46 | /// The Authentication flag. 47 | const AUTHENTICATION = 0x20; 48 | } 49 | } 50 | 51 | /// An error returned while attempting to parse a PGP signature or public key. 52 | #[derive(Fail, Debug)] 53 | pub enum PgpError { 54 | /// Invalid ASCII armor format 55 | #[fail(display = "Invalid ASCII armor format")] 56 | InvalidAsciiArmor, 57 | /// Packet header incorrectly formatted 58 | #[fail(display = "Packet header incorrectly formatted")] 59 | InvalidPacketHeader, 60 | /// Unsupported packet length format 61 | #[fail(display = "Unsupported packet length format")] 62 | UnsupportedPacketLength, 63 | /// Unsupported form of signature packet 64 | #[fail(display = "Unsupported form of signature packet")] 65 | UnsupportedSignaturePacket, 66 | /// First hashed subpacket of signature must be the key fingerprint 67 | #[fail(display = "First hashed subpacket of signature must be the key fingerprint")] 68 | MissingFingerprintSubpacket, 69 | /// Unsupported form of public key packet 70 | #[fail(display = "Unsupported form of public key packet")] 71 | UnsupportedPublicKeyPacket, 72 | } 73 | 74 | // Helper for writing base64 data 75 | struct Base64<'a>(&'a [u8]); 76 | 77 | impl<'a> std::fmt::Debug for Base64<'a> { 78 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 79 | f.write_str(&base64::encode(self.0)) 80 | } 81 | } 82 | 83 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at boats@mozilla.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /src/ascii_armor.rs: -------------------------------------------------------------------------------- 1 | // This module implements the ASCII armoring required by the OpenPGP 2 | // specification, converting binary PGP datagrams into ASCII data. 3 | use std::fmt; 4 | 5 | use base64; 6 | use byteorder::{BigEndian, ByteOrder}; 7 | 8 | use crate::PgpError; 9 | use crate::PgpError::InvalidAsciiArmor; 10 | 11 | impl From for PgpError { 12 | fn from(_: base64::DecodeError) -> PgpError { 13 | InvalidAsciiArmor 14 | } 15 | } 16 | 17 | // Convert from an ASCII armored string into binary data. 18 | pub fn remove_ascii_armor(s: &str, expected_header: &str, expected_footer: &str) -> Result, PgpError> { 19 | let lines: Vec<&str> = s.lines().map(|s| s.trim()).collect(); 20 | let header = lines.first().ok_or(InvalidAsciiArmor)?; 21 | let footer = lines.last().ok_or(InvalidAsciiArmor)?; 22 | 23 | // Check header and footer 24 | if !header.starts_with("-----") 25 | || !footer.starts_with("-----") 26 | || !header.ends_with("-----") 27 | || !footer.ends_with("-----") 28 | || header.trim_matches('-').trim() != expected_header 29 | || footer.trim_matches('-').trim() != expected_footer 30 | { 31 | return Err(InvalidAsciiArmor) 32 | } 33 | 34 | // Find the end of the header section 35 | let end_of_headers = 1 + lines.iter().take_while(|l| !l.is_empty()).count(); 36 | if end_of_headers >= lines.len() - 2 { return Err(InvalidAsciiArmor) } 37 | 38 | // Decode the base64'd data 39 | let ascii_armored: String = lines[end_of_headers..lines.len() - 2].concat(); 40 | let data = base64::decode(&ascii_armored)?; 41 | 42 | // Confirm checksum 43 | let cksum_line = &lines[lines.len() - 2]; 44 | if !cksum_line.starts_with("=") || !cksum_line.len() > 1 { 45 | return Err(InvalidAsciiArmor) 46 | } 47 | let mut cksum = [0; 4]; 48 | base64::decode_config_slice(&cksum_line[1..], base64::STANDARD, &mut cksum[..])?; 49 | if BigEndian::read_u32(&cksum[..]) != checksum_crc24(&data) { 50 | return Err(InvalidAsciiArmor) 51 | } 52 | 53 | Ok(data) 54 | } 55 | 56 | // Ascii armors data into the formatter 57 | pub fn ascii_armor( 58 | header: &'static str, 59 | footer: &'static str, 60 | data: &[u8], 61 | f: &mut fmt::Formatter 62 | ) -> fmt::Result 63 | { 64 | // Header Line 65 | f.write_str("-----")?; 66 | f.write_str(header)?; 67 | f.write_str("-----\n\n")?; 68 | 69 | // Base64'd data 70 | let b64_cfg = base64::Config::new( 71 | base64::CharacterSet::Standard, 72 | true, 73 | false, 74 | base64::LineWrap::Wrap(76, base64::LineEnding::LF), 75 | ); 76 | f.write_str(&base64::encode_config(data, b64_cfg))?; 77 | f.write_str("\n=")?; 78 | 79 | // Checksum 80 | let cksum = checksum_crc24(data); 81 | let mut cksum_buf = [0; 4]; 82 | BigEndian::write_u32(&mut cksum_buf, cksum); 83 | f.write_str(&base64::encode(&cksum_buf[1..4]))?; 84 | 85 | // Footer Line 86 | f.write_str("\n-----")?; 87 | f.write_str(footer)?; 88 | f.write_str("-----\n")?; 89 | 90 | Ok(()) 91 | } 92 | 93 | // Translation of checksum function from RFC 4880, section 6.1. 94 | fn checksum_crc24(data: &[u8]) -> u32 { 95 | const CRC24_INIT: u32 = 0x_00B7_04CE; 96 | const CRC24_POLY: u32 = 0x_0186_4CFB; 97 | 98 | let mut crc = CRC24_INIT; 99 | 100 | for &byte in data { 101 | crc ^= (byte as u32) << 16; 102 | 103 | for _ in 0..8 { 104 | 105 | crc <<= 1; 106 | 107 | if (crc & 0x_0100_0000) != 0 { 108 | crc ^= CRC24_POLY; 109 | } 110 | } 111 | } 112 | 113 | crc & 0x_00FF_FFFF 114 | } 115 | -------------------------------------------------------------------------------- /src/key.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{self, Display, Debug}; 2 | use std::ops::Range; 3 | use std::str::FromStr; 4 | use std::u16; 5 | 6 | use byteorder::{ByteOrder, BigEndian}; 7 | use digest::Digest; 8 | use sha1::Sha1; 9 | use typenum::U32; 10 | 11 | #[cfg(feature = "dalek")] use ed25519_dalek as dalek; 12 | #[cfg(feature = "dalek")] use typenum::U64; 13 | 14 | use crate::ascii_armor::{ascii_armor, remove_ascii_armor}; 15 | use crate::Base64; 16 | use crate::packet::*; 17 | 18 | use crate::{Fingerprint, Signature, KeyFlags}; 19 | use crate::{PgpSig, SubPacket, SigType}; 20 | use crate::PgpError; 21 | 22 | // curve identifier (curve25519) 23 | const CURVE: &[u8] = &[ 24 | 0x09, 0x2b, 0x06, 0x01, 25 | 0x04, 0x01, 0xda, 0x47, 26 | 0x0f, 0x01 27 | ]; 28 | 29 | /// An OpenPGP formatted ed25519 public key. 30 | /// 31 | /// This allows you to transmit an ed25519 key as a PGP key. Though gpg 32 | /// and other implementations will probably be willing to import this 33 | /// public key, it is not designed for use within the PGP ecosystem, but 34 | /// rather to transfer public key data through mediums in which an OpenPGP 35 | /// formatted key is expected. 36 | /// 37 | /// This type implements Display by ASCII armoring the public key data. 38 | #[derive(Eq, PartialEq, Hash)] 39 | pub struct PgpKey { 40 | data: Vec, 41 | } 42 | 43 | impl PgpKey { 44 | /// Construct a PgpKey from an ed25519 public key. 45 | /// 46 | /// This will construct a valid OpenPGP Public Key datagram with the 47 | /// following packets: 48 | /// 49 | /// - A public key packet (formatted according to the "EdDSA for OpenPGP" 50 | /// extension draft) 51 | /// - A user id (whatever string you pass as the user id argument) 52 | /// - A self-signature 53 | /// 54 | /// The sign function must be a valid function for signing data with the 55 | /// private key paired with the public key. You are required to provide 56 | /// this so that you don't have to trust this library with direct access 57 | /// to the private key. 58 | /// 59 | /// # Warnings 60 | /// 61 | /// This will panic if your key is not 32 bits of data. It will not 62 | /// otherwise verify that your key is a valid ed25519 key. 63 | pub fn new( 64 | key: &[u8], 65 | flags: KeyFlags, 66 | user_id: &str, 67 | unix_time: u32, 68 | sign: F, 69 | ) -> PgpKey where 70 | Sha256: Digest, 71 | F: Fn(&[u8]) -> Signature, 72 | { 73 | assert!(key.len() == 32); 74 | 75 | let mut data = Vec::with_capacity(user_id.len() + 180); 76 | 77 | let key_packet_range = write_public_key_packet(&mut data, key, unix_time); 78 | let fingerprint = fingerprint(&data[key_packet_range.clone()]); 79 | write_user_id_packet(&mut data, user_id); 80 | 81 | let sig_data = { 82 | let mut data = Vec::from(&data[key_packet_range]); 83 | data.extend(&[0xb4]); 84 | data.extend(&bigendian_u32(user_id.len() as u32)); 85 | data.extend(user_id.as_bytes()); 86 | data 87 | }; 88 | 89 | let signature_packet = PgpSig::new::( 90 | &sig_data, 91 | fingerprint, 92 | SigType::PositiveCertification, 93 | unix_time, 94 | &[ 95 | SubPacket { tag: 27, data: &[flags.bits()] }, 96 | SubPacket { tag: 23, data: &[0x80] }, 97 | ], 98 | sign, 99 | ); 100 | 101 | data.extend(signature_packet.as_bytes()); 102 | 103 | PgpKey { data } 104 | } 105 | 106 | /// Construct a PgpKey struct from an OpenPGP public key. 107 | /// 108 | /// This does minimal verification of the data received. it ensures that 109 | /// the initial portion of the data is an OpenPGP public key packet, 110 | /// formatted to contain an ed25519 public key. It does not ensure that 111 | /// the actual public key is a valid ed25519 key, and no verification is 112 | /// done on the remainder of the data. 113 | /// 114 | /// As a result, a key constructed this way many not successfully import 115 | /// into an OpenPGP implementation like gpg. 116 | pub fn from_bytes(bytes: &[u8]) -> Result { 117 | let (packet_data, end) = find_public_key_packet(bytes)?; 118 | 119 | // Validate that this is a version 4 curve25519 EdDSA key. 120 | if !is_ed25519_valid(packet_data) { 121 | return Err(PgpError::UnsupportedPublicKeyPacket); 122 | } 123 | 124 | // convert public key packet to the old style header, 125 | // two byte length. All methods on PgpKey assume the 126 | // public key is in that format (e.g. the fingerprint 127 | // method). 128 | let data = if bytes[0] != 0x99 { 129 | let mut packet = prepare_packet(6, |packet| packet.extend(packet_data)); 130 | packet.extend(&bytes[end..]); 131 | packet 132 | } else { bytes.to_owned() }; 133 | 134 | Ok(PgpKey { data }) 135 | } 136 | 137 | /// Construct a PgpKey from an ASCII armored string. 138 | pub fn from_ascii_armor(string: &str) -> Result { 139 | let data = remove_ascii_armor(string, "BEGIN PGP PUBLIC KEY BLOCK", "END PGP PUBLIC KEY BLOCK")?; 140 | PgpKey::from_bytes(&data) 141 | } 142 | 143 | /// The ed25519 public key data contained in this key. 144 | /// 145 | /// This slice will be thirty-two bytes long. 146 | pub fn key_data(&self) -> &[u8] { 147 | &self.data[22..54] 148 | } 149 | 150 | /// All of the bytes in this key (including PGP metadata). 151 | pub fn as_bytes(&self) -> &[u8] { 152 | &self.data[..] 153 | } 154 | 155 | /// The OpenPGP fingerprint of this public key. 156 | pub fn fingerprint(&self) -> Fingerprint { 157 | fingerprint(&self.data[0..54]) 158 | } 159 | 160 | #[cfg(feature = "dalek")] 161 | /// Create a PgpKey from a dalek Keypair and a user_id string. 162 | pub fn from_dalek(keypair: &dalek::Keypair, flags: KeyFlags, unix_time: u32, user_id: &str) -> PgpKey 163 | where 164 | Sha256: Digest, 165 | Sha512: Digest, 166 | { 167 | PgpKey::new::(keypair.public.as_bytes(), flags, user_id, unix_time, |data| { 168 | keypair.sign::(data).to_bytes() 169 | }) 170 | } 171 | 172 | #[cfg(feature = "dalek")] 173 | /// Convert this key into a dalek PublicKey. 174 | /// 175 | /// This will validate that the key data is a correct ed25519 public key. 176 | pub fn to_dalek(&self) -> Result { 177 | dalek::PublicKey::from_bytes(self.key_data()) 178 | } 179 | } 180 | 181 | impl Debug for PgpKey { 182 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 183 | f.debug_struct("PgpKey").field("key", &Base64(&self.data[..])).finish() 184 | } 185 | } 186 | 187 | impl Display for PgpKey { 188 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 189 | ascii_armor( 190 | "BEGIN PGP PUBLIC KEY BLOCK", 191 | "END PGP PUBLIC KEY BLOCK", 192 | &self.data[..], 193 | f, 194 | ) 195 | } 196 | } 197 | 198 | impl FromStr for PgpKey { 199 | type Err = PgpError; 200 | fn from_str(s: &str) -> Result { 201 | PgpKey::from_ascii_armor(s) 202 | } 203 | } 204 | 205 | fn write_public_key_packet(data: &mut Vec, key: &[u8], unix_time: u32) -> Range { 206 | write_packet(data, 6, |packet| { 207 | packet.push(4); // packet version #4 208 | packet.extend(&bigendian_u32(unix_time)); 209 | packet.push(22); // algorithm id #22 (edDSA) 210 | 211 | packet.extend(CURVE); 212 | 213 | let mut key_data = Vec::with_capacity(33); 214 | key_data.push(0x40); 215 | key_data.extend(key); 216 | write_mpi(packet, &key_data); 217 | }) 218 | } 219 | 220 | fn write_user_id_packet(data: &mut Vec, user_id: &str) -> Range { 221 | write_packet(data, 13, |packet| packet.extend(user_id.as_bytes())) 222 | } 223 | 224 | // Mainly this function parses the possible packet headers. 225 | // If the data begins with a valid old public key packet using 226 | // anything but the indeterminate length header format, it 227 | // will return the data of that public key packet. 228 | fn find_public_key_packet(data: &[u8]) -> Result<(&[u8], usize), PgpError> { 229 | let (init, len) = match data.first() { 230 | Some(&0x98) => { 231 | if data.len() < 2 { return Err(PgpError::InvalidPacketHeader) } 232 | let len = data[1] as usize; 233 | (2, len) 234 | } 235 | Some(&0x99) => { 236 | if data.len() < 3 { return Err(PgpError::InvalidPacketHeader) } 237 | let len = BigEndian::read_u16(&data[1..3]) as usize; 238 | (3, len) 239 | } 240 | Some(&0x9a) => { 241 | if data.len() < 5 { return Err(PgpError::InvalidPacketHeader) } 242 | let len = BigEndian::read_u32(&data[1..5]) as usize; 243 | if len > u16::MAX as usize { return Err(PgpError::UnsupportedPacketLength) } 244 | (5, len) 245 | } 246 | _ => return Err(PgpError::UnsupportedPacketLength) 247 | }; 248 | let end = init + len; 249 | if data.len() < end { return Err(PgpError::InvalidPacketHeader) } 250 | Ok((&data[init..end], end)) 251 | } 252 | 253 | fn fingerprint(key_packet: &[u8]) -> [u8; 20] { 254 | let mut hasher = Sha1::new(); 255 | hasher.update(key_packet); 256 | hasher.digest().bytes() 257 | } 258 | 259 | fn is_ed25519_valid(packet: &[u8]) -> bool { 260 | packet.len() == 51 261 | && packet[0] == 0x04 262 | && packet[5] == 0x16 263 | && &packet[6..16] == CURVE 264 | && &packet[16..19] == &[0x01, 0x07, 0x40] 265 | } 266 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/sig.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{self, Display, Debug}; 2 | use std::str::FromStr; 3 | use std::u16; 4 | 5 | use byteorder::{ByteOrder, BigEndian}; 6 | use digest::Digest; 7 | use typenum::U32; 8 | 9 | #[cfg(feature = "dalek")] use ed25519_dalek as dalek; 10 | #[cfg(feature = "dalek")] use typenum::U64; 11 | 12 | use crate::ascii_armor::{ascii_armor, remove_ascii_armor}; 13 | use crate::Base64; 14 | use crate::packet::*; 15 | use crate::{Fingerprint, Signature}; 16 | use crate::PgpError; 17 | 18 | /// The valid types of OpenPGP signatures. 19 | #[allow(missing_docs)] 20 | #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] 21 | pub enum SigType { 22 | BinaryDocument = 0x00, 23 | TextDocument = 0x01, 24 | Standalone = 0x02, 25 | GenericCertification = 0x10, 26 | PersonaCertification = 0x11, 27 | CasualCertification = 0x12, 28 | PositiveCertification = 0x13, 29 | SubkeyBinding = 0x18, 30 | PrimaryKeyBinding = 0x19, 31 | DirectlyOnKey = 0x1F, 32 | KeyRevocation = 0x20, 33 | SubkeyRevocation = 0x28, 34 | CertificationRevocation = 0x30, 35 | Timestamp = 0x40, 36 | ThirdPartyConfirmation = 0x50, 37 | } 38 | 39 | /// A subpacket to be hashed into the signed data. 40 | /// 41 | /// See RFC 4880 for more information. 42 | #[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Debug)] 43 | pub struct SubPacket<'a> { 44 | /// The tag for this subpacket. 45 | pub tag: u8, 46 | /// The data in this subpacket. 47 | pub data: &'a [u8], 48 | } 49 | 50 | /// An OpenPGP formatted ed25519 signature. 51 | #[derive(Eq, PartialEq, Hash)] 52 | pub struct PgpSig { 53 | data: Vec, 54 | } 55 | 56 | impl PgpSig { 57 | /// Construct a new PGP signature. 58 | /// 59 | /// This will construct a valid OpenPGP signature using the ed25519 60 | /// signing algorithm & SHA-256 hashing algorithm. It will contain 61 | /// these hashed subpackets: 62 | /// - A version 4 key fingerprint 63 | /// - A timestamp 64 | /// - Whatever subpackets you pass as arguments 65 | /// 66 | /// It will contain the key id as an unhashed subpacket. 67 | pub fn new( 68 | data: &[u8], 69 | fingerprint: Fingerprint, 70 | sig_type: SigType, 71 | unix_time: u32, 72 | subpackets: &[SubPacket], 73 | sign: F 74 | ) -> PgpSig 75 | where 76 | Sha256: Digest, 77 | F: Fn(&[u8]) -> Signature, 78 | { 79 | let data = prepare_packet(2, |packet| { 80 | packet.push(4); // version number 81 | packet.push(sig_type as u8); // signature class 82 | packet.push(22); // signing algorithm (EdDSA) 83 | packet.push(8); // hash algorithm (SHA-256) 84 | 85 | write_subpackets(packet, |hashed_subpackets| { 86 | // fingerprint 87 | write_single_subpacket(hashed_subpackets, 33, |packet| { 88 | packet.push(4); 89 | packet.extend(&fingerprint); 90 | }); 91 | 92 | // timestamp 93 | write_single_subpacket(hashed_subpackets, 2, |packet| packet.extend(&bigendian_u32(unix_time))); 94 | 95 | for &SubPacket { tag, data } in subpackets { 96 | write_single_subpacket(hashed_subpackets, tag, |packet| packet.extend(data)); 97 | } 98 | }); 99 | 100 | let hash = { 101 | let mut hasher = Sha256::default(); 102 | 103 | hasher.process(data); 104 | 105 | hasher.process(&packet[3..]); 106 | 107 | hasher.process(&[0x04, 0xff]); 108 | hasher.process(&bigendian_u32((packet.len() - 3) as u32)); 109 | 110 | hasher.fixed_result() 111 | }; 112 | 113 | write_subpackets(packet, |unhashed_subpackets| { 114 | write_single_subpacket(unhashed_subpackets, 16, |packet| { 115 | packet.extend(&fingerprint[12..]); 116 | }); 117 | }); 118 | 119 | packet.extend(&hash[0..2]); 120 | 121 | let signature = sign(&hash[..]); 122 | write_mpi(packet, &signature[00..32]); 123 | write_mpi(packet, &signature[32..64]); 124 | }); 125 | 126 | PgpSig { data } 127 | } 128 | 129 | /// Parse an OpenPGP signature from binary data. 130 | /// 131 | /// This must be an ed25519 signature using SHA-256 for hashing, 132 | /// and it must be in the subset of OpenPGP supported by this library. 133 | pub fn from_bytes(bytes: &[u8]) -> Result { 134 | // TODO: convert to three byte header 135 | let (data, packet) = find_signature_packet(bytes)?; 136 | has_correct_structure(packet)?; 137 | has_correct_hashed_subpackets(packet)?; 138 | Ok(PgpSig { data }) 139 | } 140 | 141 | /// Parse an OpenPGP signature from ASCII armored data. 142 | pub fn from_ascii_armor(string: &str) -> Result { 143 | let data = remove_ascii_armor(string, "BEGIN PGP SIGNATURE", "END PGP SIGNATURE")?; 144 | PgpSig::from_bytes(&data) 145 | } 146 | 147 | /// Get the binary representation of this signature. 148 | pub fn as_bytes(&self) -> &[u8] { 149 | &self.data 150 | } 151 | 152 | /// Get the portion of this signature hashed into the signed data. 153 | pub fn hashed_section(&self) -> &[u8] { 154 | let subpackets_len = BigEndian::read_u16(&self.data[7..9]) as usize; 155 | &self.data[3..(subpackets_len + 9)] 156 | } 157 | 158 | /// Get the actual ed25519 signature contained. 159 | pub fn signature(&self) -> Signature { 160 | let init = self.data.len() - 68; 161 | let sig_data = &self.data[init..]; 162 | let mut sig = [0; 64]; 163 | sig[00..32].clone_from_slice(&sig_data[02..34]); 164 | sig[32..64].clone_from_slice(&sig_data[36..68]); 165 | sig 166 | } 167 | 168 | /// Get the fingerprint of the public key which made this signature. 169 | pub fn fingerprint(&self) -> Fingerprint { 170 | let mut fingerprint = [0; 20]; 171 | fingerprint.clone_from_slice(&self.data[10..30]); 172 | fingerprint 173 | } 174 | 175 | /// Get the type of this signature. 176 | pub fn sig_type(&self) -> SigType { 177 | match self.data[4] { 178 | 0x00 => SigType::BinaryDocument, 179 | 0x01 => SigType::TextDocument, 180 | 0x02 => SigType::Standalone, 181 | 0x10 => SigType::GenericCertification, 182 | 0x11 => SigType::PersonaCertification, 183 | 0x12 => SigType::CasualCertification, 184 | 0x13 => SigType::PositiveCertification, 185 | 0x18 => SigType::SubkeyBinding, 186 | 0x19 => SigType::PrimaryKeyBinding, 187 | 0x1F => SigType::DirectlyOnKey, 188 | 0x20 => SigType::KeyRevocation, 189 | 0x28 => SigType::SubkeyRevocation, 190 | 0x30 => SigType::CertificationRevocation, 191 | 0x40 => SigType::Timestamp, 192 | 0x50 => SigType::ThirdPartyConfirmation, 193 | _ => panic!("Unrecognized signature type."), 194 | } 195 | } 196 | 197 | /// Verify data against this signature. 198 | /// 199 | /// The data to be verified should be inputed by hashing it into the 200 | /// SHA-256 hasher using the input function. 201 | pub fn verify(&self, input: F1, verify: F2) -> bool 202 | where 203 | Sha256: Digest, 204 | F1: FnOnce(&mut Sha256), 205 | F2: FnOnce(&[u8], Signature) -> bool, 206 | { 207 | let hash = { 208 | let mut hasher = Sha256::default(); 209 | 210 | input(&mut hasher); 211 | 212 | let hashed_section = self.hashed_section(); 213 | hasher.process(hashed_section); 214 | 215 | hasher.process(&[0x04, 0xff]); 216 | hasher.process(&bigendian_u32(hashed_section.len() as u32)); 217 | 218 | hasher.fixed_result() 219 | }; 220 | 221 | verify(&hash[..], self.signature()) 222 | } 223 | 224 | #[cfg(feature = "dalek")] 225 | /// Convert this signature from an ed25519-dalek signature. 226 | pub fn from_dalek( 227 | keypair: &dalek::Keypair, 228 | data: &[u8], 229 | fingerprint: Fingerprint, 230 | sig_type: SigType, 231 | timestamp: u32, 232 | ) -> PgpSig 233 | where 234 | Sha256: Digest, 235 | Sha512: Digest, 236 | { 237 | PgpSig::new::(data, fingerprint, sig_type, timestamp, &[], |data| { 238 | keypair.sign::(data).to_bytes() 239 | }) 240 | } 241 | 242 | #[cfg(feature = "dalek")] 243 | /// Convert this signature to an ed25519-dalek signature. 244 | pub fn to_dalek(&self) -> dalek::Signature { 245 | dalek::Signature::from_bytes(&self.signature()).unwrap() 246 | } 247 | 248 | #[cfg(feature = "dalek")] 249 | /// Verify this signature against an ed25519-dalek public key. 250 | pub fn verify_dalek(&self, key: &dalek::PublicKey, input: F) -> bool 251 | where 252 | Sha256: Digest, 253 | Sha512: Digest, 254 | F: FnOnce(&mut Sha256), 255 | { 256 | self.verify::(input, |data, signature| { 257 | let sig = dalek::Signature::from_bytes(&signature).unwrap(); 258 | key.verify::(data, &sig).is_ok() 259 | }) 260 | } 261 | } 262 | 263 | impl Debug for PgpSig { 264 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 265 | f.debug_struct("PgpSig").field("key", &Base64(&self.data[..])).finish() 266 | } 267 | } 268 | 269 | impl Display for PgpSig { 270 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 271 | ascii_armor( 272 | "BEGIN PGP SIGNATURE", 273 | "END PGP SIGNATURE", 274 | &self.data[..], 275 | f, 276 | ) 277 | } 278 | } 279 | 280 | impl FromStr for PgpSig { 281 | type Err = PgpError; 282 | fn from_str(s: &str) -> Result { 283 | PgpSig::from_ascii_armor(s) 284 | } 285 | } 286 | 287 | fn find_signature_packet(data: &[u8]) -> Result<(Vec, &[u8]), PgpError> { 288 | let (init, len) = match data.first() { 289 | Some(&0x88) => { 290 | if data.len() < 2 { return Err(PgpError::InvalidPacketHeader) } 291 | (2, data[1] as usize) 292 | } 293 | Some(&0x89) => { 294 | if data.len() < 3 { return Err(PgpError::InvalidPacketHeader) } 295 | let len = BigEndian::read_u16(&data[1..3]); 296 | (3, len as usize) 297 | } 298 | Some(&0x8a) => { 299 | if data.len() < 5 { return Err(PgpError::InvalidPacketHeader) } 300 | let len = BigEndian::read_u32(&data[1..5]); 301 | if len > u16::MAX as u32 { return Err(PgpError::UnsupportedPacketLength) } 302 | (5, len as usize) 303 | } 304 | _ => return Err(PgpError::UnsupportedPacketLength), 305 | }; 306 | 307 | if data.len() < init + len { 308 | return Err(PgpError::InvalidPacketHeader) 309 | } 310 | 311 | let packet = &data[init..][..len]; 312 | 313 | if init == 3 { 314 | Ok((data.to_owned(), packet)) 315 | } else { 316 | let mut vec = Vec::with_capacity(3 + len); 317 | let len = bigendian_u16(len as u16); 318 | vec.push(0x89); 319 | vec.push(len[0]); 320 | vec.push(len[1]); 321 | vec.extend(packet.iter().cloned()); 322 | Ok((vec, packet)) 323 | } 324 | } 325 | 326 | fn has_correct_structure(packet: &[u8]) -> Result<(), PgpError> { 327 | if packet.len() < 6 { 328 | return Err(PgpError::UnsupportedSignaturePacket) 329 | } 330 | 331 | if !(packet[0] == 04 && packet[2] == 22 && packet[3] == 08) { 332 | return Err(PgpError::UnsupportedSignaturePacket) 333 | } 334 | 335 | let hashed_len = BigEndian::read_u16(&packet[4..6]) as usize; 336 | if packet.len() < hashed_len + 8 { 337 | return Err(PgpError::UnsupportedSignaturePacket) 338 | } 339 | 340 | let unhashed_len = BigEndian::read_u16(&packet[(hashed_len + 6)..][..2]) as usize; 341 | if packet.len() != unhashed_len + hashed_len + 78 { 342 | return Err(PgpError::UnsupportedSignaturePacket) 343 | } 344 | 345 | Ok(()) 346 | } 347 | 348 | fn has_correct_hashed_subpackets(packet: &[u8]) -> Result<(), PgpError> { 349 | let hashed_len = BigEndian::read_u16(&packet[4..6]) as usize; 350 | if hashed_len < 23 { 351 | return Err(PgpError::MissingFingerprintSubpacket) 352 | } 353 | 354 | // check that the first subpacket is a fingerprint subpacket 355 | if !(packet[6] == 22 && packet[7] == 33 && packet[8] == 4) { 356 | return Err(PgpError::MissingFingerprintSubpacket) 357 | } 358 | 359 | Ok(()) 360 | } 361 | --------------------------------------------------------------------------------