logo
down
shadow

CMS signing in .NET with certificate chain not in local trusted certificate store


CMS signing in .NET with certificate chain not in local trusted certificate store

By : bummi huiop
Date : November 14 2020, 04:48 PM
may help you . Example CMS Signing with BouncyCastle for .NET
You could use the BouncyCastle crypto library for .NET, which contains its own X509 certificate and CMS signing machinery. A lot of the examples and documentation on the web are for Java, as BouncyCastle was a Java library first. I've used the answer to this Stackoverflow question as a starting point for the certificate and key loading, and added the CMS signing. You may have to tweak parameters to produce the results you want for your use case.
code :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

using Org.BouncyCastle.Cms;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.X509.Store;

class Program
{
  protected static byte[] SignWithSystem(byte[] data, AsymmetricKeyParameter key, X509Certificate cert, X509Certificate[] chain)
  {
    var generator = new CmsSignedDataGenerator();
    // Add signing key
    generator.AddSigner(
      key,
      cert,
      "2.16.840.1.101.3.4.2.1"); // SHA256 digest ID
    var storeCerts = new List<X509Certificate>();
    storeCerts.Add(cert); // NOTE: Adding end certificate too
    storeCerts.AddRange(chain); // I'm assuming the chain collection doesn't contain the end certificate already
    // Construct a store from the collection of certificates and add to generator
    var storeParams = new X509CollectionStoreParameters(storeCerts);
    var certStore = X509StoreFactory.Create("CERTIFICATE/COLLECTION", storeParams);
    generator.AddCertificates(certStore);

    // Generate the signature
    var signedData = generator.Generate(
      new CmsProcessableByteArray(data),
      false); // encapsulate = false for detached signature
    return signedData.GetEncoded();
  }

  static void Main(string[] args)
  {
    try
    {
      // Load end certificate and signing key
      AsymmetricKeyParameter key;
      var signerCert = ReadCertFromFile(@"C:\Temp\David.p12", "pin", out key);

      // Read CA cert
      var caCert = ReadCertFromFile(@"C:\Temp\CA.cer");
      var certChain = new X509Certificate[] { caCert };

      var result = SignWithSystem(
        Guid.NewGuid().ToByteArray(), // Any old data for sake of example
        key,
        signerCert,
        certChain);

      File.WriteAllBytes(@"C:\Temp\Signature.data", result);
    }
    catch (Exception ex)
    {
      Console.WriteLine("Failed : " + ex.ToString());
      Console.ReadKey();
    }
  }

  public static X509Certificate ReadCertFromFile(string strCertificatePath)
  {
    // Create file stream object to read certificate
    using (var keyStream = new FileStream(strCertificatePath, FileMode.Open, FileAccess.Read))
    {
      var parser = new X509CertificateParser();
      return parser.ReadCertificate(keyStream);
    }
  }

  // This reads a certificate from a file.
  // Thanks to: http://blog.softwarecodehelp.com/2009/06/23/CodeForRetrievePublicKeyFromCertificateAndEncryptUsingCertificatePublicKeyForBothJavaC.aspx
  public static X509Certificate ReadCertFromFile(string strCertificatePath, string strCertificatePassword, out AsymmetricKeyParameter key)
  {
    key = null;
    // Create file stream object to read certificate
    using (var keyStream = new FileStream(strCertificatePath, FileMode.Open, FileAccess.Read))
    {
      // Read certificate using BouncyCastle component
      var inputKeyStore = new Pkcs12Store();
      inputKeyStore.Load(keyStream, strCertificatePassword.ToCharArray());

      var keyAlias = inputKeyStore.Aliases.Cast<string>().FirstOrDefault(n => inputKeyStore.IsKeyEntry(n));

      // Read Key from Aliases  
      if (keyAlias == null)
        throw new NotImplementedException("Alias");
      key = inputKeyStore.GetKey(keyAlias).Key;
      //Read certificate into 509 format
      return (X509Certificate)inputKeyStore.GetCertificate(keyAlias).Certificate;
    }
  }
}


Share : facebook icon twitter icon
Transfer trusted certificate (plus private key / chain) from Java keystore (jks) to Windows Certificate Manager

Transfer trusted certificate (plus private key / chain) from Java keystore (jks) to Windows Certificate Manager


By : Britishdragon01
Date : March 29 2020, 07:55 AM
like below fixes the issue This seems to work for exporting the certificate but not the entire chain, the trick is to specify the srcalias:
code :
keytool -v -importkeystore -srckeystore .keystore -srcalias mykey -destkeystore myp12file.p12 -deststoretype PKCS12
API: Openssl / Wincrypt : unable to get local issuer certificate / certificate not trusted

API: Openssl / Wincrypt : unable to get local issuer certificate / certificate not trusted


By : Bonny
Date : March 29 2020, 07:55 AM
Does that help This code work very well, it's just my Windows which has no update since two years. My CA-certificates in Windows are too old.
by
Xamarin MSBuild - error MSB3323: Unable to find manifest signing certificate in the certificate store

Xamarin MSBuild - error MSB3323: Unable to find manifest signing certificate in the certificate store


By : shashi kumar
Date : March 29 2020, 07:55 AM
I wish did fix the issue. to this post I had to open up the iOS project and delete the following tags:
... ... ... ...
How can I add a server certificate to my local trusted Java key store?

How can I add a server certificate to my local trusted Java key store?


By : Dan
Date : March 29 2020, 07:55 AM
Script for Install SSL Certificate on Trusted Root Certificate Store

Script for Install SSL Certificate on Trusted Root Certificate Store


By : aa-beeZzz
Date : March 29 2020, 07:55 AM
With these it helps Bit of an old post but thought I would throw in my two cents anyway. You are right, that command in a batch script will install the certificate root_ca.cer into the trusted CA store. I would modify the line to be:
Related Posts Related Posts :
  • Console application doesn't obey Thread.Join
  • System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
  • Creating a scripting environment for a C# program
  • Is it reasonable to replace .Equals with a method rather than override it?
  • How I can capture multiple keys?
  • How to have all my classes default functionalities like .ToString method
  • Business Object properties: model as Objects or Enums?
  • Loading this assembly would produce a different grant set from other instances
  • How to call a method without first calling it's constructor in C#
  • Can't set a date time in one of my entity framework objects, says NullReferenceException
  • GETJob() Win32 Print spooler api 64bit The parameter is incorrect, how to fix?
  • Switch Case Causing Trouble In Going To A particular Function
  • Switch Case Calling A Function Based On The User's Choice
  • Accessing WebBrowser on different Threads
  • CPU Usage Avoid 100% With Environment.ProcessorCount?
  • Select distinct categories from database
  • C# app getting Watson dialog when calling TerminateProcess
  • The underlying provider failed on Open in entity framework connection
  • Compile a library without checking references
  • Can we create and access a registry key in HKEY_LOCAL_MACHINE without running application with admin permissions in C#
  • Control light intensity with a UI slider
  • Threading (Does these threads exits or aborts itself?)
  • Change the function of a button if Logged in
  • how to accept value in date format in textbox in C# windows form?
  • remove the lines from RichtextBox?
  • How to call String.Split that takes string as separator?
  • Specify task timeout in parallel linq to objects
  • comparing two custom objects to prevent duplicates
  • How to Print Text from ComboBox into a MessageBox
  • How can I do a Func<object[],Expression<Func<T,bool>>> dynamic?
  • C# SqlDataReader No data exists for the row/column
  • My code is not giving the desired output
  • Is it possible to have multiple MVC routes point to the same controller/view?
  • Updating Listbox results in " Invalid cross-thread access."
  • Finding Elbow Angle with Kinect
  • Host a mvc web api application in the sub-folder of a website
  • How to generate a sequential unique id in a thread-safe way
  • How to add a separator to a WPF combobox that is databound?
  • optimize linq query with related entities
  • Optimize this code for large input
  • Is there any way to clear all list box short way?
  • ACR122 Device Programming sample does not find reader
  • Parallel Library: does a delay on one degree of parallelism delay all of them?
  • How to convert a var which contains Long to an Long[]
  • Quickly prune and create valid data combinations
  • Get 3 parameters out of a Dictionary<string, Dictionary<string Action>>
  • Regex IsMatch taking too long to execute
  • Shuffling divs using C# behindcode
  • ASP.NET Project and IE10 Compatibility Mode issues in Windows 7
  • Why can't I loop through this dictionary?
  • RavenDB Stream for Unbounded Results - Connection Resilience
  • How to remove the focus border of a CheckBox in C# Visual Studio?
  • Exception while using String.Format "Index (zero based) must be greater than or equal to zero and less than the siz
  • Caching an LDAP connection
  • C# How to detect kill event sender
  • How to Display Splashscreen and login form at same time using c#
  • Read .sql script with parameters
  • Why would I need to compile/generate methods/code at runtime?
  • Unable to create a constant value of type 'Project.Models.Subcategory'. Only primitive types or enumeration types are su
  • How to run possibly synchronous or possibly asynchronous code?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org