Configuration problems with TLS in Golang + C# - c#

I am developing a video game and I am quite lost in the subject of secure communication between client and server. If anyone can give me a cable I would really appreciate it.
My project is based on a client (c # - Unity) + server (Go) that communicate through a TCP socket. Now I am adding security with TLS 1.2, and although following several articles and posts I have gotten a solution that apparently works, I think that I am not really getting a secure communication since although I change the client's digital certificate for a totally different one and unrelated to the keys everything still works the same, which makes me think that something I have not configured correctly
Regarding the use of RSA keys, I am using the following scheme:
Server: Digital certificate generated with the private key (.pem) + private key to create the socket (.pem)
//// Server Go ////
cert, _ := tls.LoadX509KeyPair(PemCertPath, PrivateKeyPath)
config := tls.Config{MinVersion: tls.VersionTLS12, Certificates: []tls.Certificate{cert}}
service := ServerAddress + ":" + strconv.Itoa(ServerPort)
socket, _ := tls.Listen("tcp", service, &config)
Client: Digital certificate generated with the private key (.pem) to connect to the socket.
//// Client C# ////
byte[] certBytes = Convert.FromBase64String("AS9ggSEPw5yp7+IH5S9ingq+.........."); //Cert .pem
X509Certificate2 cert = new X509Certificate2(certBytes);
X509CertificateCollection certCollection = new X509CertificateCollection(new X509Certificate[] { cert });
tcpClient = new TcpClient(serverAddress, serverPort);
sslStreamSerma = new SslStream(tcpClient.GetStream(), false, ValidateCertificate);
sslStreamSerma.AuthenticateAsClient(sermaName, certCollection, SslProtocols.Tls12, false);
I am quite confused with this ... I do not understand what is happening here so that regardless of the digital certificate that the client uses, the communication continues to work ... Should I create 2 pairs of keys, one for the client and one for the server? Should the certificate be generated with the public key?
If anyone can help me I would really appreciate it ...

The problem is that your client certificate doesn't have associated private key which is required to perform client authentication.
byte[] certBytes = Convert.FromBase64String("AS9ggSEPw5yp7+IH5S9ingq+.........."); //Cert .pem
X509Certificate2 cert = new X509Certificate2(certBytes);
this code part reads only public part of the certificate, not private key.

Related

How to submit a CSR to Windows CA for signing from C#?

My scenario:
I have an EC2 instance running Windows Server 2016 DataCenter OS in it. This EC2 instance is configured to work as CA and IIS server (I am testing cloudhsm so it is okay for me to have multiple services in the same server). My CA is configured with RSA#Cavium Key Storage Provider (as it supports AWS CloudHSM Key Storage Provider). Now from my sample .Net WebAPI app, I can create a CSR using below code:
private async Task<CertificateSigningResponse> ActualSigningAsync(CertificateSigningRequest csr)
{
CertificateSigningResponse certificateSigningResponse;
try
{
using (RSA rsa = RSA.Create(csr.KeySize))
{
CertificateRequest request = new CertificateRequest("CN=servername-CA2", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
OidCollection oidCollection = new OidCollection();
oidCollection.Add(new Oid("1.3.6.1.5.5.7.3.8"));
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(oidCollection, true));
request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false));
var serialNumberInBytes = System.Text.Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
/*
// below line creates a self signed certificate
var selfSignedCertificate = request.Create(
new X500DistinguishedName("CN=servername-CA2"),
X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1),
DateTimeOffset.Now,
DateTimeOffset.Now.AddMonths(1),
serialNumberInBytes);
*/
var certSigningRequest = request.CreateSigningRequest(X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1));
if (certSigningRequest != null)
{
certificateSigningResponse = PopulateCertificateSigningResponse(JsonConvert.SerializeObject(certSigningRequest), $"Sample Cert with Sl#: {certSigningRequest}");
}
else
{
certificateSigningResponse = PopulateCertificateSigningResponse("", $"Error: {request.PublicKey}");
}
}
}
catch (Exception ex)
{
certificateSigningResponse = PopulateCertificateSigningResponse(string.Empty, ex.Message);
}
return certificateSigningResponse;
}
Now, I want to send this CSR to my CA (which is running on EC2) and get it signed. Once signed, I want to send the signed certificate back to the user. Currently, I have hosted my sample webapi app on the same EC2 instance. This app actually exposes an endpoint, which I can hit via postman and pass in some data as request body (POST).
So, ideally, the app receives my POST request and extracts data from it, then using that data, it is creating a csr. And now I want to send this csr to my CA, get it signed and finally return the signed certificate to user. Below pseudo code may give you some idea about my requirements:
//pseudo code; not existed
// request is generated in above code
var caService = new CAService();//can use my ca info i.e. name, public dns, ip
var response = await caService.SignAsync(request);//response should be a cert
return response;
I have seen few posts using CertUtilLib/CertEnrollLib but I want to achieve this by fully managed code. Also if it is not possible, please suggest me some alternatives. Thanks.
EDIT 1 (after Michal's comment)
Below are some info for your interest:
Current Scenario:
we are using a 3rd party API to sign some critical data.
In this way, we make a POST request to that particular endpoint with the data we wanted to be signed.
The 3rd party API handles everything for us behind the scene. We know that they are using some HSM service at their end to sign data.
My intention:
I am trying to achieve the same functionality using AWS CloudHSM.
The calling process should be same, i.e. we should still call an endpoint with data and get the signed copy of the data.
For this, my understanding was to create the CSR at server end and sign it using CloudHSM from within the server.
For that, I have created a sample .Net API app that exposes an endpoint where I can post my data to be signed.
Then it is my app's responsibility to create the CSR (I did it already), and then send the CSR to a CA (this is my EC2 Windows
Server 2016 instance which has the CA feature enabled on it) for
signing (I am stuck here at the moment).

C# m2mqtt to connect to AWS broker using Root CA, key, and certificate

I am trying to use M2MQtt library to connect to AWS MQTT broker using a root CA, client certificate and key. I am using the following C# client connection code
MqttClient client = new MqttClient(
endPoint,
MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT,
true,
new X509Certificate2(#"ca.pem"),
new X509Certificate2(#"certificate.pem"),
MqttSslProtocols.TLSv1_2
);
client.Connect(Guid.NewGuid().ToString());
however, this fails with a FormatException error. It's probably related to the fact that I don't know where to pass in the private key for this connection. This is something that I already have working, prototyped in Python using AWSIoTPythonSDK (see below)
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
f = open('mqttEndpoint.txt', 'r')
awsHost = f.read()
f.close()
myAWSIoTMQTTClient = AWSIoTMQTTClient('foo')
myAWSIoTMQTTClient.configureEndpoint(awsHost, 8883)
myAWSIoTMQTTClient.configureCredentials('ca.pem', 'id_rsa', 'certificate.pem')
Does anyone know how this is supposed to work?
I figured out my problem. The clue was the fact that to properly authenticate against AWS, you need to provide both the certificate (a PEM in my case) as well as the private key, which I could not figure out how to pass into MqttClient() constructor, because it takes only one "certificate".
The solution is to use a PFX/P12 certificate, which includes inside it both a PEM and a private key (thank you, Microsoft, for being different). There are many resources that explain how to create a PFX from a PEM+key (i.e. here, here, here, here, etc). Then you have to use a X509Certificate2() class to pull in the PFX file (that '2' is
MqttClient client = new MqttClient(
endPoint,
MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT,
true,
rootCa,
new X509Certificate2(#"certificate.pfx", #""); // My PFX was created with a blank password, hence empty string as 2nd arg
MqttSslProtocols.TLSv1_2
);
client.Connect(Guid.NewGuid().ToString());

UWP app HttpClient HTTPS client certificate problems

I'm writing a UWP app in C# that is eventually destined for IoT, but right now I've only been debugging locally. I'm using Windows.Web.Http.HttpClient to connect to a self-hosted WCF REST web service that I've also written and have running as a Console app on the same machine for testing. The service requires mutual authentication with certificates, so I have a CA cert, service cert, and client cert.
My UWP code works like this:
Check app cert store for client cert and CA cert installed.
If not, install from PFX file and CER file, respectively.
Attach the Certificate to the HttpBaseProtocolFilter and add the filter to the HttpClient
Call the HttpClient.PostAsync
After I call PostAsync I get the following error: An Error Occurred in the Secure Channel Support. After plenty of searching online, and by common sense, I'm pretty sure HttpClient is barfing because of a problem establishing the mutually-authenticated SSL connection. But based on my troubleshooting I can't figure why.
To troublshoot further, I've written a plain old Console app using System.Net.Http.HttpClient, attached the client certificate to the request and everything works great. Sadly, System.Net isn't fully supported on UWP. I've also tried NOT attaching the certificate to the UWP HttpClient and the app prompts me with a UI to select an installed certificate. I select the correct cert and still get the same exception (this at least lets me know the cert is installed correctly and validating properly with the CA from the app's perspective). In additon, I hit the GET on the web service from a browser, select the client cert when prompted, and am able to download a file.
I've tried using Fiddler and, I assume because of the way it proxies traffic, it seems to work a little bit further, except my web service rejects the request as Forbidden (presumably because Fiddler is not including the correct client cert in the request). I haven't hit up Wireshark yet because it's a pain to get Wireshark to work using localhost on Windows.
My next step is to start changing the web service to not require client authentication and see if that is the problem.
Two questions: Why is Windows.Web.Http.HttClient not working in this case? And, less important, any recommendations on good HTTP monitoring tools to help me debug this further?
This MSDN post proved to have the answer. Seems like an oversight on MS part requiring a separate, meaningless call to the API beforehand. Oh well.
http://blogs.msdn.com/b/wsdevsol/archive/2015/03/26/how-to-use-a-shared-user-certificate-for-https-authentication-in-an-enterprise-application.aspx
Excerpt from the article:
However, the security subsystem requires user confirmation before allowing access to a certificates private key of a certificate stored in the shared user certificates store. To complicate matters, if a client certificate is specified in code then the lower level network functions assume the application has already taken care of this and will not prompt the user for confirmation.
If you look at the Windows Runtime classes related to certificates you won’t find any method to explicitly request access to the certificate private key, so what is the app developer to do?
The solution is to use the selected certificate to 'Sign' some small bit of data. When an application calls CryptographicEngine.SignAsync, the underlying code requests access to the private key to do the signing at which point the user is asked if they want to allow the application to access the certificate private key. Note that you must call 'Async' version of this function because the synchronous version of the function: Sign, uses an option that blocks the display of the confirmation dialog.
For example:
public static async Task<bool> VerifyCertificateKeyAccess(Certificate selectedCertificate)
{
bool VerifyResult = false; // default to access failure
CryptographicKey keyPair = await PersistedKeyProvider.OpenKeyPairFromCertificateAsync(
selectedCertificate, HashAlgorithmNames.Sha1,
CryptographicPadding.RsaPkcs1V15);
String buffer = "Data to sign";
IBuffer Data = CryptographicBuffer.ConvertStringToBinary(buffer, BinaryStringEncoding.Utf16BE);
try
{
//sign the data by using the key
IBuffer Signed = await CryptographicEngine.SignAsync(keyPair, Data);
VerifyResult = CryptographicEngine.VerifySignature(keyPair, Data, Signed);
}
catch (Exception exp)
{
System.Diagnostics.Debug.WriteLine("Verification Failed. Exception Occurred : {0}", exp.Message);
// default result is false so drop through to exit.
}
return VerifyResult;
}
You can then modify the earlier code example to call this function prior to using the client certificate in order to ensure the application has access to the certificate private key.
Add the Certificate file your Project
Add the Certificate to the Manifested file (give file path in attachment)
the Frist Service Call of in Ur Project use to ignore the certificate validation Following Code is most Suitable for Login Function.
try
{
var filter = new HttpBaseProtocolFilter();
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationFailure);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationInformationMissing);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.WrongUsage);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.IncompleteChain);
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(filter);
TimeSpan span = new TimeSpan(0, 0, 60);
var cts = new CancellationTokenSource();
cts.CancelAfter(span);
var request = new Windows.Web.Http.HttpRequestMessage()
{
RequestUri = new Uri(App.URL + "/oauth/token"),
Method = Windows.Web.Http.HttpMethod.Post,
};
//request.Properties. = span;
string encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(Server_Username + ":" + Server_Password));
var values = new Dictionary<string, string>
{ { "grant_type", "password" },{ "username", Uname}, { "password", Pwd }};
var content = new HttpFormUrlEncodedContent(values);
request.Headers.Add("Authorization", "Basic " + encoded);
request.Content = content;
User root = new User();
using (Windows.Web.Http.HttpResponseMessage response = await client.SendRequestAsync(request).AsTask(cts.Token))
{
HttpStatusCode = (int)response.StatusCode;
if (HttpStatusCode == (int)HttpCode.OK)
{
using (IHttpContent content1 = response.Content)
{
var jsonString = await content1.ReadAsStringAsync();
root = JsonConvert.DeserializeObject<User>(jsonString);
App.localSettings.Values["access_token"] = root.Access_token;
App.localSettings.Values["refresh_token"] = root.Refresh_token;
App.localSettings.Values["expires_in"] = root.Expires_in;
var json = JsonConvert.SerializeObject(root.Locations);
App.localSettings.Values["LocationList"] = json;
App.localSettings.Values["LoginUser"] = Uname;
}
}
}
}
catch (Exception ex)
{
ex.ToString();
}

Socket and Authentication failed because the remote party has closed the transport stream exception in WPF

I am trying to connect with Java netty based server, which auto generates certificates for itself (and server guys told me, that is accepting any certificate from client side for now).
My task was to migrate TcpSocket connection into Tls encrypted connection.
First of all, I converted TcpSocket into NetworkStream:
using (var client = new NetworkStream(connection.TcpSocket))
{
if (client.CanRead)
{
client.BeginRead(recvState.DataBuffer, 0, recvState.DataBuffer.Length, ReceiveCallback,
recvState);
}
}
and that is working perfectly. So then, I decided to build SslAuthentication - like here:
using (var client = new NetworkStream(connection.TcpSocket))
using (var sslStream = new SslStream(client, false, App_CertificateValidation))
{
var clientCertificate = new X509Certificate2("client.pfx");
var clientCertificateCollection = new X509Certificate2Collection(new[] { clientCertificate });
sslStream.AuthenticateAsClient("MyServer", clientCertificateCollection, SslProtocols.Tls, false);
if (sslStream.CanRead)
{
sslStream.BeginRead(recvState.DataBuffer, 0, recvState.DataBuffer.Length, ReceiveCallback,
recvState);
}
}
Where client.pfx is random certificate with no password, as a file in project and also imported into Current User Certificates > Personal > Certificates in certmgr.msc.
The problem is AuthenticateAsClient throws an
System.IO.IOException: Authentication failed because the remote party
has closed the transport stream exception.
Also, if the hostname in AuthenticateAsCtlient method means anything, if server accepts every certificate? Should I put there something significant?
I still can contact with the server guys, so I can ask them about everything - do we need any additional information?
Got it working.
The server who is hosting the socket server MUST have installed on its Certification Storage the certificate WITH the Private Key. If you install it without it (just the certificate or just the public key) you will get those errors of authentication failure.
I hope it help.

Cipher selection for sslStream in .NET 4.5

I am trying to create a TLS1.1/TLS1.2 server using .Net's sslStream class. It appears that by default the only cipher suites that this stream accepts are:
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
I'd like to enable non-ECDHE versions of these (i.e. TLS_RSA_WITH_AES_128_CBC_SHA256). I googled around a bit and people talk about changing cipher suites by modifying the default SChannel settings -- either through the "SSL Cipher Suite Order" or using CNG functions: http://msdn.microsoft.com/en-us/library/windows/desktop/bb870930(v=vs.85).aspx
However, I tried this and I can't get anything to work. Using the above link's C++ code to list the enabled cipher suites with BCryptEnumContextFunctions() shows that the cipher suites I want are enabled by default. I even added TLS_RSA_WITH_AES_128_CBC_SHA256 as a top priority suite, and sslStream still refuses a TLS connection from a client that only supports that cipher (Exception: "The client and server cannot communicate, because they do not possess a common algorithm") Any idea what is going on here?
(By the way, if my client supports one of the ECDHE cipher suites, everything works great)
How are other folks implementing TLS in .Net 4.5? Should I be looking at opensource solutions? What about a wrapper for SChannel to use the CNG api more directly?
I contacted Microsoft's technical support and after using their proprietary tracing ability, it turned out that the certificate I had installed on my server did not have it's private key marked as an "exchange key". Apparently the private key counterpart of every public key in the certificate store has certain uses for which it it is allowed. In my case, the private key was only allowed to be used for signatures and was not allowed to be used for encrypting a symmetric key during the SSL/TLS handshake. This meant that my server could only support ECDHE cipher suites.
It also turns out that you can't check the enabled uses of a private key in the Certificate MMC snap-in. Making matters worse, using the sslStream class, there is also no way of determining any information for a handshake failure beyond the generic exception "The client and server cannot communicate, because they do not possess a common algorithm".
The final thing to mention is how I managed to install a server certificate with a restricted private key in the first place. It turns out that I generated it that way. I was using the CertEnroll COM interface to programmatically generate a certificate signing request which I exported, had a certificate authority sign, and installed the certificate authority's response. The C# code that I used to generate the certificate signing request accidentally created a private key that was only enabled for signature use.
From my experience, the CertEnroll interface is difficult to use and it's hard to find working examples online. So for others' reference I am including my C# code that generates a base64 encoded certificate signing request functional for SSL/TLS handshakes. In my case, the line objPrivateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; was missing.
using CERTENROLLLib;
using CERTCLILib;
public string GenerateRequest(string Subject, StoreLocation Location)
{
//code originally came from: http://blogs.msdn.com/b/alejacma/archive/2008/09/05/how-to-create-a-certificate-request-with-certenroll-and-net-c.aspx
//modified version of it is here: http://stackoverflow.com/questions/16755634/issue-generating-a-csr-in-windows-vista-cx509certificaterequestpkcs10
//here is the standard for certificates: http://www.ietf.org/rfc/rfc3280.txt
//the PKCS#10 certificate request (http://msdn.microsoft.com/en-us/library/windows/desktop/aa377505.aspx)
CX509CertificateRequestPkcs10 objPkcs10 = new CX509CertificateRequestPkcs10();
//assymetric private key that can be used for encryption (http://msdn.microsoft.com/en-us/library/windows/desktop/aa378921.aspx)
CX509PrivateKey objPrivateKey = new CX509PrivateKey();
//access to the general information about a cryptographic provider (http://msdn.microsoft.com/en-us/library/windows/desktop/aa375967.aspx)
CCspInformation objCSP = new CCspInformation();
//collection on cryptographic providers available: http://msdn.microsoft.com/en-us/library/windows/desktop/aa375967(v=vs.85).aspx
CCspInformations objCSPs = new CCspInformations();
CX500DistinguishedName objDN = new CX500DistinguishedName();
//top level object that enables installing a certificate response http://msdn.microsoft.com/en-us/library/windows/desktop/aa377809.aspx
CX509Enrollment objEnroll = new CX509Enrollment();
CObjectIds objObjectIds = new CObjectIds();
CObjectId objObjectId = new CObjectId();
CObjectId objObjectId2 = new CObjectId();
CX509ExtensionKeyUsage objExtensionKeyUsage = new CX509ExtensionKeyUsage();
CX509ExtensionEnhancedKeyUsage objX509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage();
string csr_pem = null;
// Initialize the csp object using the desired Cryptograhic Service Provider (CSP)
objCSPs.AddAvailableCsps();
//Provide key container name, key length and key spec to the private key object
objPrivateKey.ProviderName = providerName;
objPrivateKey.Length = KeyLength;
objPrivateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; //Must flag as XCN_AT_KEYEXCHANGE to use this certificate for exchanging symmetric keys (needed for most SSL cipher suites)
objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
if (Location == StoreLocation.LocalMachine)
objPrivateKey.MachineContext = true;
else
objPrivateKey.MachineContext = false; //must set this to true if installing to the local machine certificate store
objPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; //must set this if we want to be able to export it later.
objPrivateKey.CspInformations = objCSPs;
// Create the actual key pair
objPrivateKey.Create();
// Initialize the PKCS#10 certificate request object based on the private key.
// Using the context, indicate that this is a user certificate request and don't
// provide a template name
if (Location == StoreLocation.LocalMachine)
objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, objPrivateKey, "");
else
objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, objPrivateKey, "");
//Set hash to sha256
CObjectId hashobj = new CObjectId();
hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256");
objPkcs10.HashAlgorithm = hashobj;
// Key Usage Extension -- we only need digital signature and key encipherment for TLS:
// NOTE: in openSSL, I didn't used to request any specific extensions. Instead, I let the CA add them
objExtensionKeyUsage.InitializeEncode(
CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE |
CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE
);
objPkcs10.X509Extensions.Add((CX509Extension)objExtensionKeyUsage);
// Enhanced Key Usage Extension
objObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // OID for Server Authentication usage (see this: http://stackoverflow.com/questions/17477279/client-authentication-1-3-6-1-5-5-7-3-2-oid-in-server-certificates)
objObjectId2.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // OID for Client Authentication usage (see this: http://stackoverflow.com/questions/17477279/client-authentication-1-3-6-1-5-5-7-3-2-oid-in-server-certificates)
objObjectIds.Add(objObjectId);
objObjectIds.Add(objObjectId2);
objX509ExtensionEnhancedKeyUsage.InitializeEncode(objObjectIds);
objPkcs10.X509Extensions.Add((CX509Extension)objX509ExtensionEnhancedKeyUsage);
// Encode the name in using the Distinguished Name object
// see here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa379394(v=vs.85).aspx
objDN.Encode(
Subject,
X500NameFlags.XCN_CERT_NAME_STR_SEMICOLON_FLAG
);
// Assign the subject name by using the Distinguished Name object initialized above
objPkcs10.Subject = objDN;
//suppress extra attributes:
objPkcs10.SuppressDefaults = true;
// Create enrollment request
objEnroll.InitializeFromRequest(objPkcs10);
csr_pem = objEnroll.CreateRequest(
EncodingType.XCN_CRYPT_STRING_BASE64
);
csr_pem = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + csr_pem + "-----END CERTIFICATE REQUEST-----";
return csr_pem;
}

Categories