Git Product home page Git Product logo

aspnetcorecertificates's Introduction

Certificate Manager is a package which makes it easy to create certificates which can be used to in client server authentication and IoT Devices like Azure IoT Hub

Build Certificate Manager
.NET Core .NET NuGet Status

========================

Quickstart | Documentation | Changelog

Basic usage ASP.NET Core, .NET Core

Add the NuGet package to the your project file

<PackageReference Include="CertificateManager" Version="1.0.8" />

The NuGet packages uses dependency injection to setup. In a console application initialize the package as follows:

var serviceProvider = new ServiceCollection()
    .AddCertificateManager()
    .BuildServiceProvider();

Or in an ASP.NET Core application use the Startup ConfigureServices method to initialize the package.

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddCertificateManager();
}

Now the package is ready to use. See the Documentation to create the specific certificates for your use case.

Examples Creating Certificates:

Examples Using Certificates:

Microsoft Certificate Authentication Docs:

Read certificates and private keys from PEM files

https://github.com/oocx/ReadX509CertificateFromPem

Blogs

aspnetcorecertificates's People

Contributors

anktsrkr avatar damienbod avatar jtone123 avatar kimmokantojarvi-solita avatar willyt150 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  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  avatar  avatar

aspnetcorecertificates's Issues

Add an example on export certificate to Key Vault

Hello,

Thanks for you great job ๐Ÿ‘

I am able to create chained certificate, but when I tried to upload certificate in an Azure Key Vault with the Azure Key Vault SDK (Azure.Security.KeyVault.Certificates), I have the error :

"The specified PKCS#12 X.509 certificate content can not be read. Please check if certificate is in valid PKCS#12 format."

var keyVaultName = "keyvault-name";
var kvUri = $"https://{keyVaultName}.vault.azure.net";

string certificatePath = @"C:\temp\DeviceProvisioningCertificates\intermediateCa3.pfx";
string certificateExportPassword = "1234";
string certificateName = "MyCertificateName"

var certificate = new X509Certificate2(certificatePath, certificateExportPassword, X509KeyStorageFlags.Exportable);
byte[] export = certificate.Export(X509ContentType.Pfx, certificateExportPassword);

var client = new CertificateClient(new Uri(kvUri), new InteractiveBrowserCredential());
var importCertificateOptions = new ImportCertificateOptions(certificateName, export);

The issuer certificate public key algorithm does not match the value for this certificate request

Hello ! I want to sign a leaf certificate with a custom generated CA but I have this error

System.Private.CoreLib: Exception while executing function: 
CreateLeafCert. System.Security.Cryptography.X509Certificates: The issuer certificate public key algorithm (1.2.840.113549.1.1.1)
does not match the value for this certificate request (1.2.840.10045.2.1), 
use the X509SignatureGenerator overload.

But i don't know what i'm supposed to changed T_T
Somone can help me ?
Thank for your help :)

"The certificate key algorithm is not supported." error for PrivateKey of certificate

ฤฑ am trying search the PrivateKey property of my certificate which is created by using 'NewRootCertificate' method, but it threws exception.

string pathd = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "localhost_root_l1.pfx");
X509Certificate2 crt = new X509Certificate2(pathd, "1234");
image

what is the reason of this error ?

Failed to validate the token

I have generated RSA key for identityserver4 but i get this exception in production

Failed to validate the token.
Microsoft.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException: IDX10501: Signature validation failed. Unable to match key:
kid: '[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
Number of keys in TokenValidationParameters: '0'.
Number of keys in Configuration: '1'.
Exceptions caught:
'[PII of type 'System.Text.StringBuilder' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
token: '[PII of type 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
at Microsoft.IdentityModel.Tokens.InternalValidators.ValidateLifetimeAndIssuerAfterSignatureNotValidatedJwt(SecurityToken securityToken, Nullable1 notBefore, Nullable1 expires, String kid, TokenValidationParameters validationParameters, BaseConfiguration configuration, StringBuilder exceptionStrings, Int32 numKeysInConfiguration, Int32 numKeysInTokenValidationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters, BaseConfiguration configuration)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateJWS(String token, TokenValidationParameters validationParameters, BaseConfiguration currentConfiguration, SecurityToken& signatureValidatedToken, ExceptionDispatchInfo& exceptionThrown)
--- End of stack trace from previous location ---
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken& signatureValidatedToken)

Docs

  • Creating Chained Certificates for Azure IoT
  • Creating Chained Certificates from a trusted CA Certificate

Intermittent certificate failure when authenticating to Azure IoT Hub DPS

When using the following process to create root, intermediate, and leaf certs, I receive occasional unauthorized errors when communicating with Azure IoT Hub Device Provisioning Service (DPS). https://damienbod.com/2019/06/27/using-chained-certificates-for-certificate-authentication-in-asp-net-core-3-0/

However, this error only occurs part of the time, and the same workflow will produce successful authentications. Examining the certificates, they are stored in .pfx format with the leaf, intermediate, and root stored inside. Communication is over HTTP.

Is this repository still being maintained? I notice the last commit was several years ago. Thank you!

Add IP to subjectalternativename

Hello, now the SubjectAlternativeName only support adding dnsname and email. Would you consider adding support to add IP to SubjectAlternativeName too? Thank you.

Should not we have OidLookup for common OIDs?

Instead of

var enhancedKeyUsages = new OidCollection
            {
                new Oid("1.3.6.1.5.5.7.3.1"),  // TLS Server auth
                new Oid("1.3.6.1.5.5.7.3.2"),  // TLS Client auth
            };

if we can use something like

image

I guess, it will be helpful for end users as well as it is more readable. Below is the list of common OID we can enable -

Windows Update (1.3.6.1.4.1.311.76.6.1) | Key Recovery (1.3.6.1.4.1.311.10.3.11)
Windows Third Party Application Component (1.3.6.1.4.1.311.10.3.25) | Key Recovery Agent (1.3.6.1.4.1.311.21.6)
Windows System Component Verification (1.3.6.1.4.1.311.10.3.6) | Early Launch Antimalware Driver (1.3.6.1.4.1.311.61.4.1)
Windows TCB Component (1.3.6.1.4.1.311.10.3.23) | Kernel Mode Code Signing (1.3.6.1.4.1.311.61.1.1)
Windows Software Extension Verification (1.3.6.1.4.1.311.10.3.26) | Attestation Identity Key Certificate (2.23.133.8.3)
Windows Store (1.3.6.1.4.1.311.76.3.1) | Key Pack Licenses (1.3.6.1.4.1.311.10.6.1)
Smart Card Logon (1.3.6.1.4.1.311.20.2.2) | KDC Authentication (1.3.6.1.5.2.3.5)
IP security user (1.3.6.1.5.5.7.3.7) | Embedded Windows System Component Verification (1.3.6.1.4.1.311.10.3.8)
Windows Kits Component (1.3.6.1.4.1.311.10.3.20) | IP security tunnel termination (1.3.6.1.5.5.7.3.6)
Windows Hardware Driver Verification (1.3.6.1.4.1.311.10.3.5) | IP security IKE intermediate (1.3.6.1.5.5.8.2.2)
Windows Hardware Driver Extended Verification (1.3.6.1.4.1.311.10.3.39) | License Server Verification (1.3.6.1.4.1.311.10.6.2)
Windows Hardware Driver Attested Verification (1.3.6.1.4.1.311.10.3.5.1) | Dynamic Code Generator (1.3.6.1.4.1.311.76.5.1)
Time Stamping (1.3.6.1.5.5.7.3.8) | File Recovery (1.3.6.1.4.1.311.10.3.4.1)
SpcRelaxedPEMarkerCheck (1.3.6.1.4.1.311.2.6.1) | Endorsement Key Certificate (2.23.133.8.1)
SpcEncryptedDigestRetryCount (1.3.6.1.4.1.311.2.6.2) | Encrypting File System (1.3.6.1.4.1.311.10.3.4)
Server Authentication (1.3.6.1.5.5.7.3.1) | HAL Extension (1.3.6.1.4.1.311.61.5.1)
Secure Email (1.3.6.1.5.5.7.3.4) | IP security end system (1.3.6.1.5.5.7.3.5)
Root List Signer (1.3.6.1.4.1.311.10.3.9) | Disallowed List (1.3.6.1.4.1.311.10.3.30)
Revoked List Signer (1.3.6.1.4.1.311.10.3.19) | Windows RT Verification (1.3.6.1.4.1.311.10.3.21)
Qualified Subordination (1.3.6.1.4.1.311.10.3.10) | Document Signing (1.3.6.1.4.1.311.10.3.12)
Protected Process Verification (1.3.6.1.4.1.311.10.3.24) | Document Encryption (1.3.6.1.4.1.311.80.1)
Protected Process Light Verification (1.3.6.1.4.1.311.10.3.22) | Directory Service Email Replication (1.3.6.1.4.1.311.21.19)
Private Key Archival (1.3.6.1.4.1.311.21.5) | Digital Rights (1.3.6.1.4.1.311.10.5.1)
Preview Build Signing (1.3.6.1.4.1.311.10.3.27) | Certificate Request Agent (1.3.6.1.4.1.311.20.2.1)
Platform Certificate (2.23.133.8.2) | CTL Usage (1.3.6.1.4.1.311.20.1)
OCSP Signing (1.3.6.1.5.5.7.3.9) | Code Signing (1.3.6.1.5.5.7.3.3)
Microsoft Trust List Signing (1.3.6.1.4.1.311.10.3.1) | Microsoft Time Stamping (1.3.6.1.4.1.311.10.3.2)
Microsoft Publisher (1.3.6.1.4.1.311.76.8.1) | Client Authentication (1.3.6.1.5.5.7.3.2)
Lifetime Signing (1.3.6.1.4.1.311.10.3.13) | Any Purpose (2.5.29.37.0)
Domain Name System (DNS) Server Trust (1.3.6.1.4.1.311.64.1.1) | OEM Windows System Component Verification (1.3.6.1.4.1.311.10.3.7)

Signing certificates based on CSR

Hi,
I like the package and therefore would like to propose some small enhancements for signing the certificates.
Basically functions in CreateCertificates.cs always create a new key pair instead of using existing keys from a CSR and therefore would like to propose adding possibility to sign certificates based on CSRs.
Instead of creating CertificateRequest inside the function allow bringing it as a parameter to the functions.
Functions affected:

  • NewECDsaSelfSignedCertificate
  • NewRsaSelfSignedCertificate
  • NewRsaChainedCertificate
  • NewECDsaChainedCertificate
    Best regards,
    Kimmo

SHA1 and MD5 not supported

I want to use this library to generate a certificate for a legacy device, so I have to use MD5 or SHA1 for certificate signiture, however, setting HashAlgorithmName to MD5 or SHA1 would throw System.ArgumentOutOfRangeException: 'SHA1' is not a known hash algorithm. (Parameter 'hashAlgorithm') Actual value was SHA1..

After some googling, it seems that MD5 and SHA1 support should be added manually (from https://stackoverflow.com/questions/59885459/argumentoutofrangeexception-when-trying-to-create-a-self-signed-certificate-usin)

Is adding this support possible?

Thank you!

Unable to generate server certificate from root CA and preserve hierarchy

I am trying to generate a X509 certificate from a root CA and use it as a server certificate. I tried the following from the demo:

var serviceProvider = new ServiceCollection()
    .AddCertificateManager()
    .BuildServiceProvider();

var createClientServerAuthCerts = serviceProvider.GetService<CreateCertificatesClientServerAuth>();

var rootCaL1 = createClientServerAuthCerts.NewRootCertificate(
    new DistinguishedName { CommonName = "root dev", Country = "IT" },
    new ValidityPeriod { ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(10) },
    3,
    "localhost");

var intermediateCaL2 = createClientServerAuthCerts.NewIntermediateChainedCertificate(
    new DistinguishedName { CommonName = "intermediate dev", Country = "FR" },
    new ValidityPeriod { ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(10) },
    2,
    "localhost",
    rootCaL1);

var serverL3 = createClientServerAuthCerts.NewServerChainedCertificate(
    new DistinguishedName { CommonName = "server", Country = "DE" },
    new ValidityPeriod { ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(10) },
    "localhost",
    intermediateCaL2);

When I try to use the resulting leaf certificate (serverL3) on an HTTP server, I get the following certificate hierarchy:

image

Whereas what I am trying to achieve is the following:

image

Is this possible using AspNetCoreCertificates?

3 out of 27 Unit Tests are failing on Windows 7, but run ok on Windows 10

Hi,

The following 3 tests are failing on Windows 7, but run ok on Windows 10:

  1. ImportExportRsaPrivateKeyPublicKeyPairPem()
  2. ImportExportSingleChainedECPrivateKeyPublicKeyPairPem()
  3. ImportExportECPrivateKeyPublicKeyPairPem()

They are all failing with the Excepton:

"Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException : The specified network password is not correct."

Is there some further preparation to run these Tests successfully on Windows 7, some code changes required, or is this a known limitation of ASPNetCore on Windows 7 (e.g. rather like no .NET ALPN support in Win7)?

Exception stack trace details are listed below.

  1. ImportExportRsaPrivateKeyPublicKeyPairPem

CertificateManagerTests.ImportExportTests.ImportExportRsaPrivateKeyPublicKeyPairPem
Source: ImportExportTests.cs line 165
Duration: 204 ms

Message:
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException : The specified network password is not correct.

Stack Trace:
CertificatePal.FilterPFXStore(Byte[] rawData, SafePasswordHandle password, PfxCertStoreFlags pfxCertStoreFlags)
CertificatePal.FromBlobOrFile(Byte[] rawData, String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
X509Certificate.ctor(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
X509Certificate2.ctor(Byte[] rawData, String password)
PemDecoder.CreateCertificateWithPrivateKey(X509Certificate2 certificate, AsymmetricAlgorithm privateKey, String password) line 151
ImportExportCertificate.CreateCertificateWithPrivateKey(X509Certificate2 certificate, AsymmetricAlgorithm privateKey, String password) line 193
ImportExportTests.ImportExportRsaPrivateKeyPublicKeyPairPem() line 182

  1. ImportExportSingleChainedECPrivateKeyPublicKeyPairPem

CertificateManagerTests.ImportExportTests.ImportExportSingleChainedECPrivateKeyPublicKeyPairPem
Source: ImportExportTests.cs line 220
Duration: 154 ms

Message:
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException : The specified network password is not correct.

Stack Trace:
CertificatePal.FilterPFXStore(Byte[] rawData, SafePasswordHandle password, PfxCertStoreFlags pfxCertStoreFlags)
CertificatePal.FromBlobOrFile(Byte[] rawData, String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
X509Certificate.ctor(Byte[] data)
X509Certificate2.ctor(Byte[] rawData)
PemDecoder.CreateCertificateWithPrivateKey(X509Certificate2 certificate, AsymmetricAlgorithm privateKey, String password) line 146
ImportExportCertificate.CreateCertificateWithPrivateKey(X509Certificate2 certificate, AsymmetricAlgorithm privateKey, String password) line 193
ImportExportTests.ImportExportSingleChainedECPrivateKeyPublicKeyPairPem() line 236

  1. ImportExportECPrivateKeyPublicKeyPairPem

CertificateManagerTests.ImportExportTests.ImportExportECPrivateKeyPublicKeyPairPem
Source: ImportExportTests.cs line 192
Duration: 129 ms

Message:
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException : The specified network password is not correct.

Stack Trace:
CertificatePal.FilterPFXStore(Byte[] rawData, SafePasswordHandle password, PfxCertStoreFlags pfxCertStoreFlags)
CertificatePal.FromBlobOrFile(Byte[] rawData, String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
X509Certificate.ctor(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
X509Certificate2.ctor(Byte[] rawData, String password)
PemDecoder.CreateCertificateWithPrivateKey(X509Certificate2 certificate, AsymmetricAlgorithm privateKey, String password) line 151
ImportExportCertificate.CreateCertificateWithPrivateKey(X509Certificate2 certificate, AsymmetricAlgorithm privateKey, String password) line 193
ImportExportTests.ImportExportECPrivateKeyPublicKeyPairPem() line 208

ImportExport password issues with on OSX

I've been trying to get this working on OSX. A few issues are easily handled, such as OSX's lack of support for "FriendlyName". However, I've been unable to get the ImportExportTests to execute properly.

The ImportExportTests.ImportExportECPrivateKeyPublicKeyPairPem test fails on these lines:

            var roundTripFullCert =
                importExport.CreateCertificateWithPrivateKey(
                    roundTripPublicKeyPem, 
                    roundTripRsaPrivateKeyPem, "1234");

with the error

Interop+AppleCrypto+AppleCommonCryptoCryptographicException : MAC verification failed during PKCS12 import (wrong password?)
   at Interop.AppleCrypto.X509ImportCertificate(Byte[] bytes, X509ContentType contentType, SafePasswordHandle importPassword, SafeKeychainHandle keychain, Boolean exportable, SafeSecIdentityHandle& identityHandle)
   at Internal.Cryptography.Pal.AppleCertificatePal.FromBlob(Byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
   at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
   at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password)
   at CertificateManager.PemDecoder.CreateCertificateWithPrivateKey(X509Certificate2 certificate, AsymmetricAlgorithm privateKey, String password) in /Users/bill/ws/SB/Certificates/AspNetCoreCertificates/src/CertificateManager/PemDecoder.cs:line 152
   at CertificateManager.ImportExportCertificate.CreateCertificateWithPrivateKey(X509Certificate2 certificate, AsymmetricAlgorithm privateKey, String password) in /Users/bill/ws/SB/Certificates/AspNetCoreCertificates/src/CertificateManager/ImportExportCertificate.cs:line 193
   at CertificateManagerTests.ImportExportTests.ImportExportECPrivateKeyPublicKeyPairPem() in /Users/bill/ws/SB/Certificates/AspNetCoreCertificates/src/CertificateManagerTests/ImportExportTests.cs

Similar issues occur on the tests ImportExportRsaPrivateKeyPublicKeyPairPem and ImportExportSingleChainedECPrivateKeyPublicKeyPairPem, always on the call importExport.CreateCertificateWithPrivateKey.

Any chance of getting this library to work on OSX? This is the only real issue that I've run into with it.

GetClientCertificateAsync

Hello guys,
I developed an api. that at the controller I need to read the data from the client certificate attached to the request.
on my computer in development mode, I make requests and when debugging I receive the certified object
concealer when I run
X509Certificate2 cert = await HttpContext.Connection.GetClientCertificateAsync ();

  • However some strange things happen ....
    if I attach other (valid) .pfx certificates to some I get Null in the cert object, others I get correct,
    I didn't understand why some read and others don't
    (I checked if they were not expired, or without the certificate chains, apparently all right).

  • and what is more catching is when I publish this on my server, give it for good ...
    in all requests the cert object comes as Null ...
    (it is a linux centos server with nginx).

is some extra configuration that I have to do, or some other detail that I'm missing,
I would like to know if someone can give me a light on this issue ....

Missing docs

What is a chained certificate

What is a intermiedate certificate

Certificate Types

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.