├── renovate.json ├── src └── cert-generator │ ├── Properties │ └── launchSettings.json │ ├── ReadMe.md │ ├── cert-generator.csproj │ ├── Interfaces │ ├── ICertificateAuthority.cs │ ├── IPrivateKeyGenerator.cs │ ├── ICertificateStore.cs │ ├── ICertificateRootAuthority.cs │ └── CertificateMetadata.cs │ ├── Helpers │ └── CertificateExtensions.cs │ ├── RootOptions.cs │ ├── Implementation │ ├── CertificateAuthority.cs │ └── CertificateRootAuthority.cs │ └── Program.cs ├── .github ├── dependabot.yml └── workflows │ ├── dotnet-core.yml │ └── container.yml ├── Dockerfile ├── README.md ├── LICENSE ├── .gitattributes ├── Generator.sln └── .gitignore /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "local>Altinn/renovate-config" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /src/cert-generator/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Cert": { 4 | "commandName": "Project" 5 | }, 6 | "Docker": { 7 | "commandName": "Docker" 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: nuget 4 | directory: "/src/cert-generator" 5 | schedule: 6 | interval: daily 7 | time: "04:00" 8 | open-pull-requests-limit: 40 9 | -------------------------------------------------------------------------------- /src/cert-generator/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Altinn-Cert 2 | 3 | Features: 4 | - Generate and sign new certificates with a certificate chain 5 | 6 | 7 | Commands: 8 | - generate-certificate 9 | - generate-ica (generate-intermediate-ca) 10 | -------------------------------------------------------------------------------- /src/cert-generator/cert-generator.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net7.0 6 | Linux 7 | CertGenerator 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/cert-generator/Interfaces/ICertificateAuthority.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Security.Cryptography.X509Certificates; 4 | using System.Text; 5 | 6 | namespace CertGenerator.Interfaces 7 | { 8 | interface ICertificateAuthority 9 | { 10 | /// 11 | /// Generate and sign a new certificate. 12 | /// 13 | /// 14 | /// 15 | X509Certificate2 GenerateAndSignCertificate(string subjectName); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/cert-generator/Interfaces/IPrivateKeyGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Security.Cryptography; 4 | using System.Text; 5 | 6 | namespace CertGenerator.Interfaces 7 | { 8 | interface IPrivateKeyGenerator 9 | { 10 | /// 11 | /// Generates a new RSA keypair with length . 12 | /// 13 | /// 14 | /// A newly created RSA keypair 15 | RSA GeneratePrivateKey(int keyLength); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/dotnet/sdk:7.0-alpine@sha256:1478c99b4bed8d297ccd000e0fdaf060cdfb281779f8c8aa47f031a09503c0d4 AS build 2 | MAINTAINER Bengt Fredh 3 | 4 | COPY src/cert-generator ./cert-generator 5 | WORKDIR cert-generator/ 6 | 7 | RUN dotnet build cert-generator.csproj -o /app_output 8 | 9 | FROM mcr.microsoft.com/dotnet/runtime:7.0-alpine@sha256:cc4d0d1b69099a4cb0cff57975f00e4248096bf301d1962b139b01828c84157f AS final 10 | MAINTAINER Bengt Fredh 11 | 12 | COPY --from=build /app_output /usr/local/bin/ 13 | 14 | WORKDIR /data 15 | VOLUME /data 16 | -------------------------------------------------------------------------------- /.github/workflows/dotnet-core.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-22.04 13 | 14 | steps: 15 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 16 | - name: Setup .NET Core 17 | uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4.3.1 18 | with: 19 | dotnet-version: 3.1.101 20 | - name: Install dependencies 21 | run: dotnet restore 22 | - name: Build 23 | run: dotnet build --configuration Release --no-restore 24 | - name: Test 25 | run: dotnet test --no-restore --verbosity normal 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cert Generator 2 | > [!WARNING] 3 | > ## Archived 4 | > This utility is no longer in use and hence it is archived. 5 | 6 | A simple utility for creating "valid" TLS certificates for use in internal communication scenarios. 7 | 8 | ## Features: 9 | - Generate root certificate authority certificates 10 | - Generate intermediate certificate authorities which are signed with the root CA certificate 11 | - Generate server/client certificates which are signed with the chosen CA certificate 12 | 13 | ## Limitations 14 | The utility is not a substitute for a PKI management system. There are **NO SUPPORT** for revoking certificates or certificate transparency. 15 | 16 | ## Implementation 17 | The utility is written using .NET Core. 18 | -------------------------------------------------------------------------------- /src/cert-generator/Interfaces/ICertificateStore.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Security.Cryptography.X509Certificates; 4 | using System.Text; 5 | 6 | namespace CertGenerator.Interfaces 7 | { 8 | interface ICertificateStore 9 | { 10 | /// 11 | /// Save the certificate metadata in the database. 12 | /// 13 | /// 14 | /// The unique identifier for the metadata 15 | string SaveCertificateMetadata(X509Certificate2 certificate); 16 | 17 | 18 | /// 19 | /// Get the certificate metadata based on the identifier 20 | /// 21 | /// 22 | /// 23 | CertificateMetadata GetCertificateMetadataByIdentifier(string identifier); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/cert-generator/Interfaces/ICertificateRootAuthority.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Security.Cryptography.X509Certificates; 4 | using System.Text; 5 | 6 | namespace CertGenerator.Interfaces 7 | { 8 | interface ICertificateRootAuthority : ICertificateAuthority 9 | { 10 | /// 11 | /// Generate a new root certificate and sign it with its own certificate. 12 | /// 13 | /// 14 | /// 15 | X509Certificate2 GenerateRootCertificate(string subjectName); 16 | 17 | /// 18 | /// Geneerate a new intermediate certificate and sign it with this root certificate. 19 | /// 20 | /// 21 | /// 22 | X509Certificate2 GenerateAndSignIntermediateCertificate(string subjectName); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Altinn 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # General setting that applies Git's binary detection for file-types not specified below 2 | # Meaning, for 'text-guessed' files: 3 | # use normalization (convert crlf -> lf on commit, i.e. use `text` setting) 4 | # & do unspecified diff behavior (if file content is recognized as text & filesize < core.bigFileThreshold, do text diff on file changes) 5 | * text=auto 6 | 7 | 8 | # Override with explicit specific settings for known and/or likely text files in our repo that should be normalized 9 | # where diff{=optional_pattern} means "do text diff {with specific text pattern} and -diff means "don't do text diffs". 10 | # Unspecified diff behavior is decribed above 11 | *.cer text -diff 12 | *.cmd text 13 | *.cs text diff=csharp 14 | *.csproj text 15 | *.css text diff=css 16 | Dockerfile text 17 | *.json text 18 | *.md text diff=markdown 19 | *.msbuild text 20 | *.pem text -diff 21 | *.ps1 text 22 | *.sln text 23 | *.yaml text 24 | *.yml text 25 | 26 | # Files that should be treated as binary ('binary' is a macro for '-text -diff', i.e. "don't normalize or do text diff on content") 27 | *.jpeg binary 28 | *.pfx binary 29 | *.png binary -------------------------------------------------------------------------------- /.github/workflows/container.yml: -------------------------------------------------------------------------------- 1 | name: Build from Dockerfile 2 | on: 3 | push: 4 | pull_request: 5 | schedule: 6 | - cron: "33 3 * * 3" 7 | 8 | jobs: 9 | build: 10 | name: Build image 11 | runs-on: ubuntu-latest 12 | permissions: 13 | packages: write 14 | env: 15 | IMAGE_NAME: cert-generator 16 | REGISTRY: ghcr.io/altinn 17 | steps: 18 | - name: Clone the repository 19 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 20 | 21 | - name: Buildah Action 22 | id: build-image 23 | uses: redhat-actions/buildah-build@7a95fa7ee0f02d552a32753e7414641a04307056 # v2.13 24 | with: 25 | image: ${{ env.IMAGE_NAME }} 26 | tags: ${{ github.sha }} latest 27 | containerfiles: | 28 | ./Dockerfile 29 | 30 | - name: Log in to the GitHub Container registry 31 | uses: redhat-actions/podman-login@4934294ad0449894bcd1e9f191899d7292469603 # v1.7 32 | with: 33 | registry: ${{ env.REGISTRY }} 34 | username: ${{ github.actor }} 35 | password: ${{ secrets.GITHUB_TOKEN }} 36 | 37 | - name: Push to GitHub Container Repository 38 | id: push-to-ghcr 39 | uses: redhat-actions/push-to-registry@5ed88d269cf581ea9ef6dd6806d01562096bee9c # v2.8 40 | with: 41 | image: ${{ steps.build-image.outputs.image }} 42 | tags: ${{ steps.build-image.outputs.tags }} 43 | registry: ${{ env.REGISTRY }} 44 | -------------------------------------------------------------------------------- /Generator.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.7.34202.233 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "cert-generator", "src\cert-generator\cert-generator.csproj", "{DF65DD2F-AFA2-4632-84A6-AA4CE040D9B2}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8DEF4338-4465-45A3-A25C-26B933709F84}" 9 | ProjectSection(SolutionItems) = preProject 10 | Dockerfile = Dockerfile 11 | LICENSE = LICENSE 12 | README.md = README.md 13 | EndProjectSection 14 | EndProject 15 | Global 16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 17 | Debug|Any CPU = Debug|Any CPU 18 | Release|Any CPU = Release|Any CPU 19 | EndGlobalSection 20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 21 | {DF65DD2F-AFA2-4632-84A6-AA4CE040D9B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {DF65DD2F-AFA2-4632-84A6-AA4CE040D9B2}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {DF65DD2F-AFA2-4632-84A6-AA4CE040D9B2}.Release|Any CPU.ActiveCfg = Release|Any CPU 24 | {DF65DD2F-AFA2-4632-84A6-AA4CE040D9B2}.Release|Any CPU.Build.0 = Release|Any CPU 25 | EndGlobalSection 26 | GlobalSection(SolutionProperties) = preSolution 27 | HideSolutionNode = FALSE 28 | EndGlobalSection 29 | GlobalSection(ExtensibilityGlobals) = postSolution 30 | SolutionGuid = {D52446D8-CF93-4692-94FF-6BFB6765D6E6} 31 | EndGlobalSection 32 | EndGlobal 33 | -------------------------------------------------------------------------------- /src/cert-generator/Helpers/CertificateExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Security.Cryptography; 4 | using System.Security.Cryptography.X509Certificates; 5 | using System.Text; 6 | 7 | namespace CertGenerator.Helpers 8 | { 9 | static class CertificateExtensions 10 | { 11 | /// 12 | /// Get the PEM version of the certificate. 13 | /// 14 | /// 15 | /// 16 | public static string ToPem(this X509Certificate2 certificate) 17 | { 18 | byte[] certBytes = certificate.Export(X509ContentType.Cert); 19 | 20 | return PrettyPrint("CERTIFICATE", certBytes); 21 | } 22 | 23 | /// 24 | /// Pretty-print the contents with BEGIN header and END footer and max-line-length of 64 characters. 25 | /// 26 | /// 27 | /// 28 | /// 29 | private static string PrettyPrint(string tag, byte[] contents) 30 | { 31 | StringBuilder sb = new StringBuilder(); 32 | string base64 = Convert.ToBase64String(contents); 33 | 34 | sb.AppendLine("-----BEGIN " + tag + "-----"); 35 | int lineLength = 64; 36 | for (int index = 0; index < base64.Length; index += lineLength) 37 | { 38 | int to = base64.Length - index; 39 | if (to > lineLength) 40 | to = lineLength; 41 | 42 | sb.AppendLine(base64.Substring(index, to)); 43 | } 44 | 45 | sb.AppendLine("-----END " + tag + "-----"); 46 | 47 | return sb.ToString(); 48 | } 49 | 50 | /// 51 | /// Get the string version of the RSA key in PEM format. 52 | /// 53 | /// 54 | /// 55 | public static string ToPrivateKeyPkcs(this X509Certificate2 certificate) 56 | { 57 | RSA rsa = certificate.GetRSAPrivateKey(); 58 | byte[] rsaBytes = rsa.ExportRSAPrivateKey(); 59 | 60 | return PrettyPrint("RSA PRIVATE KEY", rsaBytes); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/cert-generator/Interfaces/CertificateMetadata.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Security.Cryptography.X509Certificates; 5 | using System.Text; 6 | using System.Text.Json; 7 | using System.Threading.Tasks; 8 | 9 | namespace CertGenerator.Interfaces 10 | { 11 | /// 12 | /// Class for storing metadata about certificates 13 | /// 14 | class CertificateMetadata 15 | { 16 | /// 17 | /// SubjectName 18 | /// 19 | public string SubjectName { get; set; } 20 | 21 | /// 22 | /// Validity period of certificate 23 | /// 24 | public DateTime NotAfter { get; set; } 25 | 26 | /// 27 | /// Validity period of certificate 28 | /// 29 | public DateTime NotBefore { get; set; } 30 | 31 | /// 32 | /// The serial number of the certificate 33 | /// 34 | public string SerialNumber { get; set; } 35 | 36 | public static CertificateMetadata LoadFromCertificate(X509Certificate2 certificate) 37 | { 38 | CertificateMetadata metadata = new CertificateMetadata 39 | { 40 | NotBefore = certificate.NotBefore, 41 | NotAfter = certificate.NotAfter, 42 | SubjectName = certificate.Subject, 43 | SerialNumber = certificate.SerialNumber 44 | }; 45 | 46 | return metadata; 47 | } 48 | 49 | /// 50 | /// Load metadata from a metadata json file. 51 | /// 52 | /// 53 | /// 54 | public static async Task LoadFromJsonFile(string fileName) 55 | { 56 | string obj = await File.ReadAllTextAsync(fileName); 57 | return JsonSerializer.Deserialize(obj); 58 | } 59 | 60 | /// 61 | /// Save the metadata as json to a file. 62 | /// 63 | /// 64 | /// 65 | public async Task SaveJsonAsync(string fileName) 66 | { 67 | await File.WriteAllTextAsync(fileName, JsonSerializer.Serialize(this)); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/cert-generator/RootOptions.cs: -------------------------------------------------------------------------------- 1 | using CommandLine; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace CertGenerator 7 | { 8 | class BaseOptions 9 | { 10 | [Option('v', "verbose", Required = false, HelpText = "Use verbose output")] 11 | public bool Verbose { get; set; } 12 | 13 | [Option("subject", Required = true, HelpText ="The subject of the certificate. For instance: \"CN=Test\"")] 14 | public string SubjectName { get; set; } 15 | 16 | 17 | [Option("out-pfx", Required = true)] 18 | public string PfxFile { get; set; } 19 | 20 | [Option("out-pass", Required = false)] 21 | public string PfxPassword { get; set; } 22 | 23 | [Option("export-key", Required = false, Default = false)] 24 | public bool ExportKey { get; set; } 25 | 26 | [Option("no-pem", Required = false, Default = false)] 27 | public bool NoPem { get; set; } 28 | } 29 | 30 | [Verb("generate-ca", HelpText = "Generate root authority")] 31 | class RootOptions : BaseOptions 32 | { 33 | 34 | } 35 | 36 | [Verb("generate-ica", HelpText = "Generate intermediate authority")] 37 | class IcaOptions : BaseOptions 38 | { 39 | [Option("in-pfx", Required = true)] 40 | public string InPfxFile { get; set; } 41 | 42 | [Option("in-pass", Required = false)] 43 | public string InPfxPassword { get; set; } 44 | } 45 | 46 | [Verb("generate-self-signed", HelpText = "Generate self-signed certificate")] 47 | class SelfSignedOptions : BaseOptions 48 | { 49 | [Option("no-dns", Default = true, HelpText ="Do not add a dns name to the certificate")] 50 | public bool DoNotAddDns { get; set; } 51 | 52 | [Option("valid-days", Default = 365, HelpText = "How many days is this certificate valid?")] 53 | public int ValidDays { get; set; } 54 | 55 | [Option("not-before", Required = false, Default = "", HelpText = "Format: dd.MM.yyyy HH:mm")] 56 | public string NotBefore { get; set;} 57 | } 58 | 59 | [Verb("generate", HelpText = "Generate client certificate")] 60 | class Options : BaseOptions 61 | { 62 | [Option("in-pfx", Required = true)] 63 | public string InPfxFile { get; set; } 64 | 65 | [Option("in-pass", Required = false)] 66 | public string InPfxPassword { get; set; } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/cert-generator/Implementation/CertificateAuthority.cs: -------------------------------------------------------------------------------- 1 | using CertGenerator.Interfaces; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Security.Cryptography; 7 | using System.Security.Cryptography.X509Certificates; 8 | using System.Text; 9 | 10 | namespace CertGenerator.Implementation 11 | { 12 | /// 13 | /// Implements basic support for a Certificate Authority. 14 | /// 15 | class CertificateAuthority : ICertificateAuthority, IDisposable 16 | { 17 | protected X509Certificate2 _caCertificate; 18 | protected int _defaultValidToDays = 365 * 100; 19 | protected int _defaultKeyLength = 2048; 20 | 21 | public CertificateAuthority() 22 | { 23 | 24 | 25 | } 26 | 27 | public CertificateAuthority(string pfxFile, string password) 28 | { 29 | this.SetupAuthorityFromFile(pfxFile, password); 30 | } 31 | 32 | protected void SetupAuthorityFromFile(string pfxFile, string password) 33 | { 34 | try 35 | { 36 | this._caCertificate = new X509Certificate2(pfxFile, password); 37 | } 38 | catch(Exception) 39 | { 40 | // Azure key vault returns pfx files in BASE64 encoded format. 41 | this._caCertificate = new X509Certificate2(Convert.FromBase64String(File.ReadAllText(pfxFile)), password); 42 | } 43 | } 44 | 45 | protected byte[] GenerateSerialNumber() 46 | { 47 | // We don't really care about the serial number in our limited implementation of CA. 48 | // We are just interested in getting valid certificates that live in a very limited environment. 49 | using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) 50 | { 51 | // 32 bytes = 256 bits. 52 | byte[] serial = new byte[18]; 53 | rng.GetBytes(serial); 54 | 55 | return serial; 56 | } 57 | } 58 | 59 | /// 60 | /// Dispose and cleanup any resources used. 61 | /// 62 | public void Dispose() 63 | { 64 | this._caCertificate?.Dispose(); 65 | this._caCertificate = null; 66 | } 67 | 68 | /// 69 | public X509Certificate2 GenerateAndSignCertificate(string subjectName) 70 | { 71 | using (RSA newKey = RSA.Create(_defaultKeyLength)) 72 | { 73 | // Create the reguest 74 | CertificateRequest request = new CertificateRequest(subjectName, newKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); 75 | var s = new SubjectAlternativeNameBuilder(); 76 | s.AddDnsName(subjectName.Substring("CN=".Length)); 77 | 78 | request.CertificateExtensions.Add(s.Build()); 79 | request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, true)); 80 | 81 | // This is no CA 82 | request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); 83 | 84 | // Add default TLS key usages 85 | request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, false)); 86 | 87 | 88 | request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection 89 | { 90 | new Oid("1.3.6.1.5.5.7.3.1"), // Server-auth 91 | new Oid("1.3.6.1.5.5.7.3.2") // Client-auth 92 | }, true)); 93 | 94 | X509Certificate2 certificate = request.Create(this._caCertificate, DateTimeOffset.UtcNow.AddDays(-1), 95 | this._caCertificate.NotAfter.AddDays(-10), GenerateSerialNumber()); 96 | 97 | return certificate.CopyWithPrivateKey(newKey); 98 | } 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/cert-generator/Program.cs: -------------------------------------------------------------------------------- 1 | using CertGenerator.Implementation; 2 | using System; 3 | using System.IO; 4 | using System.Security.Cryptography.X509Certificates; 5 | using CommandLine; 6 | using CertGenerator.Helpers; 7 | using System.Security.Cryptography; 8 | 9 | namespace CertGenerator 10 | { 11 | class Program 12 | { 13 | static int Main(string[] args) 14 | { 15 | 16 | int result = CommandLine.Parser.Default.ParseArguments(args) 17 | .MapResult( 18 | (RootOptions ro) => RunRootAuthority(ro), 19 | (IcaOptions io) => RunIntermediateOptions(io), 20 | (SelfSignedOptions so) => RunSelfSignedOptions(so), 21 | (Options o) => RunCertificateOptions(o), 22 | errs => 1); 23 | 24 | return result; 25 | } 26 | 27 | static int RunRootAuthority(RootOptions ro) 28 | { 29 | using (CertificateRootAuthority rootAuthority = new CertificateRootAuthority()) 30 | { 31 | X509Certificate2 cert = rootAuthority.GenerateRootCertificate(ro.SubjectName); 32 | byte[] pfxBytes = cert.Export(X509ContentType.Pfx, ro.PfxPassword); 33 | File.WriteAllBytes(ro.PfxFile + ".pfx", pfxBytes); 34 | 35 | if (false == ro.NoPem) 36 | File.WriteAllText(ro.PfxFile + ".pem", cert.ToPem()); 37 | } 38 | 39 | return 0; 40 | } 41 | 42 | static int RunIntermediateOptions(IcaOptions io) 43 | { 44 | using (CertificateRootAuthority rootAuthority = new CertificateRootAuthority(io.InPfxFile, io.InPfxPassword)) 45 | { 46 | X509Certificate2 cert = rootAuthority.GenerateAndSignIntermediateCertificate(io.SubjectName); 47 | byte[] pfxBytes = cert.Export(X509ContentType.Pfx, io.PfxPassword); 48 | File.WriteAllBytes(io.PfxFile + ".pfx", pfxBytes); 49 | 50 | 51 | if (false == io.NoPem) 52 | File.WriteAllText(io.PfxFile + ".pem", cert.ToPem()); 53 | 54 | } 55 | 56 | return 0; 57 | } 58 | 59 | static int RunSelfSignedOptions(SelfSignedOptions so) 60 | { 61 | using (CertificateRootAuthority rootAuthority = new CertificateRootAuthority()) 62 | { 63 | DateTimeOffset notBefore = DateTimeOffset.UtcNow.AddDays(-1); 64 | 65 | if (!string.IsNullOrEmpty(so.NotBefore)) 66 | { 67 | notBefore = DateTimeOffset.ParseExact(so.NotBefore, "dd.MM.yyyy HH:mm", null); 68 | } 69 | 70 | 71 | 72 | DateTimeOffset notAfter = notBefore.AddDays(so.ValidDays); 73 | 74 | X509Certificate2 cert = rootAuthority.GenerateSelfSignedCertificate(so.SubjectName, so.DoNotAddDns, notBefore, notAfter); 75 | 76 | byte[] pfxBytes = cert.Export(X509ContentType.Pfx, so.PfxPassword); 77 | File.WriteAllBytes(so.PfxFile + ".pfx", pfxBytes); 78 | 79 | if (false == so.NoPem) 80 | File.WriteAllText(so.PfxFile + ".pem", cert.ToPem()); 81 | 82 | if (so.ExportKey) 83 | { 84 | File.WriteAllText(so.PfxFile + ".key", cert.ToPrivateKeyPkcs()); 85 | } 86 | } 87 | 88 | return 0; 89 | } 90 | 91 | static int RunCertificateOptions(Options o) 92 | { 93 | using (CertificateAuthority authority = new CertificateAuthority(o.InPfxFile, o.InPfxPassword)) 94 | { 95 | X509Certificate2 cert = authority.GenerateAndSignCertificate(o.SubjectName); 96 | byte[] pfxBytes = cert.Export(X509ContentType.Pfx, o.PfxPassword); 97 | File.WriteAllBytes(o.PfxFile + ".pfx", pfxBytes); 98 | 99 | if (false == o.NoPem) 100 | File.WriteAllText(o.PfxFile + ".pem", cert.ToPem()); 101 | 102 | if (o.ExportKey) 103 | { 104 | File.WriteAllText(o.PfxFile + ".key", cert.ToPrivateKeyPkcs()); 105 | } 106 | } 107 | 108 | return 0; 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/cert-generator/Implementation/CertificateRootAuthority.cs: -------------------------------------------------------------------------------- 1 | using CertGenerator.Interfaces; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Security.Cryptography; 6 | using System.Security.Cryptography.X509Certificates; 7 | using System.Text; 8 | 9 | namespace CertGenerator.Implementation 10 | { 11 | class CertificateRootAuthority : CertificateAuthority, ICertificateRootAuthority 12 | { 13 | private int _defaultValidRootDays = 365 * 20; 14 | 15 | public CertificateRootAuthority() 16 | { 17 | 18 | } 19 | 20 | public CertificateRootAuthority(string pfxFile, string password) 21 | : base(pfxFile, password) 22 | { 23 | 24 | } 25 | 26 | public X509Certificate2 GenerateAndSignIntermediateCertificate(string subjectName) 27 | { 28 | if (this._caCertificate == null) 29 | throw new Exception("Missing root certificate."); 30 | 31 | 32 | using (RSA key = RSA.Create(_defaultKeyLength)) 33 | { 34 | CertificateRequest request = new CertificateRequest(subjectName, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); 35 | 36 | request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, true)); 37 | 38 | // This is a CA 39 | request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, true, 1, true)); 40 | 41 | // Add default TLS key usages 42 | request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.CrlSign | X509KeyUsageFlags.KeyCertSign, true)); 43 | 44 | 45 | request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection 46 | { 47 | new Oid("1.3.6.1.5.5.7.3.1"), // Server-auth 48 | new Oid("1.3.6.1.5.5.7.3.2") // Client-auth 49 | }, true)); 50 | 51 | 52 | X509Certificate2 certificate = request.Create(_caCertificate, DateTimeOffset.UtcNow.AddDays(-1), 53 | _caCertificate.NotAfter.AddDays(-5), GenerateSerialNumber()); 54 | 55 | return certificate.CopyWithPrivateKey(key); 56 | } 57 | 58 | } 59 | 60 | public X509Certificate2 GenerateSelfSignedCertificate(string subjectName, bool doNotAddDnsName, DateTimeOffset notBefore, DateTimeOffset notAfter) 61 | { 62 | using (RSA key = RSA.Create(_defaultKeyLength)) 63 | { 64 | CertificateRequest request = new CertificateRequest(subjectName, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); 65 | 66 | request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, true)); 67 | 68 | // This is CA 69 | request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true)); 70 | 71 | // Add default TLS key usages 72 | request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true)); 73 | 74 | 75 | request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection 76 | { 77 | new Oid("1.3.6.1.5.5.7.3.1"), // Server-auth 78 | new Oid("1.3.6.1.5.5.7.3.2") // Client-auth 79 | }, true)); 80 | 81 | if (false == doNotAddDnsName) 82 | { 83 | var s = new SubjectAlternativeNameBuilder(); 84 | s.AddDnsName(subjectName.Substring("CN=".Length)); 85 | request.CertificateExtensions.Add(s.Build()); 86 | } 87 | 88 | X509Certificate2 certificate = request.CreateSelfSigned(notBefore, notAfter); 89 | 90 | 91 | return certificate; 92 | } 93 | 94 | } 95 | public X509Certificate2 GenerateRootCertificate(string subjectName) 96 | { 97 | using (RSA key = RSA.Create(_defaultKeyLength)) 98 | { 99 | CertificateRequest request = new CertificateRequest(subjectName, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); 100 | 101 | request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, true)); 102 | 103 | // This is CA 104 | request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, true, 2, true)); 105 | 106 | // Add default TLS key usages 107 | request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.CrlSign | X509KeyUsageFlags.KeyCertSign, true)); 108 | 109 | 110 | request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection 111 | { 112 | new Oid("1.3.6.1.5.5.7.3.1"), // Server-auth 113 | new Oid("1.3.6.1.5.5.7.3.2") // Client-auth 114 | }, true)); 115 | 116 | X509Certificate2 certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), 117 | DateTimeOffset.UtcNow.AddDays(_defaultValidRootDays)); 118 | 119 | 120 | return certificate; 121 | } 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | --------------------------------------------------------------------------------