pem-rs pem PEM jcreekmore/pem-rs [pem] โ€” A Rust based way to parse and encode PEM-encoded data

Overview

pem

A Rust library for parsing and encoding PEM-encoded data.

Build Status

Documentation

Module documentation with examples

Usage

Add this to your Cargo.toml:

[dependencies]
pem = "0.8"

and this to your crate root:

extern crate pem;

Here is a simple example that parse PEM-encoded data and prints the tag:

extern crate pem;

use pem::parse;

const SAMPLE: &'static str = "-----BEGIN RSA PRIVATE KEY-----
MIIBPQIBAAJBAOsfi5AGYhdRs/x6q5H7kScxA0Kzzqe6WI6gf6+tc6IvKQJo5rQc
dWWSQ0nRGt2hOPDO+35NKhQEjBQxPh/v7n0CAwEAAQJBAOGaBAyuw0ICyENy5NsO
2gkT00AWTSzM9Zns0HedY31yEabkuFvrMCHjscEF7u3Y6PB7An3IzooBHchsFDei
AAECIQD/JahddzR5K3A6rzTidmAf1PBtqi7296EnWv8WvpfAAQIhAOvowIXZI4Un
DXjgZ9ekuUjZN+GUQRAVlkEEohGLVy59AiEA90VtqDdQuWWpvJX0cM08V10tLXrT
TTGsEtITid1ogAECIQDAaFl90ZgS5cMrL3wCeatVKzVUmuJmB/VAmlLFFGzK0QIh
ANJGc7AFk4fyFD/OezhwGHbWmo/S+bfeAiIh2Ss2FxKJ
-----END RSA PRIVATE KEY-----

let pem = parse(SAMPLE)?;
println!("PEM tag: {}", pem.tag);
Comments
  • Linker error while compiling cryptography-rust

    Linker error while compiling cryptography-rust

    I don't know why this issue plagued me and what is the culprit. I am trying Windows build for latest pyca cryptography 36 dev1 and got linker error while compiling cryptography-rust:

    "C:\Python37\cryptography-main\src\rust\target\i686-pc-windows-gnu\release\deps\cryptography_rust.cryptography_rust.8yeboqs1-cgu.12.rcgu.o:cryptography_rust.: undefined reference to _imp___ZN3pem11ASCII_ARMOR17hda6e74d90990760eE collect2.exe: error: ld returned 1 exit status"

    Missing function should obviously be named ZN3pem11ASCII_ARMOR17hda6e74d90990760eE and linked from pem library. But why it got erroneous imp prefix? No idea.

    I'm using 32-bit environment with Python 3.7 / Rust 1.48 (i686-pc-windows-gnu) / PEM 1.0.0

    opened by Tarnum-tst 6
  • How encode public key?

    How encode public key?

    I write a generate private key program with pem:

    extern crate openssl;
    extern crate pem;
    
    use openssl::rsa::Rsa;
    use pem::{Pem, encode};
    
    fn main() {
      // Generate a new 4096-bit key.
      let rsa = Rsa::generate(4096).unwrap();
    
      let public_key = rsa.public_key_to_der().unwrap();
      let private_key = rsa.private_key_to_der().unwrap();
    
      let private_pem = Pem {
        tag: String::from("RSA PRIVATE KEY"),
        contents: private_key,
      };
      let private = encode(&private_pem);
    
      println!("{}", private);
    }
    

    But I couldn't found a way encode public data to PKIX format, do you have an idea?

    Thanks much!

    opened by genedna 5
  • Replace regex dependency with a simple hand-written parser

    Replace regex dependency with a simple hand-written parser

    The removes the dependencies on both regex and once_cell, and gives significant performance increases in the current benchmarks. It passes all the tests, and I believe it has the same semantics as the regex.

    opened by Aeledfyr 4
  • Any interest in serde support behind a feature flag?

    Any interest in serde support behind a feature flag?

    I have added the Pem type to an enum that was previously able to derive Serialize and Deserialize but I can no longer derive as Pem does not implement the serde traits.

    Could we add this support behind a serde feature flag please? It should be quite straightforward I think given that Pem is just a couple of String values.

    Happy to do the work if you would land this as it's quite tedious manually implementing the serde traits in my codebase on an enum with quite a few variants!

    opened by tmpfs 2
  • Make `parse_many` return a `Result<Vec<Pem>>`

    Make `parse_many` return a `Result>`

    Thanks for the prompt reply in #27! :cake:

    This PR changes parse_many to return a Result. Feel free to discard the CHANGELOG.md if you do not want to maintain it, I figured it'd be somewhat useful with the breaking change. ๐Ÿ˜ƒ

    opened by mhils 2
  • `parse_many` silently discards invalid sections

    `parse_many` silently discards invalid sections

    First off, thanks for the super helpful project! :cake:

    I was looking at exposing pem::parse_many to Python users via the cryptography package (https://github.com/pyca/cryptography/issues/6351#issuecomment-932148321). In that process I discovered that parse_many silently discards all invalid sections, which I found quite surprising. That makes it hard to provide good error messages as I cannot differentiate between malformed and missing sections.

    Long story short, would you entertain the idea of either changing parse_many to return a Result<Vec<Pem>> or adding an alternative method name (parse_all, parse_many_strict?) that returns an error on the first parsing failure? I'd be happy to send a PR with whatever you prefer. ๐Ÿ˜ƒ

    For reference, here's the current parse_many implementation:

    https://github.com/jcreekmore/pem-rs/blob/b2cfec184815fecace9b5b1844eb6b15bda69793/src/lib.rs#L320-L326

    opened by mhils 2
  • Adding benchmarks

    Adding benchmarks

    This pull-requests adds benchmarks to encoding and decoding PEMs.

    I hope to follow up with some more pull requests, adding support for PEM headers along with other ergonomic improvements, but I wanted to get benchmarks in first to validate that my future PRs will not regress performance.

    opened by phayes 1
  • hide the ASCII_ARMOR symbol

    hide the ASCII_ARMOR symbol

    There appears to be some interaction between once_cell and the 32-bit toolchain for windows that is causing the ASCII_ARMOR symbol to be mis-linked. To work around the issue reported in #29, hide the ASCII_ARMOR symbol inside of a function so that it is not even crate-wide available but is only available inside the function. Closes #29.

    opened by jcreekmore 0
  • Disable default features of regex crate to reduce dependencies, compile time, code size

    Disable default features of regex crate to reduce dependencies, compile time, code size

    This decreases number of dependencies from 8 to 4.

    Disabled features are:

    • perf
      • PEM decoding should not be in a critical path
    • unicode
      • Unicode support is not needed for ASCII only files

    It might be more ideal to build a special purpose simple parser for PEM files, but this was an easy change with relatively large benefits IMHO.

    opened by rolftimmermans 0
  • Add interface allowing the user to specify line endings

    Add interface allowing the user to specify line endings

    When encoding data into PEM, the library uses \r\n line endings. This commit provides the user the ability to change this behavior and use \n instead by introducing encode_config and encode_many_config functions, which take an additional argument providing configuration for the encoding process. For backwards compatibility, encode and encode_many will use CRLF by default.

    opened by sarnautov 0
Owner
Jonathan Creekmore
Jonathan Creekmore
rust-jsonnet - The Google Jsonnet( operation data template language) for rust

rust-jsonnet ==== Crate rust-jsonnet - The Google Jsonnet( operation data template language) for rust Google jsonnet documet: (http://google.github.io

Qihoo 360 24 Dec 1, 2022
A series of compact encoding schemes for building small and fast parsers and serializers

A series of compact encoding schemes for building small and fast parsers and serializers

Manfred Krรถhnert 2 Feb 5, 2022
Encoding and decoding support for BSON in Rust

bson-rs Encoding and decoding support for BSON in Rust Index Overview of BSON Format Usage BSON Values BSON Documents Modeling BSON with strongly type

mongodb 304 Dec 30, 2022
Rust library for reading/writing numbers in big-endian and little-endian.

byteorder This crate provides convenience methods for encoding and decoding numbers in either big-endian or little-endian order. Dual-licensed under M

Andrew Gallant 811 Jan 1, 2023
Variable-length signed and unsigned integer encoding that is byte-orderable for Rust

ordered-varint Provides variable-length signed and unsigned integer encoding that is byte-orderable. This crate provides the Variable trait which enco

Khonsu Labs 7 Dec 6, 2022
Free Rust-only Xbox ADPCM encoder and decoder

XbadPCM Safe (and optionally no-std) Rust crate for encoding and decoding Xbox ADPCM blocks. Decoding example Here is example code for decoding stereo

Snowy 5 Nov 20, 2022
Decode Mode S and ADS-B signals in Rust

rs1090 rs1090 is a Rust library to decode Mode S and ADS-B messages. It takes its inspiration from the Python pyModeS library, and uses deku in order

Xavier Olive 6 Mar 1, 2024
Fast and compact sets of bytes or ASCII characters

bset Fast and compact sets of bytes and ASCII characters, useful for searching, parsing and determining membership of a given byte in the given set. T

null 26 Jul 19, 2022
Astro Format is a library for efficiently encoding and decoding a set of bytes into a single buffer format.

Astro Format is a library for efficiently transcoding arrays into a single buffer and native rust types into strings

Stelar Labs 1 Aug 13, 2022
Decode SCALE bytes into custom types using a scale-info type registry and a custom Visitor impl.

scale-decode This crate attempts to simplify the process of decoding SCALE encoded bytes into a custom data structure given a type registry (from scal

Parity Technologies 6 Sep 20, 2022
MessagePack implementation for Rust / msgpack.org[Rust]

RMP - Rust MessagePack RMP is a pure Rust MessagePack implementation. This repository consists of three separate crates: the RMP core and two implemen

Evgeny Safronov 840 Dec 30, 2022
A Rust ASN.1 (DER) serializer.

rust-asn1 This is a Rust library for parsing and generating ASN.1 data (DER only). Installation Add asn1 to the [dependencies] section of your Cargo.t

Alex Gaynor 85 Dec 16, 2022
Implementation of Bencode encoding written in rust

Rust Bencode Implementation of Bencode encoding written in rust. Project Status Not in active developement due to lack of time and other priorities. I

Arjan Topolovec 32 Aug 6, 2022
Cap'n Proto for Rust

Cap'n Proto for Rust documentation blog Introduction Cap'n Proto is a type system for distributed systems. With Cap'n Proto, you describe your data an

Cap'n Proto 1.5k Dec 26, 2022
A Gecko-oriented implementation of the Encoding Standard in Rust

encoding_rs encoding_rs an implementation of the (non-JavaScript parts of) the Encoding Standard written in Rust and used in Gecko (starting with Fire

Henri Sivonen 284 Dec 13, 2022
Character encoding support for Rust

Encoding 0.3.0-dev Character encoding support for Rust. (also known as rust-encoding) It is based on WHATWG Encoding Standard, and also provides an ad

Kang Seonghoon 264 Dec 14, 2022
Rust implementation of CRC(16, 32, 64) with support of various standards

crc Rust implementation of CRC(16, 32, 64). MSRV is 1.46. Usage Add crc to Cargo.toml [dependencies] crc = "2.0" Compute CRC use crc::{Crc, Algorithm,

Rui Hu 120 Dec 23, 2022
A CSV parser for Rust, with Serde support.

csv A fast and flexible CSV reader and writer for Rust, with support for Serde. Dual-licensed under MIT or the UNLICENSE. Documentation https://docs.r

Andrew Gallant 1.3k Jan 5, 2023
A HTTP Archive format (HAR) serialization & deserialization library, written in Rust.

har-rs HTTP Archive format (HAR) serialization & deserialization library, written in Rust. Install Add the following to your Cargo.toml file: [depende

Sebastian Mandrean 25 Dec 24, 2022