Convert private key to PKCS#8 format in java - private-key

I'm trying to get certificates and private keys from windows certificate store using MSCAPI provider, then i need to store them in a Java Keystore object, but i'm facing a problem of private keys format, the error says:
java.security.KeyStoreException: Cannot get key bytes, not PKCS#8 encoded
Here's my code:
SunMSCAPI providerMSCAPI = new SunMSCAPI();
Security.addProvider(providerMSCAPI);
KeyStore ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null);
PrivateKey privateKey = null;
X509Certificate cert = null;
cert = (X509Certificate) ks.getCertificate("ALIAS");
if (ks.isKeyEntry("ALIAS")) {
privateKey = (PrivateKey) ks.getKey("ALIAS", null);
}
KeyStore newKs = null;
...
...
newKs .setKeyEntry("pvKey", privateKey , "pwd".toCharArray(), certifChain);
Also, the privateKey.getEncoded() returns null.

I have exactly the same issue when programatically importing a pfx file into the windows certificate store and then attempting to read this certificate and key again later. I believe the answer lies in http://www.oracle.com/technetwork/articles/javase/security-137537.html and I quote: "...the resulting PKCS#12 keystore may not be imported into applications that use only a single password for the keystore and all its key entries". Earlier in the document it also states: "Note that keys produced by the SunMSCAPI provider are wrapper objects for the native handles. Thus, they may not be accepted by other providers and may behave somewhat differently than keys produced by pure-Java providers, such as SunJCE. In particular, the RSA private keys generated by the SunMSCAPI provider cannot be serialised". Upon trying to read the private key results in null algorithm and null encoded data as you note above, though reading the certificate works fine. Alternatively you could save the PrivateKey in a separate RSA encrypted file instead of the windows certificate store or just work of the original pfx file instead of importing the pfx into the windows certificate store.

I use command such like:
Runtime.getRuntime().exec("openssl pkcs8 -topk8 -nocrypt -in "+ privateKeyPath + " -out " + pkcs8PrivateKeyPath)

Related

Meaning of "--_mixed 009J33F94539089U_--" in tail of public key

I have a public key as:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-------_mixed 009J33F94539089U_--
I don't understand what "--mixed 009J33F94539089U--" in the end is, and what it's purpose is.
This key is supposed to be used for creation of encrypted JWT, which is to be sent as payload to hit an API. I used this website to create encrypted JWT, but API hit fails when I use this generated encrypted JWT. But I had to remove this "--mixed 009J33F94539089U--" from my key while entering in the aforementioned website for the creation of encrypted JWT to be successful.
I am wondering if generating encrypted JWT without using this "--mixed 009J33F94539089U--" and using it as payload is causing the API hit to fail. What do I do about this?
[NOTE : The key I mentioned above isn't my actual key.]

How should I sign a CSR using a signature created in HSM, in C# .NET Core?

I'm exhausted after looking for an answer for 3 days. I don't know if my suggested flow is wrong or my Google skills have really deteriorated.
My API needs to create a valid certificate from a CSR it received, by signing it with a private key that exists ONLY inside an HSM-like service (Azure KeyVault), which unfortunately doesn't offer Certificate Authority functions BUT does offer signing data with a key that exists there. My CA certificate's private key is stored in the HSM. I'm using ECDSA.
My suggested flow:
Client generates Key Pair + CSR and sends CSR to API
API creates a certificate from the CSR
API asks HSM to sign the CSR data and receives back a signature
API appends the signature to the certificate and returns a signed (and including CA in chain) certificate to the Client
I'm using C# .NET Core and would like to keep it cross-platform (as it runs in Linux containers), so I have to keep it as native as possible or using Bouncy Castle (which I'm still not sure if runs in Linux .NET Core).
I really appreciate your help!
I had faced a similar issue and found a solution. You'll have to use the PKCS11Interop.X509Store library.
The solution uses dotnet core native System.Security.Cryptography.X509Certificates.CertificateRequest::Create method
for generating a certificate.
As per the docs:
Pkcs11Interop is managed library written in C# that brings the
full power of PKCS#11 API to the .NET environment
Pkcs11Interop.X509Store is managed library built on top of
Pkcs11Interop. It's main goal is to provide easy to use PKCS#11 based
read-only X.509 certificate store that can be easily integrated with
standard .NET ecosystem.
Till v0.3.0, implementation for issuing a certificate (i.e signing a CSR) is not available.
With minor modifications in the PKCS11Interop library, I was able to sign the CSR.
Mentioned in Issue #30, the code is now added in the PKCS11Interop.X509Store library version 0.4.0.
The below code is taken from test cases for BasicEcdsaCertificateRequestTest. Test cases for RSA CertificateRequest are also there.
// Load PKCS#11 based store
using (var pkcs11Store = new Pkcs11X509Store(SoftHsm2Manager.LibraryPath, SoftHsm2Manager.PinProvider))
{
// Find signing certificate (CA certificate)
Pkcs11X509Certificate pkcs11CertOfCertificateAuthority = Helpers.GetCertificate(pkcs11Store, SoftHsm2Manager.Token1Label, SoftHsm2Manager.Token1TestUserEcdsaLabel);
// Generate new key pair for end entity
ECDsa ecKeyPairOfEndEntity = ECDsa.Create(ECCurve.NamedCurves.nistP256);
// Define certificate request
CertificateRequest certificateRequest = new CertificateRequest(
new X500DistinguishedName("C=SK,L=Bratislava,CN=BasicEcdsaCertificateRequestTest"),
ecKeyPairOfEndEntity,
HashAlgorithmName.SHA256);
// Define certificate extensions
certificateRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
certificateRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(certificateRequest.PublicKey, false));
certificateRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false));
// Issue X.509 certificate for end entity
X509Certificate2 certificateOfEndEntity = certificateRequest.Create(
pkcs11CertOfCertificateAuthority.Info.ParsedCertificate.SubjectName,
X509SignatureGenerator.CreateForECDsa(pkcs11CertOfCertificateAuthority.GetECDsaPrivateKey()),
DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow.AddDays(365),
new BigInteger(1).ToByteArray());
// Verify signature on X.509 certificate for end entity
Assert.IsTrue(CaCertSignedEndEntityCert(pkcs11CertOfCertificateAuthority.Info.ParsedCertificate.RawData, certificateOfEndEntity.RawData));
// Asociate end entity certificate with its private key
certificateOfEndEntity = certificateOfEndEntity.CopyWithPrivateKey(ecKeyPairOfEndEntity);
// Export end entity certificate to PKCS#12 file
string basePath = Helpers.GetBasePath();
string pkcs12FilePath = Path.Combine(basePath, "BasicEcdsaCertificateRequestTest.p12");
File.WriteAllBytes(pkcs12FilePath, certificateOfEndEntity.Export(X509ContentType.Pkcs12, "password"));
}
Hope this helps.

How to generate a certificate with DH parameters

I need to support Diffie Hellman encryption, now in order to test this i need to create a certificate with DH key parameters eg. key-length - 2048 etc.
Now as i understand DH doesn't work with self-signed certificates, so basically i need to create a certificate issued by some trusted third party containing DH key parameters.
I searched a lot but can't seem to find proper direction, no where can i find a way to create a cert with DH parameters.
Can someone point me in right direction?? Thanks in advance!!
I need to support Diffie Hellman encryption
DH is key exchange (or key agreement) protocol, not encryption. DH is used to securely generate a common key between two parties, other algorithms are used for encryption itself.
I need to create a certificate with DH key parameters eg. key-length - 2048 etc
There is nothing like DH parameters in a certificate.
DH is only one of ways how a public key can be used. You may generate a DH public key with specified length (e.g. 2048 bit) and execute the DH exchange, but it has nothing to do with certificate parameters. (didn't you mean to generate a keypair, not a certificate?).
Indeed the DH key exchange needs other parameters (p, g), but the parameters are part of the protocol, not the certificate. In TLS even the DH parameters can be random and authenticated by the certificate's public key - it is called Ephemeral Diffie-Hellman key exchange.
You could generate DH parameters (p, g) separately:
openssl dhparam -out dhparams.pem 4096
Can someone point me in right direction??
Now I assume you want to establish an encrypted channel (TLS) using DH. The easiest way would be to specify allowed parameters for SSL for the library. This is an example httpd configuration, where you can enforce DH key exchange. Every reasonable SSL framework or server has option to set the parameters.
If you want to do the DH key exchange yourself (not as part of TLS), I'd advice to use an out-of-box mature library for your programming language.
Yes, it seems true that OpenSSL will not create a certificate for DH keys. You'll get an error like: operation not supported for this keytype. The reason someone would want to do this is that they want to store the DH public key in a keystore; which seems like a reasonable place to store them. In my case, I want my client application to be deployed with the server's public DH key. The problem is that keystores don't let you store public keys in them. They do however, let you store certificates in them. Hence the need for creating a certificate that contains a DH public key. Since you can't do this using OpenSSL, you'll have to do it in code. Here's the code that I use to create a certificate. If you pass in a DH public key, you'll be able to add this certificate to a keystore:
public X509Certificate createCert (PublicKey publicKey, PrivateKey caKey, X509Certificate caCert , String subject) throws Exception {
Date now = new Date();
Date exp = new Date(now.getTime()+2555*86400*1000); // 2555 days validity
BigInteger.valueOf(now.getTime());
ContentSigner signer = new JcaContentSignerBuilder("SHA256with"+caKey.getAlgorithm()).build(caKey);
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
byte[] enc = new X509v3CertificateBuilder(
/*issuer*/ new X500Name(caCert.getIssuerX500Principal().getName()),
/*serial*/BigInteger.valueOf(now.getTime()),
/*validity*/now, exp,
/*subject*/new X500Name (subject),
/*spki*/subPubKeyInfo).build(signer).getEncoded();
X509Certificate cert = (X509Certificate)CertificateFactory.getInstance ("X.509") .generateCertificate(new ByteArrayInputStream(enc));
return cert;
}
The code uses several BouncyCastle classes. Besides passing in the DH public key, you have to pass in the CA private key and the CA certificate and a String that contains the subject for the certificate that you generate. Hope that helps for those wanting to store a DH public key in a keystore.

Apple Pay - How to compare merchant public key with publicKeyHash from payment token?

I'm working on Apple Pay payment token decryption.
According to this instruction Payment Token Format Reference on step 2. I need use publicKeyHash field from header of payment token to determine which
merchant certificate was used by Apple.
pulbicKeyHash is SHA–256 hash of the X.509 encoded public key bytes of the merchant’s certificate, Base64 encoded as a string.
I have one merchant certificate. So I assume that if i will take sha-256 hash of my certificate's public key and Base64 encode it i will get the same value that i receive in publicKeyHash field of payment token.
But I can't figure out what particular part of the certificate should I hash.
The initial merchant certificate provided by Apple is in .cer format.
I'have extracted public key from it to .pem format. Than i have tried both take hash -> base64encode of public key (String between -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----) and
to take hash of base64 decoded .pem which i think should be .der and base 64 encode it.
And both failed to match value received from Apple Pay. Also it have different length my base64 encoded hash have 88 char length, and publicKeyHash field is 44 char in length.
When I have tried to base 64 decode publicKeyHash, I've got unreadeble characters like "D��$�f���#c���$����WP��"
But according to Apple documentation there should be sha-256 hash which can not contain such symbols.
Can somebody explain me what concrete steps should I perform in order to complete this merchant certificate check?
In my case the main problem and solution was to use Payment Processing Certificate's public key hash and NOT Merchant Identity Certificate's public key hash, witch I was trying to compare with PublicKeyHash from payment token.
In my excuse I can say that following text from Apple Documentation is pretty much ambiguous:
publicKeyHash SHA–256 hash, Base64 encoded as a string Hash of the
X.509 encoded public key bytes of the merchant’s certificate.
As we have two kind of certificates merchant and payment processing. It was obvious for me that merchant certificate from documentation is merchant id certificate.
Only after re-read Payment Processing certificate description
Payment Processing Certificate. A certificate used to securely
transfer payment data. Apple Pay servers use the payment processing
certificate’s public key to encrypt the payment data. Use the private
key to decrypt the data when processing payments.
from Apple Pay JS documentation I have realized my mistake.
So I hope my experience can help somebody not to step on the same rake)
Its shame I was not able to find openssl command to extract hash directly from the cert. So you have to create the public key first in order to get the public key hash. There are two ways to extract the public key.
Step 1
A. From your ecc private key (payment processing private key)
openssl ec -in ecc_private_key.key -pubout -out ec_public_key.pem
OR
B. From the cert downloaded from apple pay portal (after uploading payment processing csr)
openssl x509 -inform der -in apple_pay.cer -pubkey -noout > apple_pay_public_key.pem
Both will give you public key in following format
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAENGbyXUzeZTdeyyNuXyc0nMzXmnLl
xMwd/t/sCZr3RPhytPbZpR/V4/xHqN/MVzozzq30I0/eUefbThEBl236Og==
-----END PUBLIC KEY-----
Step 2
You can use following code to extract the base64 hash from above public key remember to remove headers/footers and line feeds.
I hoped I could have figured out how to use openssl tool to get hash from public key but anyway following c# code works for me. its very simple and easy to port to java/python/php or whatever your preference is. Or just use following code online at ideone.com
String publicKeyBase64 = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAENGbyXUzeZTdeyyNuXyc0nMzXmnLlxMwd/t/sCZr3RPhytPbZpR/V4/xHqN/MVzozzq30I0/eUefbThEBl236Og==";
byte[] publicKey = Convert.FromBase64String(publicKeyBase64);
SHA256 sha256 = SHA256Managed.Create();
byte[] hash = sha256.ComputeHash(publicKey);
String publicKeyHash = Convert.ToBase64String(hash);
Console.WriteLine("Result: {0}", publicKeyHash);
Please keep in mind that your system should be able to accept multiple keys at any given time and instead of just verifying you need to load the correct private key based on publicKeyHash you receive from device(iphone/ipad etc) considering the scenario when your current certificate is expiring (or you are revoking for any reason) otherwise your system may not be able to accept the transaction for a short period of time. As per one of my encounter it took apple more than one hour, before new payment processing keys became active, after pressing activate in the portal.
This question and the accepted answer were still a bit vague on details, so here is exact tested method in java to check that token.paymentData.header.publicKeyHash matches Apple Pay Payment Processing Certificate:
private static void checkPublicKeyHash(String publicKeyHash, X509Certificate paymentProcessingCertificate)
throws NoSuchAlgorithmException, CertificateException {
String certHash = Base64.getEncoder().encodeToString(
MessageDigest.getInstance("SHA-256").digest(
paymentProcessingCertificate.getPublicKey().getEncoded()));
if (!Objects.equals(publicKeyHash, certHash)) {
throw new DigestException(String.format(
"publicKeyHash %s doesn't match Payment Processing Certificate hash %s",
publicKeyHash, certHash));
}
}
First it seem the answers to the original question are several months apart. Second all answers seem to lack one critical bit of information; the only reason for step 2 of the the Payment Token Format Reference is that you can have more than one Payment Processing Certificate in use. If you do then apple may use anyone to encrypt the data.
If you have just one Payment Processing Certificate then you can skip this step and just use the its private key. After all, the end result of step two is to get the private key of the payment processing certificate that was used to encrypt the payment data.

split a PKCS12 into its certificate and private key bytes

I have been able to OpenSSL tools to extract the certificate and private key bytes from an existing PFX (PKCS12) file.
However, I wish to do this using .NET. I am able to use the X509Certificate classes to load a PFX file and extract the certificate bytes but, I do not know how to extract the private key. The certificate (exported as a PFX file) was created using a sha1RSA aignature algorithm.
I know RSA classes exist in .NET but I do not know how to use them together.
Any advice will help.
Thanks in advance.
Subbu
See my answer here: extract private key bytes in C#
Does this work for you?

Resources