I have an issue with generation pfx file with full certificate chain which is correctly read as X509Certificate2 object in .net core for authentication. I tried various approaches but with no luck.
I have a chain generated by OpenSSL and I use last certificate and private key to generate user certificates for authentication.
Finally, I have PEM files with certs (each cert from a chain in a separate file)
-----BEGIN CERTIFICATE-----
MIIFR[....]Aerk=
-----END CERTIFICATE-----
etc.
In webapi controller I have
X509Certificate2 clientCertificate =
this.Request.HttpContext.Connection.ClientCertificate;
X509Chain x509Chain = new X509Chain(){ ChainPolicy = new
X509ChainPolicy({...}};
x509Chain.Build(clientCertificate))
var elements = x509Chain.ChainElements.Cast<X509ChainElement>()
// in elements variable I expect to have more than one item but I don't have
How can I generate pfx in Bouncy Castle in the correct way to achieve it?
Below some code snippet for pfx file creation which generates pfx but is read as X509Certificate2 with only one chain element. How to modify it to have all of them available?
Pkcs12Store store = new Pkcs12Store();
X509CertificateEntry[] chain = new X509CertificateEntry[5];
X509Certificate cert1 = certParser.ReadCertificate(new
MemoryStream(Encoding.UTF8.GetBytes(certString1)));
X509CertificateEntry certificateEntry1 = new X509CertificateEntry(cert1);
chain[0] = certificateEntry1;
// I adds all certs in order from user cert to root one (self signed)
store.SetKeyEntry(csr.GetCertificationRequestInfo().Subject.ToString(), new
AsymmetricKeyEntry(key.Private), chain);
using (var filestream = new FileStream("./full.cert.pfx"), FileMode.Create,
FileAccess.ReadWrite)){
store.Save(filestream, "".ToCharArray(), new SecureRandom());
}
Related
I am using bouncecastle library to generate certificae using My CA.
I dont know how to verify certificate that was signed by My CA
I found this answer but its using java.security.cert
X509Certificate certificate =...
X509Certificate intermediate = ...
try{
certificate.verify(intermediate.getPublicKey());
//Verification ok. intermediate is the issuer
} catch (Exception e){}
}
How can I do this using bouncecastle library?
My Question:
From a Certificate Signing Request as below:
Example:
-----BEGIN CERTIFICATE REQUEST-----
MIIClDCCAXwCAQAwTzELMAkGA1UEBhMCVk4xEDAOBgNVBAMMB2RldmljZTMxCjAI ...
-----BEGIN CERTIFICATE REQUEST-----
I am using system.security.cryptography.x509certificates, I would load it as a CertificateRequest/X509Certificate2 object to create new certificate from Certificate Signing Request.
Anyone who know how to do?
My Try
Input:
self signed certificate as a CA
certificate signing request
My code
string rootCA = ""; // root certificate
string scrString = ""; // certificate signing request
byte[] rootRawData = Convert.FromBase64String(rootCA);
X509Certificate2 rootCert = new X509Certificate2(rootRawData);
var generator = X509SignatureGenerator.CreateForRSA(rootCert.GetRSAPrivateKey(), RSASignaturePadding.Pkcs1);
byte[] scrRawData = Convert.FromBase64String(scrString);
X509Certificate2 scrDeviceCert = new X509Certificate2(scrRawData); ------> ERROR: : 'Cannot find the requested object.'
CertificateRequest scrDeviceReq = new CertificateRequest(scrDeviceCert.IssuerName, scrDeviceCert.PublicKey, HashAlgorithmName.SHA256);
var deviceCert = scrDeviceReq.Create(rootCert.IssuerName, generator, DateTimeOffset.UtcNow.AddDays(1), DateTimeOffset.UtcNow.AddDays(6), new byte[] { 1, 2, 3, 4 });
There is no built-in functionality to read CSRs in .NET Core. You have to use 3rd party libraries to decode CSRs.
Extra information at the end after comments from Crypt32 (thank you Crypt32!)
I have to send data to a server. I need mutual authentication: the server needs to be certain it is me, and I need to be certain that the server really is the server that I trust. This needs to be dons in a windows program.
To identify itself, the server will send me a certificate that is issued by certificate authorities that I trust: a root certificate and an intermediate certificate:
Root CA-G2.PEM
Intermediate CA-G2.PEM
To identify me, the organization gave me a certificate and a private key
Root CA-G3.PEM
Intermediate CA-G3.PEM
MyCertificate.CRT (= pem) and MyCertificate.Private.Key (=RSA)
I have imported all root certificates and intermediate certificates into the windows keystore.
To sent the message:
const string url = "https://...//Deliver";
HttpWebRequest webRequest = WebRequest.CreateHttp(url);
// Security:
webRequest.AuthenticationLevel=AuthenticationLevel.MutualAuthRequired;
webRequest.Credentials = CredentialCache.DefaultCredentials;
// Should I add my certificate?
X509Certificate myCertificate = new X509Certificate("MyCertificate.CRT");
// Should I add Certificate authorities?
// only the CA-G2 authorities, so my WebRequest can trust the certificate
// that will be sent by the Server?
// or Should I also add the CA-G3 who issued MyCertificate
// and what about MyCertificate.Private.Key, the RSA file?
// Fill the rest of the WebRequest:
webRequest.Method = "Post";
webRequest.Accept = "text/xml";
webRequest.Headers.Add("SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
... etc
// do the call and display the result
using (WebResponse response = webRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string soapResult = reader.ReadToEnd();
Console.WriteLine(soapResult);
}
}
The WebResponse doesn't indicate any error. The returned data is an empty (non-null) string. Yet:
response.StatusCode == NoContent (204)
soapResult == String.Empty
response.IsMutuallyAuthenticated == false
The NoContent and the empty data result are expected. Does the false IsMutuallyAuthenticated indicate that something is wrong with my authentication?
Added information
Crypt32 suggested I should convert MyCertificate.CRT and MyCertificate.Private.Key into one PFX (or P12) file.
For this I use openssl.
I concatenated the CA-G3 files into one TrustG3.Pem and created the P12 file:
openssl.exe pkcs12 -export -name "<some friendly name>"
-certfile TrustG3.Pem
-in MyCertificate.CRT
-inkey MyCertificate.Private.Key
-out MyCertificate.P12
After providing a password a proper Pkcs12 file (PFX) was created. The source code changes slightly:
HttpWebRequest webRequest = WebRequest.CreateHttp(url);
// Security:
webRequest.AuthenticationLevel=AuthenticationLevel.MutualAuthRequired;
webRequest.Credentials = CredentialCache.DefaultCredentials;
var p12Certificate = new X509Certificate("MyCertificate.P12", "my password");
webRequest.ClientCertificates.Add(p12Certificate);
Alas, this didn't help. The webResponse still says:
response.IsMutuallyAuthenticated == false
Does the false IsMutuallyAuthenticated indicate that something is wrong with my authentication?
yes, it does. Because you add only public part of client certificate. There is no associated private key specified. Either, use certificate from certificate store (assuming, cert store contains private key) or import certificate from PFX.
Update:
now your client authentication code looks correct. Next step is to check if your client certificate is trusted by server.
When I try to upload the certificate to https://identity.apple.com/pushcert/, it tells me the signature is invalid.
I followed step-by-step the Mobile Device Manager documentation and http://www.softhinker.com/in-the-news/iosmdmvendorcsrsigning. I am using C#.NET
The format of the plist_encoded file is correct.
//Load signing certificate from MDM_pfx.pfx, this is generated using signingCertificatePrivate.pem and SigningCert.pem.pem using openssl
var cert = new X509Certificate2(MY_MDM_PFX, PASSWORD, X509KeyStorageFlags.Exportable);
//RSA provider to generate SHA1WithRSA
//Signed private key - PushCertSignature
var crypt = (RSACryptoServiceProvider)cert.PrivateKey;
var sha1 = new SHA1CryptoServiceProvider();
byte[] data = Convert.FromBase64String(csr);
byte[] hash = sha1.ComputeHash(data);
//Sign the hash
byte[] signedHash = crypt.SignHash(hash, CryptoConfig.MapNameToOID("sha1RSA"));
hashedSignature = Convert.ToBase64String(signedHash);
//Read Certificate Chain
String mdm = signCSR.readCertificate(mdmCertificate);
String intermediate = signCSR.readCertificate(intermediateCertificate);
String root = signCSR.readCertificate(rootCertificate);
StringBuilder sb = new StringBuilder(); ;
sb.Append(mdm);
sb.Append(intermediate);
sb.Append(root);
signCSR.PushCertWebRequest(csr, sb.ToString(), hashedSignature);
I am not sure what to place in MDM_pfx.pfx. What I did was that I generated the cst to upload to the enterprise iOS Provisioning portal and I download the certificate generate one.
Then I exported the private key of the CSR I generated and exported it as a .pfx file.
This is the file I used.
was this the correct way?
What you have to upload to https://identity.apple.com/pushcert/ isn't just the certificate, it's a plist (XML) with the certificate chain. A sample Java app is available (http://www.softhinker.com/in-the-news/iosmdmvendorcsrsigning) which you should be able to use for reference.
I solved this problem by using: C:\Program Files (x86)\GnuWin32\bin>openssl pkcs12 -export -out mdmapnspfx.pfx -
inkey mdmpk.pem -in mdm.pem
The key was incorrect, i was not using mdm.pem certificate by it was self-signed.
I'm getting a "The remote certificate is invalid according to the validation procedure" exception message with the following code:
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(MyCertValidationCb);
var request = (FtpWebRequest)WebRequest.Create(new Uri(myUri));
request.EnableSsl = true;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.BeginGetRequestStream(EndGetStreamCallback, _state);
public static bool MyCertValidationCb(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors)
== SslPolicyErrors.RemoteCertificateChainErrors)
{
return false;
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch)
== SslPolicyErrors.RemoteCertificateNameMismatch)
{
Zone z;
z = Zone.CreateFromUrl(((FtpWebRequest)sender).RequestUri.ToString());
if (z.SecurityZone == SecurityZone.Intranet
|| z.SecurityZone == SecurityZone.MyComputer)
{
return true;
}
return false;
}
return false;
}
The ftp server is filezilla. FTP over SSL is enabled, and Allow explicit FTP over TLS is also enabled. I've generated a certificate.crt file. Connected to the ftp location using filezilla client, and checked "Always trust this certificate" in the popup window.
In the MyCertValidationCb method, (sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == SslPolicyErrors.RemoteCertificateChainErrors is always true.
If I change MyCertValidationCb to always return true, the ftp request goes through without a problem. I'm sure it's an issue with certificates. Anyone have any ideas?
The RemoteCertificateChainErrors was a result of not having the certificate in the Trusted Root Certification Authorities certificate store.
Filezilla generates a self signed certificate with the following format:
-----BEGIN RSA PRIVATE KEY-----
//hash
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
//hash
-----END CERTIFICATE-----
In order to import the certificate, remove the private key section and save the new file. Install that into the Trusted Root Certification Authorities certificate store.
Now the issue I'm having is RemoteCertificateNameMismatch, I'll post that in another topic.