Giter Club home page Giter Club logo

pem-utils's Introduction

PEM-utils

Build status

Managed .NET (C#) utility library for working with PEM files with DER/ASN.1 encoding.

This project has 2 separate libraries:

  • DerConverter - for converting ASN.1 syntax from/to binary data
  • PemUtils - builds on top of DerConverter for reading/writing RSAParameters from/to a PEM formatted file

PEM files are commonly used to exchange public or private key data.

Currently files with these headers are supported:

  • ----- BEGIN PUBLIC KEY ----- / ----- END PUBLIC KEY -----
  • ----- BEGIN RSA PRIVATE KEY ----- / ----- END RSA PRIVATE KEY -----

Get it on NuGet

PM> Install-Package PemUtils

or if you only want a DER converter:

PM> Install-Package DerConverter

Usage

Reading

using (var stream = File.OpenRead(path))
using (var reader = new PemReader(stream))
{
    var rsaParameters = reader.ReadRsaKey();
    // ...
}

Writing

using (var stream = File.Create(path))
using (var writer = new PemWriter(stream))
{
    // ...
    writer.WritePublicKey(rsaParameters);
}

pem-utils's People

Contributors

bravotango86 avatar dsuk avatar huysentruitw avatar qmfrederik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pem-utils's Issues

Please support PRIVATE KEY

Exception: System.NotImplementedException: The format PRIVATE KEY is not yet implemented
at PemUtils.PemReader.ReadRsaKey()

PemWriter creates an invalid PEM file when byte begin with a zero

Initially I found an intermittent issue in my integration tests with RSAParameters to PEM conversion using PemWriter and reading it back using PemReader.

Now I have narrowed it down to PemWriter and I can replicate it.

When any of the RSAParameters such as Modulus, D, P, etc start with zero as the first byte, PemWriter generates an invalid PEM file. It does not include the first zero in the PEM file.

I am looking further into this. I will post if I find anything interesting.

Method not found exception

Does not seem to work for me as I'm seeing the following exception:

Method not found: 'System.Collections.Generic.IReadOnlyList`1<DerConverter.Asn.DerAsnType> DerConverter.Asn.DerAsnSequence.get_Items()'.
at PemUtils.PemReader.ReadPublicKey(DerAsnType der)
at PemUtils.PemReader.ReadRsaKey()

Using the following code:

static void Main()
{
    var pub =
        "-----BEGIN PUBLIC KEY-----\n" +
        "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKuMYcirPj81WBtMituJJenF0CG/HYLc\n" +
        "AUOtWKl1HchC0dM8VRRBI/HV+nZcweXzpjhX8ySa9s7kJneP0cuJiU8CAwEAAQ==\n" +
        "-----END PUBLIC KEY-----";
        
    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(pub)))
    using (var reader = new PemReader(stream))
    {
        var rsaParameters = reader.ReadRsaKey();
    }
}

I am using version 1.0.0.21

Decoding indefinite-length encoded values

Consider e.g. the following value:

30 80 a0 80 80 01 06 83 02 00 e2 00 00 a2 80 80 01 01 81 01 0d 00 00 83 01 65 00 00

This decodes to

SEQUENCE(3 elem)
  [0](2 elem)
    [0](1 byte) 06
    [3](2 byte) 00E2
  [2](2 elem)
    [0](1 byte) 01
    [1](1 byte) 0D
  [3]e

This uses indefinite-length encoding (see paragraph 8.1.3.6), which is currently not supported.

Hi and thanks for your efforts. Is there an example for how todo this?

Hi and thanks for your efforts. Is there an example for how todo this?
I have case where I am creating a DerAsnIa5String and serializes perfectly!

var contextSpesificId = new DerAsnIdentifier(DerAsnTagClass.ContextSpecific, DerAsnEncodingType.Primitive, DerAsnKnownTypeTags.Primitive.ObjectIdentifier);
var location = new DerAsnIa5String(contextSpesificId, uri.ToString());
// etc....

But cant seem to get the value out. I tried to hack my way through by doing Encoding.ASCII.GetString(objectIdentifier.Value.Select(x => (byte)x).ToArray()) which gives me almost the string I wanted with missing one character plus two control characters at the begining. Did not like this approach anyway.

What i am trying to figure out is how to tell the default decoder not to parse this into DerAsnObjectIdentifier if it sees the DerAsnTagClass.ContextSpecific but instead parse it into DerAsnIa5String. Can it be done?

Originally posted by @cleftheris in #16 (comment)

The format PRIVATE KEY is not yet implemented

I would like to load a pem file into C# and I can't find the proper tool. I was hoping pem-utils is exactly what I need, but I'm getting the following error:

Unhandled Exception: System.NotImplementedException: The format PRIVATE KEY is not yet implemented

I didn't know there are other formats besides "PRIVATE KEY". Is any other format 'implemented' in this library?

This is how my code looks like:

        RSA rsa = RSA.Create();
        string file = "/home/user/certs/ca5.pem";
        using (var stream = File.OpenRead(file))
        using (var reader = new PemReader(stream))
        {
            var rsaParameters = reader.ReadRsaKey();
            rsa.ImportParameters(rsaParameters);
        }
        Console.WriteLine("RSA: " + rsa.KeySize);

It crashes at ReadRsaKey() line.

Any help would be great.

Extensibility story

The current implementation of DerConverter is incomplete - some types, such as the various string types or the real type, are missing.
Plus, ASN.1 is by default extensible. For example, you can define custom types in contexts.

There's currently no good story for extensibility in the DerConverter library, short of forking.

For example, adding a new type currently requires you to fork the library, because you cannot easily inject your type in the types the DerAsnType.Parse method considers. Neither can you create your own parser since the DerAsn*(Queue<byte> rawData) constructors are internal.

It would be helpful it were easier to extend the library.

VerifyData using loaded PEM fails

I used the command-line OpenSSL program to generate the public and private keys and to sign a file but when I try to use RSA.VerifyData to verify the signature, it fails.

I was previously using the .NET Core version of the RSA class which has (slightly) better support for PEM and so didn't need to use PEM-utils and the VerifyData call succeeded.

I'm generating the keys like so:

> openssl version
OpenSSL 1.0.2u  20 Dec 2019
> openssl genpkey -out privkey.pem -algorithm rsa 4096

and the signature like so:

> openssl dgst -sha256 -sign privkey.pem -out test.zip.sig test.zip

and the code for verifying the signature looks like this:

var fileToVerifyStream = new FileStream(fileToVerifyPath, FileMode.Open);
byte[] signatureBytes = File.ReadAllBytes(fileSignaturePath);

RSAParameters publicKey = ReadPemPublicKey(publicKeyPath); // Calls PemReader.ReadRsaKey()
_rsa.ImportParameters(publicKey);
_rsa.VerifyData(fileToVerifyStream, signatureBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.