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.
Related
I am using a Java Websocket Server (TooTallNate). A Javascript App is connecting securely via a LetsEncrypt certificate. It is renewed automatically via certbot and is serving an Apache on the same machine too. On all tested browsers everything is working fine, for both https and wss.
I wanted to submit my app as a packaged FireTV app. I tested it in the "Web App Tester" app. As soon as the JS tries to connect to the WSS, it raises an SSL error, which reads in adb-logcat
I/X509util: Failed to validate the certificate chain, error: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
but sometimes just
E/chromium(13208): [ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -202
The relevant Java code filling the SSLContext from TooTallNate is:
private static SSLContext getContext() {
SSLContext context;
String password = "CHANGEIT";
String pathname = "pem";
try {
context = SSLContext.getInstance("TLS");
byte[] certBytes = parseDERFromPEM(getBytes(new File(pathname + File.separator + "cert.pem")),"-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
byte[] keyBytes = parseDERFromPEM(getBytes(new File(pathname + File.separator + "privkey.pem")),"-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");
X509Certificate cert = generateCertificateFromDER(certBytes);
RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes);
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
keystore.setCertificateEntry("cert-alias", cert);
keystore.setKeyEntry("key-alias", key, password.toCharArray(), new Certificate[]{cert});
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, password.toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
}
catch (Exception e) {
context = null;
}
return context;
}
It took some reading to get it to work. There are few information on this special problem, so I decided to answer myself:
It was truly a problem of the missing chain in the SSLContext. Couldn't believe that, because it worked on every other chromium based browser.
In my LetsEncrypt folder I have four files: privkey.pem (not at thing), cert.pem, chain.pem and fullchain.pem, where fullchain.pem is just the concatenation of chain.pem and cert.pem. cert.pem is our own certificate and chain.pem is the Digital Signature Trust DST Root CA X3 certificate which you can see yourself using:
cat chain.pem | openssl x509 -text
I compared the certificates served over https and wss using:
openssl s_client -connect myurl:443 | openssl x509 -text
and
openssl s_client -connect myurl:8080 | openssl x509 -text
The latter showed two error at the beginning of the output
verify error:num=20:unable to get local issuer certificate
while the https response from apache showed
depth=2 O = Digital Signature Trust Co., CN = DST Root CA X3
verify return:1
depth=1 C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
verify return:1
depth=0 CN = myurl
verify return:1
Finally the working solution is a lot easier than my solutions I had meanwhile. Its not necessary to download any further chain certificates. Just load the chain.pem you already have in your LetsEncrypt folder like the cert.pem and add both as the chain to the keystore in the setKeyEntry function:
private static SSLContext getContext() {
SSLContext context;
String password = "CHANGEIT";
String pathname = "pem";
try {
context = SSLContext.getInstance("TLS");
byte[] certBytes = parseDERFromPEM(getBytes(new File(pathname + File.separator + "cert.pem")),"-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
byte[] chainBytes = parseDERFromPEM(getBytes(new File(pathname + File.separator + "chain.pem")),"-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
byte[] keyBytes = parseDERFromPEM(getBytes(new File(pathname + File.separator + "privkey.pem")),"-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");
X509Certificate cert = generateCertificateFromDER(certBytes);
X509Certificate chain = generateCertificateFromDER(chainBytes);
RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes);
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
keystore.setCertificateEntry("cert-alias", cert);
keystore.setKeyEntry("key-alias", key, password.toCharArray(), new Certificate[]{cert, chain});
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, password.toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
}
catch (Exception e) {
context = null;
}
return context;
}
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.
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());
}
I'm trying to deploy a certificate into a windows-my store in order to use it for SSL in IIS6.0.
When the application is running I don't see any errors in SSLDiag output and everything works perfectly, but once I close the application SSLDiag shows an error:
#WARNING: You have a private key that corresponds to this certificate
but CryptAcquireCertificatePrivateKey failed
I checked the machine keyset and noticed that after I close my application it removes the file with a key which was created. Here is the location I checked:
C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys
How can I preserve the create key file in a machine keyset?
Here is the code I'm using:
using(var openFileDialog = new OpenFileDialog())
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var password = "password";
var certificate = new X509Certificate2(openFileDialog.FileName, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
var keystore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
keystore.Open(OpenFlags.MaxAllowed);
keystore.Add(certificate);
keystore.Close();
}
}
I tried different variations of X509KeyStorageFlags, but the file is still removed from machine keyset once I close the app. Why the file is removed and how can I prevent it?
I found the solution:
certificate.PrivateKey.PersistKeyInCsp = true;
This lets the private key to remain in the machine key set.
I suppose the key was removed when the X509Certificate2 object was freeing its resources.