Providing Key Usage to X509Certificate generated with Java BouncyCastle - java

Here is my piece of code to for generating X509Certificate with BouncyCastle API
private static X509Certificate createCertificate(String dn, String issuer,
PublicKey publicKey, PrivateKey privateKey) throws Exception {
X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
certGenerator.setSerialNumber(BigInteger.valueOf(Math.abs(new Random()
.nextLong())));
certGenerator.setIssuerDN(new X509Name(dn));
certGenerator.setSubjectDN(new X509Name(dn));
certGenerator.setIssuerDN(new X509Name(issuer)); // Set issuer!
certGenerator.setNotBefore(Calendar.getInstance().getTime());
certGenerator.setNotAfter(Calendar.getInstance().getTime());
certGenerator.setPublicKey(publicKey);
certGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption");
**certGenerator..... ??? what for key usage ?**
X509Certificate certificate = (X509Certificate) certGenerator.generate(
privateKey, "BC");
return certificate;
}
Full code you can see here
My question is there is no way to set the key usage for the generated Digital Certificate.
I am trying to set the usage as Encryption.. There is no such method/way in X509V3CertificateGenerator class.
How to go about it.
Thanks for any hints.

Related

How to sign a .jar file using XMSS (PQC) Signature Scheme with JarSigner

I am trying to use JarSigner to sign .jar files with XMSS Signatures.
With the use of the JCA/JCE Post-Quantum Cryptography Provider from BouncyCastle it is possible to generate XMSS and XMSSMT KeyPairs programmatically (example).
In order to use JarSigner it is, as far as I know, crucial to provide a KeyStore and the alias of the entry one wants to sign its code with: jarsigner -keystore myKeystore -storetype JKS -storepass password -keypass password myjarfile.jar keystoreEntryAlias The KeyStore entry contains the Public/Secret KeyPair and the assosiated X.509 Certificate.
The 'normal' way of signing a Jar file with the JarSigner is as follows:
Use keytool to generate the Public/Secret KeyPair and a Certificate then store them in a KeyStore (keytool -genkeypair -alias keystoreEntryAlias -keyalg RSA -sigalg SHA256withRSA -dname CN=MyCompanyName -storetype JKS -keypass password -keystore mykeystore.jks -storepass password)
Use JarSigner to sign the .jar using the SecretKey stored in mykeystore.jks with the alias keysotreEntryAlias (jarsigner -keystore mykeystore.jks -storetype jks -storepass passeword -keypass password myjarfile.jar keystoreEntryAlias)
In order to Sign my file with an XMSS Key I have theoretically two possibilities:
Use BCPQC to create XMSS KeyPairs programmatically, store them in mykeystore and use jarsigner -keystore mykeystore -alias xmss via CLI to sign my file.
Use BCPQC-Provider with the keytool in order to directly via CLI generate XMSS KeyPairs and store them in mykeystore (keytool would here need 2 more arguments: -providerclass org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider and -providerpath C:\Path\to\BouncyCastle\provider\bcprov-jdk15on-160.jar) Then sign the file with the keystore entry using JarSigner
Sadly I run into problems with both possibilities:
As I have not found a way yet to use JarSigner without CLI I need to put my generated XMSS KeyPairs in a KeyStore, but therefor I need the Certificate which includes the Public XMSS Key. BouncyCastle does provide a X.509CertificateBuilder which can be used to generate the needed Certificate, however something seems to go wrong if you take a look at the generated Certificate, especially at Signature Algorithm and Public Key(Source code at bottom [CertificateBuilderExample], using XMSSMT)
It appears keytool only uses the init(int) overload from BCPQCProvider and XMSSKeyPairGeneratorSpi rejects that; it wants AlgorithmParameterSpec specifically XMSSParameterSpec, or no init at all -- and if I try the latter, it does generates a keypair, but the resulting keys can't be encoded and thus can't be stored in KeyStore.
My Question would now be:
Does anyone know of a way to sign .jar Files using XMSS / XMSSMT with JarSigner and can provide a more or less detailed explanation on what he/her did right that I did wrong?
Or if I was wrong about anything I mentioned above provide a correction and point out a way to do so ?
UPDATE 1: I am now able, with the use of another X509CertificateGenerator (Source code at bottom [X509CertificateGenerator]) and intel gathered from here, here and here, to successfully sign jar files programmatically with RSA provided from BouncyCastle (Source code for signing at bottom [RSA_JarSigner]).
If I try to apply the same scheme used to sign with RSA to sign with XMSS or XMSSMT I run into a JarSignerException: Error in signer materialscaused by NoSuchAlgorithmException: unrecognized algorithm name: XMSS (Source code for XMSS/XMSSMT at bottom [SignXMSS] [SignXMSSMT].
Hopefully someone can help me figure out where the problem is!
UPDATE 2: It seems the problem with the generated XMSS (or XMSSMT) certificates is due to the fact that the entry for the Signature Algorithm (which is SHA256withXMSS) is passed as an ASN1ObjectIdentifier which is unknown to the system yet. Thus I did some research to see if BouncyCastle does not by accident have an XMSS Certificate Generator laying around somewhere.. Bingo, here is one!
I shortened the code a bit and came up with 1 generator and 1 verifier (Source code at bottom [XMSSGen] [XMSSVer].
The generator tho gives me the same Certificates I already got with the other methods (such as [X509CertificateGenerator]).
The verifier sadly prompts me this ugly error: Exception in thread "main" java.security.spec.InvalidKeySpecException: java.lang.ClassCastException: org.bouncycastle.asn1.DLSequence cannot be cast to org.bouncycastle.asn1.ASN1Integer at org.bouncycastle.pqc.jcajce.provider.xmss.XMSSKeyFactorySpi.engineGeneratePrivate(Unknown Source) at java.base/java.security.KeyFactory.generatePrivate(KeyFactory.java:384) at BCXMSSCertificateVerifyer.verifyCertificate(BCXMSSCertificateVerifyer.java:32) at BCXMSSCertificateTester.main(BCXMSSCertificateTester.java:23)
Maybe someone has an idea where it comes from / how to fix it. In order to see if BC it self can work with its own created XMSS Certificates.
Edit: One problem with the verifier: PrivateKey privKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); why would we need a private Key to verify the Certificate ? Makes no sense - just remove it and it works ^^ (or at least should)
UPDATE 3: I finally managed to get the the verifier to work properly, so I am currently able to produce and verify XMSS Certificates. I am also able to store XMSS KeyPairs with a Certificate containing the PublicKey in a KeyStore. Though I am still not able to sign any .jar file with.
Now comes something a bit strange: I am able to sign things with the BC XMSS KeyPairs (of course I am, thats what they got made for) tho if I save them (or at least the PrivateKey, as he is required to sign stuff) and reload it afterwards to sign stuff again with it, it does not work. Neither if I store them in a KeyStore and retrieve them nor if I save the Key as encoded Bytes to a file and load them again. (If your interested in the code, just comment and I'll post it here)
My suggestion is: as the XMSS Signature Scheme requires a state (the state of the OTS already used) to be saved, that this state somehow cannot be retrieved from the PrivateKey as it is loaded again (whether from KeyStore or file doesnt matter) and thus cannot be used to sign something with.
[CertificateBuilderExample]
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
import org.bouncycastle.pqc.jcajce.spec.XMSSMTParameterSpec;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
public class App {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastlePQCProvider());
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String datefrom = "12-08-2018 10:20:56";
String dateuntil = "12-05-2020 10:20:56";
Date from = sdf.parse(datefrom);
Date until = sdf.parse(dateuntil);
// Create self signed Root CA certificate
KeyPair rootCAKeyPair = generateKeyPair();
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
new X500Name("CN=rootCA"), // issuer authority
BigInteger.valueOf(new Random().nextInt()), //serial number of certificate
from, // start of validity
until, //end of certificate validity
new X500Name("CN=rootCA"), // subject name of certificate
rootCAKeyPair.getPublic()); // public key of certificate
// key usage restrictions
builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
X509Certificate rootCA = new JcaX509CertificateConverter().getCertificate(builder
.build(new JcaContentSignerBuilder("SHA256withXMSSMT").setProvider("BCPQC").
build(rootCAKeyPair.getPrivate()))); // private key of signing authority , here it is self signed
saveToFile(rootCA, "rootCA.cer");
}
private static KeyPair generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("XMSSMT", "BCPQC");
kpGen.initialize(new XMSSMTParameterSpec(20, 10, XMSSMTParameterSpec.SHA256), new SecureRandom());
KeyPair kp = kpGen.generateKeyPair();
System.out.print("Public key:" + Arrays.toString(kp.getPublic().getEncoded()));
return kp;
}
private static void saveToFile(X509Certificate certificate, String filePath) throws IOException, CertificateEncodingException {
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
fileOutputStream.write(certificate.getEncoded());
fileOutputStream.flush();
fileOutputStream.close();
}
}
[X509CertificateGenerator]
public X509Certificate generateCertificate(String dn, KeyPair keyPair, int validity, String sigAlgName) throws GeneralSecurityException, IOException {
PrivateKey privateKey = keyPair.getPrivate();
X509CertInfo info = new X509CertInfo();
Date from = new Date();
Date to = new Date(from.getTime() + validity * 1000L * 24L * 60L * 60L);
CertificateValidity interval = new CertificateValidity(from, to);
BigInteger serialNumber = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name(dn);
AlgorithmId sigAlgId = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(serialNumber));
info.set(X509CertInfo.SUBJECT, owner);
info.set(X509CertInfo.ISSUER, owner);
info.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(sigAlgId));
// Sign the cert to identify the algorithm that's used.
X509CertImpl certificate = new X509CertImpl(info);
certificate.sign(privateKey, sigAlgName);
// Update the algorith, and resign.
sigAlgId = (AlgorithmId) certificate.get(X509CertImpl.SIG_ALG);
info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, sigAlgId);
certificate = new X509CertImpl(info);
certificate.sign(privateKey, sigAlgName);
return certificate;
}
[RSA_JarSigner]
public class JarSignerTest {
public static void main(String[] args) throws Exception{
JarSignerTest jst = new JarSignerTest();
jst.SignRSA();
}
public void SignRSA() throws Exception{
Security.addProvider(new BouncyCastleProvider());
File inputFile = new File("C:\\Path\\to\\jar\\toSign\\jarfile.jar"),
outputfile = new File("C:\\Path\\to\\signedJar\\jarfile.jar");
X509CertificateGen x509certgen = new X509CertificateGen();
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
kpGen.initialize(1024, new SecureRandom());
KeyPair keyPair = kpGen.generateKeyPair();
Certificate[] chain = {x509certgen.generateCertificate("cn=Unknown", keyPair, 356, "SHA256withRSA")};
List<? extends Certificate> foo = Arrays.asList(chain);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
CertPath certPath = certificateFactory.generateCertPath(foo);
JarSigner signer = new JarSigner.Builder(keyPair.getPrivate(), certPath)
.digestAlgorithm("SHA-256")
.signatureAlgorithm("SHA256withRSA")
.build();
try (ZipFile in = new ZipFile(inputFile);
FileOutputStream out = new FileOutputStream(outputfile)){
signer.sign(in, out);
}
}
}
[SignXMSS]
public void SignXMSS() throws Exception{
Security.addProvider(new BouncyCastlePQCProvider());
File inputFile = new File("C:\\Path\\to\\jar\\toSign\\jarfile.jar"),
outputfile = new File("C:\\Path\\to\\signedJar\\jarfile.jar");
X509CertificateGen x509certgen = new X509CertificateGen();
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("XMSS", "BCPQC");
kpGen.initialize(new XMSSParameterSpec(10, XMSSParameterSpec.SHA256), new SecureRandom());
KeyPair keyPair = kpGen.generateKeyPair();
Certificate[] chain = {x509certgen.generateCertificate("cn=Unknown", keyPair, 356, "SHA256withXMSS")};
List<? extends Certificate> foo = Arrays.asList(chain);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
CertPath certPath = certificateFactory.generateCertPath(foo);
JarSigner signer = new JarSigner.Builder(keyPair.getPrivate(), certPath)
.digestAlgorithm("SHA-256")
.signatureAlgorithm("SHA256withXMSS", new BouncyCastlePQCProvider())
.build();
try (ZipFile in = new ZipFile(inputFile);
FileOutputStream out = new FileOutputStream(outputfile)){
signer.sign(in, out);
}
}
[SignXMSSMT]
public void SignXMSSMT() throws Exception{
Security.addProvider(new BouncyCastlePQCProvider());
File inputFile = new File("C:\\Path\\to\\jar\\toSign\\jarfile.jar"),
outputfile = new File("C:\\Path\\to\\signedJar\\jarfile.jar");
X509CertificateGen x509certgen = new X509CertificateGen();
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("XMSSMT", "BCPQC");
kpGen.initialize(new XMSSMTParameterSpec(20, 10, XMSSMTParameterSpec.SHA256), new SecureRandom());
KeyPair keyPair = kpGen.generateKeyPair();
Certificate[] chain = {x509certgen.generateCertificate("cn=Unknown", keyPair, 356, "SHA256withXMSSMT")};
List<? extends Certificate> foo = Arrays.asList(chain);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
CertPath certPath = certificateFactory.generateCertPath(foo);
JarSigner signer = new JarSigner.Builder(keyPair.getPrivate(), certPath)
.digestAlgorithm("SHA-256")
.signatureAlgorithm("SHA256withXMSSMT")
.build();
try (ZipFile in = new ZipFile(inputFile);
FileOutputStream out = new FileOutputStream(outputfile)){
signer.sign(in, out);
}
}
[XMSSGen]
public class BCXMSSCertificateGenerator {
public static X509Certificate generateCertificate(PrivateKey privKey, PublicKey pubKey, int duration, boolean isSelfSigned) throws Exception {
Provider BC = new BouncyCastleProvider();
//
// distinguished name table.
//
X500NameBuilder builder = createStdBuilder();
//
// create the certificate - version 3
//
ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withXMSS").setProvider("BCPQC").build(privKey);
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(new X500Name("cn=Java"), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), new Date((long)(System.currentTimeMillis() + duration*8.65*Math.pow(10,7))), builder.build(), pubKey);
X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));
cert.checkValidity(new Date());
if (isSelfSigned) {
//
// check verifies in general
//
cert.verify(pubKey);
//
// check verifies with contained key
//
cert.verify(cert.getPublicKey());
}
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", BC);
return (X509Certificate) fact.generateCertificate(bIn);
}
private static X500NameBuilder createStdBuilder() {
X500NameBuilder builder = new X500NameBuilder(RFC4519Style.INSTANCE);
builder.addRDN(RFC4519Style.c, "AU");
builder.addRDN(RFC4519Style.o, "The Legion of the Bouncy Castle");
builder.addRDN(RFC4519Style.l, "Melbourne");
builder.addRDN(RFC4519Style.st, "Victoria");
builder.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "feedback-crypto#bouncycastle.org");
return builder;
}
}
[XMSSVer]
public class BCXMSSCertificateVerifyer {
public static boolean verifyCertificate(byte[] certBytes, String sigAlgorithm, byte[] keyBytes) throws Exception{
ByteArrayInputStream bIn;
bIn = new ByteArrayInputStream(certBytes);
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
Certificate cert = fact.generateCertificate(bIn);
PublicKey k = cert.getPublicKey();
X509CertificateHolder certHldr = new X509CertificateHolder(certBytes);
certHldr.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BCPQC").build(k));
System.out.println(cert);
KeyFactory keyFactory = KeyFactory.getInstance(k.getAlgorithm(), "BCPQC");
PrivateKey privKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); // ERROR at this line
/*_______________________________________________________________________________________________________________*\
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.lang.ClassCastException: org.bouncycastle.asn1.DLSequence cannot be cast to org.bouncycastle.asn1.ASN1Integer
at org.bouncycastle.pqc.jcajce.provider.xmss.XMSSKeyFactorySpi.engineGeneratePrivate(Unknown Source)
at java.base/java.security.KeyFactory.generatePrivate(KeyFactory.java:384)
at BCXMSSCertificateVerifyer.verifyCertificate(BCXMSSCertificateVerifyer.java:32)
at BCXMSSCertificateTester.main(BCXMSSCertificateTester.java:23)
_________________________________________________________________________________________________________________
/* */
Signature signer = Signature.getInstance(sigAlgorithm, "BCPQC");
signer.initSign(privKey);
signer.update(certBytes);
byte[] sig = signer.sign();
signer.initVerify(cert);
signer.update(certBytes);
signer.verify(sig);
return true;
}
}
TL;DR: Signing .jar Files with PQC Signature schemes such as XMSS provided by BC using the built in JarSigner is not possible. However one can wright its one JarSigner which then can.
Although Oracle provides with JCA/JCE an out of the box integration for Crypto Provider such as BC those registered providers are not used from JarSigner neither for signing nor for verifying.
Considering the JarSigner: the supported algorithms are hard-coded and can thus not be extended.
The only way to use JarSigner with the BC Provider is to rebuild it entirely. However this is not recommended.
For those which are not afraid of hijacking jdk source code, your project has to "override" the following classes from the jdk:
AlgorithmId
Attributes
ContentInfo
EndEntityChecker
HttpTimestamper
InvalidJarIndexError
Jarentry
JarException
JarFile
JarIndex
JarInputStream
JarOutputStream
JarSigner
JarVerifier
JavaUtilJarAccess
JavaUtilJarAccessImpl
JavaUtilZipFileAccess
Main (jdk.jartool.sun.security.tools.jarsigner)
Manifest
ManifestEntryVerifier
Pack200
PKCS7
PKIXValidator
Resources
Resources_ja
Resources_zh_CN
SharedSecrets
SignatureFileVerifier
SignerInfo
SimpleValidator
TimestampedSigner
Timestamper
TimestampToken
TSResponse
Validator
VersionedStream
Therefor copy paste the original code into your project and remove the import of all classes which you hijack so your "custom" classes will be taken instead of the official ones.
Note: Most of the classes mentioned above can be found in the java.base module, although some are in the jdk.jartool module (such as the JarSigner itself).
After cloning the necessary part of the jdk to get the JarSigner to work you can finally move on implementing your BC provider and the support of the PQC Signature Schemes, especially XMSSMT and SPHINCS, as for the moment it seems like XMSS has some major problems.
Note that for the verification of a signed jar file the JarVerifier takes the file extension of the signature block file and checks rather if its .RSA, .DCA or .EC. So you will have to add .XMSS .XMSSMT .SPHINCS256 etc. You will also have to tell the PKCS7 class in the parseSignedData method to use a BC certificate generator.
There are a few other things to change as well (e.g. AlgorithmID) which I don't remember, but once you have done all the necessary steps, your JarSigner is able to sign and verify .jar files using BC in addition to using the "normal" RSA DCA and EC signing and verifying.
Sadly I will not be able to share the final Source Code with you, although I will try answer as much of your questions as possible.

Signing file with hardware token

I'm trying to sign some files with SafeNet eToken5110. I have managed to get certificate from it but found out that i can't export PrivateKey. I developed some code to encrypt/decrypt files with common certificate, now my issue is to do the same with eToken. But i can't find any info how to do that.
Any tips? Is there any API for that? (and documentation/examples)
Ok, I've found out how to sign smtx with hardware token, and I hope someone will find it usefull. Need to use Signature class and SunPKCS11 provider
public static byte[] sign(byte[] file) throws Exception {
char password[] = "12345678".toCharArray();
Provider userProvider = new sun.security.pkcs11.SunPKCS11("C:\\ForJava\\eToken.cfg");
KeyStore ks = KeyStore.getInstance("PKCS11", userProvider);
ks.load(null, password);
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Security.addProvider(userProvider);
//Working only with the first alias on the token
String alias = (String)ks.aliases().nextElement();
Signature signature = Signature.getInstance("SHA256withRSA");
PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password);
signature.initSign(privateKey);
signature.update(file);
byte[] result = signature.sign();
//System.out.println("result coding: \n" +new BASE64Encoder().encode(result));
return result;
}
To verify signed data u can use the following code
public static void verify(byte[] sig, byte[] original) throws Exception {
Keystore keystore = initKeystore();
PublicKey key = keystore.getCertificate(getCertAlias()).getPublicKey();
Signature s = Signature.getInstance("SHA256withRSA");
s.initVerify(key);
s.update(original);
if ( ! s.verify(sig)) {
System.out.println("Signature check FAILED");
return;
}
System.out.println("Signature check PASSED");
}
Please add initKeysStore() method into it. It will be more useful then.

Extract ECPublicKey from a X509 certicate

I'm having trouble extracting an ECPublicKey from an X509 certifcate using Java.
The keys and certificate were created as follows
ssh-keygen -t ecdsa -f id_ecdsa
openssl pkcs8 -topk8 -in id_ecdsa -out id_ecdsa.p8
openssl req -new x509 -key id_ecdsa.p8 -out id_ecdsa.crt.der -outform der
The code used to extract the public key from the certificate is
FileInputStream fin = new FileInputStream("<path to id_ecdsa.crt.der>");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(fin);
PublicKey pk = cert.getPublicKey();
if (pk instanceof ECPublicKey) {
ECPublicKey key = (ECPublicKey) pk;
...
} else if (pk instanceof RSAPublicKey) {
RSAPublicKey key = (RSAPublicKey) pk;
...
}
For a certificate containing an RSA key all is ok. However if an ECDSA key is used the if(pk instanceof ECPublicKey) block is ignored.
A call to pk.getAlgorithm() yields "EC" which suggests the key is an ECDSA key.
Examination of pk with a debugger yields a type X509Key for ECDSA. For an RSA key the debugger yields RSAPublicKeyImpl.
N.B. java.security.* is used as the library.
Any help solving my problem would be greatly appreciated.
TrustManagerFactory tmf;
try {
tmf = TrustManagerFactory.getInstance("X509");
tmf.init((KeyStore) null);
for (TrustManager trustManager : tmf.getTrustManagers()) {
((X509TrustManager) trustManager).checkServerTrusted(
chain, authType);
}
} catch (Exception e) {
}
ECPublicKey pubkey = (ECPublicKey) chain[0].getPublicKey();
I found that adding Bouncy Castle as a provider appears to have fixed my issue. It appears JDK is not fitted with EC support by default.
Security.addProvider(new BouncyCastleProvider());
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");

Correctly creating a new certificate with an intermediate certificate using bouny castle

So my problem is as follows,
Basically I want to create a certificate chain using bouncy castle (jdk16 version 1.46). I am rather new to bouncy castle and java.security in general so if my approach might be completely wrong, but anyway this is what I did:
So far I am able to create a self signed certificate which I use as the root certificate. This is done using the following code:
//-----create CA certificate with key
KeyPair caPair = Signing.generateKeyPair("DSA", 1024, null, null);
This basically creates the keypair, the two null options are for a provider and a secure random, if needed.
Map<ASN1ObjectIdentifier, Entry<Boolean, DEREncodable>> caMap = new HashMap<ASN1ObjectIdentifier, Entry<Boolean, DEREncodable>>();
caMap.put(X509Extensions.BasicConstraints, new AbstractMap.SimpleEntry<Boolean, DEREncodable>(true, new BasicConstraints(true)));
//------this creates the self signed certificate
X509Certificate caCert = X509CertificateGenerator.generateX509Certificate(serial, "CN=CA", "CN=CA", start, end, "SHA1withDSA", caPair.getPrivate(), caPair.getPublic(), null, caMap);
This will create the a certificate with the provided attributes.
serial = simply the current time in milliseconds
start = same as serial basically (may have 1 or 2 milliseconds difference)
end = start + 2 days
The map simply adds the basic contraint to set the certificate to be a CA. I use a map here since I want to be able to add additional X509Extensions if need be.
//-----save ca certificate in PEM format
X509CertificateGenerator.savePemX509Certificate(caCert, caPair.getPrivate(), caWriter);
This will store the certificate and private key in a pem file using the bouncy caste pem writer.
After that the file is generated and I can install the file as well (I use IE and then install it via the Internet Options as a trusted CA. The certificate is also shown to be valid).
After that I create the intermediate certificate, using the following code (note the above code is in the same scope so those variables are available as well)
KeyPair intermediatePair = Signing.generateKeyPair("DSA", 1024, null, null);
Map<ASN1ObjectIdentifier, Entry<Boolean, DEREncodable>> intermediateMap = new HashMap<ASN1ObjectIdentifier, Entry<Boolean, DEREncodable>>();
intermediateMap.put(X509Extensions.AuthorityKeyIdentifier, new AbstractMap.SimpleEntry<Boolean, DEREncodable>(false, new AuthorityKeyIdentifierStructure(caCert)));
intermediateMap.put(X509Extensions.SubjectKeyIdentifier, new AbstractMap.SimpleEntry<Boolean, DEREncodable>(false, new SubjectKeyIdentifierStructure(intermediatePair.getPublic())));
X509Certificate intermediateCert = X509CertificateGenerator.generateX509Certificate(serial.add(BigInteger.valueOf(1l)), "CN=intermediate", caCert.getSubjectX500Principal().toString(), start, end, "SHA1withDSA", caPair.getPrivate(), intermediatePair.getPublic(), null, intermediateMap);
//-----save intermediate certificate in PEM format
X509CertificateGenerator.savePemX509Certificate(intermediateCert, intermediatePair.getPrivate(), intermediateWriter);
The procedure is bascially the same, however I add additional X509Extensions:
X509Extensions.AuthorityKeyIdentifier = sets the CA certificate as the intermediates parent
X509Extensions.SubjectKeyIdentifier = uses the generates public key for the certificate
furthermore the CA is used as the issuer and the CA private key is used to create the intermediate certificate.
This also works and I can install the intermediate certificate (using IE again), it is also shown that the parent certififcate is the generated CA certificate and that the certificate is valid.
Now comes the tricky part where I am making a mistake I guess. I now create a new certificate using the intermediate certificate, using the following code.
KeyPair endPair = Signing.generateKeyPair("DSA", 1024, null, null);
Map<ASN1ObjectIdentifier, Entry<Boolean, DEREncodable>> endMap = new HashMap<ASN1ObjectIdentifier, Entry<Boolean, DEREncodable>>();
endMap.put(X509Extensions.AuthorityKeyIdentifier, new AbstractMap.SimpleEntry<Boolean, DEREncodable>(false, new AuthorityKeyIdentifierStructure(intermediateCert)));
endMap.put(X509Extensions.SubjectKeyIdentifier, new AbstractMap.SimpleEntry<Boolean, DEREncodable>(false, new SubjectKeyIdentifierStructure(endPair.getPublic())));
X509Certificate endCert = X509CertificateGenerator.generateX509Certificate(serial.add(BigInteger.valueOf(1l)), "CN=end", intermediateCert.getSubjectX500Principal().toString(), start, end, "SHA1withDSA", intermediatePair.getPrivate(), endPair.getPublic(), null, endMap);
X509CertificateGenerator.savePemX509Certificate(endCert, endPair.getPrivate(), endWriter);
Essentially it is the same as creating the intermediate certificate. However I now use the following X509Extension settings:
X509Extensions.AuthorityKeyIdentifier = sets the intermediate certificate as the certificates parent
X509Extensions.SubjectKeyIdentifier = uses the generates public key for the certificate
Also the intermediate certificate is used as the issuer and its private key is used to create the certificate.
I can also install the new certificate but when I examine if (again IE), it shows that the certificate is however invalid because "This CA is either not entitled to issue certificates or the certificate can not be used as an end-entity."
So I somehow need to enable the intermediate certificate to be able to create new certificates as well, by adding some KeyUsages/ExtendedKeyUsage I assume.
Does someone know how I enable the intermediate certificate to do what I need it to do or if I do something wrong in general ?
EDIT 1:
So okay I forgot to provide the code for the method which created the certificate and the one that saved it in PEM format (I renamed it to savePemX509Certificate since the old one was misguiding).
Code for the certificate generation:
public static X509Certificate generateX509Certificate(BigInteger serialnumber, String subject, String issuer, Date start , Date end, String signAlgorithm, PrivateKey privateKey, PublicKey publicKey, String provider, Map<ASN1ObjectIdentifier, Entry<Boolean, DEREncodable>> map) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException
{
if(serialnumber!=null && subject!=null && issuer!=null && start!=null && end!=null && signAlgorithm !=null && privateKey!=null && publicKey!=null)
{
//-----GENERATE THE X509 CERTIFICATE
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
X509Principal dnSubject = new X509Principal(subject);
X509Principal dnIssuer = new X509Principal(issuer);
certGen.setSerialNumber(serialnumber);
certGen.setSubjectDN(dnSubject);
certGen.setIssuerDN(dnIssuer);
certGen.setNotBefore(start);
certGen.setNotAfter(end);
certGen.setPublicKey(publicKey);
certGen.setSignatureAlgorithm(signAlgorithm);
//-----insert extension if needed
if(map!=null)
for(ASN1ObjectIdentifier extension : map.keySet())
certGen.addExtension(extension, map.get(extension).getKey(), map.get(extension).getValue());
return certGen.generate(privateKey, provider);
}
return null;
}
Code for the saveing of the certificate and key:
public static boolean savePemX509Certificate(X509Certificate cert, PrivateKey key, Writer writer) throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, SignatureException, InvalidKeyException, IOException
{
if(cert!=null && key!=null && writer!=null)
{
PEMWriter pemWriter = new PEMWriter(writer);
pemWriter.writeObject(cert);
pemWriter.flush();
if(key!=null)
{
pemWriter.writeObject(key);
pemWriter.flush();
}
pemWriter.close();
return true;
}
return false;
}
As you can see I basically put the certificate and the key in the file, thats all. The result is the following and seems good to me.
-----BEGIN CERTIFICATE-----
MIICdjCCAjagAwIBAgIGAUDuXLRLMAkGByqGSM44BAMwDTELMAkGA1UEAwwCQ0Ew
HhcNMTMwOTA1MTM0MzA3WhcNMTMwOTA3MTM0MzA3WjANMQswCQYDVQQDDAJDQTCC
AbcwggEsBgcqhkjOOAQBMIIBHwKBgQD9f1OBHXUSKVLfSpwu7OTn9hG3UjzvRADD
Hj+AtlEmaUVdQCJR+1k9jVj6v8X1ujD2y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gE
exAiwk+7qdf+t8Yb+DtX58aophUPBPuD9tPFHsMCNVQTWhaRMvZ1864rYdcq7/Ii
Axmd0UgBxwIVAJdgUI8VIwvMspK5gqLrhAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4
V7l5lK+7+jrqgvlXTAs9B4JnUVlXjrrUWU/mcQcQgYC0SRZxI+hMKBYTt88JMozI
puE8FnqLVHyNKOCjrh4rs6Z1kW6jfwv6ITVi8ftiegEkO8yk8b6oUZCJqIPf4Vrl
nwaSi2ZegHtVJWQBTDv+z0kqA4GEAAKBgAeFoGATLbIr8+QNuxcbYJ7RhbefKWSC
Br67Pp4Ynikxx8FZN4kCjGX7pwT1KffN3gta7jxIXNM5G3IFbs4XnYljh5TbdnjP
9Ge3kxpwncsbMQfCqIwHh8T5gh55KaxH7yYV2mrtEEqj7NBL4thQhJe2WGwgkB9U
NxNmLoMq3m4poyMwITAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAJ
BgcqhkjOOAQDAy8AMCwCFFm5ybLY09y8y2uGsEnpceffy2KaAhQIyshgy3ohCLxQ
q3CmnvC+cfT2VQ==
-----END CERTIFICATE-----
-----BEGIN DSA PRIVATE KEY-----
MIIBuwIBAAKBgQD9f1OBHXUSKVLfSpwu7OTn9hG3UjzvRADDHj+AtlEmaUVdQCJR
+1k9jVj6v8X1ujD2y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7qdf+t8Yb
+DtX58aophUPBPuD9tPFHsMCNVQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdg
UI8VIwvMspK5gqLrhAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlX
TAs9B4JnUVlXjrrUWU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCj
rh4rs6Z1kW6jfwv6ITVi8ftiegEkO8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtVJWQB
TDv+z0kqAoGAB4WgYBMtsivz5A27FxtgntGFt58pZIIGvrs+nhieKTHHwVk3iQKM
ZfunBPUp983eC1ruPEhc0zkbcgVuzhediWOHlNt2eM/0Z7eTGnCdyxsxB8KojAeH
xPmCHnkprEfvJhXaau0QSqPs0Evi2FCEl7ZYbCCQH1Q3E2YugyrebikCFDJCJHtt
NWB4LWYc4y4QvJ/l46ap
-----END DSA PRIVATE KEY-----
So after gtrig provided me with the correct way to create the certificate, I ended up using this method to create either a normal or self signed (if the private key is from the same keyPair as the public key that is) certificate
public static X509Certificate createX509V3Certificate(X500Principal name, BigInteger serial, Date start, Date end, PublicKey pubKey, String algorithm, PrivateKey privateKey, Map<ASN1ObjectIdentifier, Entry<Boolean, ASN1Object>> map, X509Certificate parentCert) throws IOException, OperatorCreationException, CertificateException
{
if(serial!=null && start!=null && end!=null && name!=null && pubKey!=null && algorithm!=null && privateKey!=null)
{
ContentSigner signer = new JcaContentSignerBuilder(algorithm).build(privateKey);
X509v3CertificateBuilder certBldr = null;
if(parentCert==null)
certBldr = new JcaX509v3CertificateBuilder(name, serial, start, end, name, pubKey);
else
certBldr = new JcaX509v3CertificateBuilder(parentCert, serial, start, end, name, pubKey);
if(map!=null)
for(ASN1ObjectIdentifier extension : map.keySet())
certBldr.addExtension(extension, map.get(extension).getKey(), map.get(extension).getValue());
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer));
}
return null;
}
Something looks wrong with the way you're creating the PEM files. You're using a method called, generateSelfSignedPemX509Certificate, but you don't really want a self-signed certificate, you want an end certificate signed by the intermediate private key, and you want an intermediate certificate signed by the CA private key.
Also, you need basic constraints and key usage extensions on your certificates.
For creating certificates signed by other entities (non-self-signed), I use these methods from Bouncy Castle to create an "end" certificate.
ASN1Sequence seq=
(ASN1Sequence) new ASN1InputStream(parentPubKey.getEncoded()).readObject();
SubjectPublicKeyInfo parentPubKeyInfo = new SubjectPublicKeyInfo(seq);
ContentSigner signer = new JcaContentSignerBuilder(algorithm).build(parentPrivKey);
X509v3CertificateBuilder certBldr =
new JcaX509v3CertificateBuilder(
parentCert,
serialNum,
startDate,
endDate,
distName,
pubKey)
.addExtension(
new ASN1ObjectIdentifier("2.5.29.35"),
false,
new AuthorityKeyIdentifier(parentPubKeyInfo))
.addExtension(
new ASN1ObjectIdentifier("2.5.29.19"),
false,
new BasicConstraints(false)) // true if it is allowed to sign other certs
.addExtension(
new ASN1ObjectIdentifier("2.5.29.15"),
true,
new X509KeyUsage(
X509KeyUsage.digitalSignature |
X509KeyUsage.nonRepudiation |
X509KeyUsage.keyEncipherment |
X509KeyUsage.dataEncipherment));
// Build/sign the certificate.
X509CertificateHolder certHolder = certBldr.build(signer);
X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
.getCertificate(certHolder);
For a CA or intermediate certificate, you'll need to add a SubjectKeyIdentifier extension. Also, BasicConstraints should be true, and KeyUsage should be:
new X509KeyUsage(
X509KeyUsage.keyCertSign|
X509KeyUsage.cRLSign));

Store PGP (public) keys in java keystore - Bouncycastle

I am using bouncycastle (JAVA) for signing, encryption, decryption and signatures' verification in implementation of SSO.
I have raw PGP public and private keys and I need to store them in Java keystore.
These PGP public keys have no certificate.
I understand that for public keys (according to javadoc of Keystore: http://docs.oracle.com/javase/6/docs/api/java/security/KeyStore.html) I have to create certificate. Once certificate is created I can import it to the keystore as KeyStore.TrustedCertificateEntry.
However, I am not able to create certificate entry for type org.bouncycastle.openpgp.PGPPublicKey.
I have searched through the web but could not find any valid example:
Bouncycastle documentation: http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation
Generates certificate for X.509 keys -
Bouncycastle examples - org.bouncycastle.openpgp.examples.DirectKeySignature:
Add certificat (object of type PGPSignature) directly to the PGPPublicKey.
To conclude - I have signed (certified) PGPPublicKey but I am not able to store this type of Key into the java keystore.
OutputStream out = new ByteArrayOutputStream();
if (armor)
{
out = new ArmoredOutputStream(out);
}
PGPPrivateKey pgpPrivKey = secretKey.extractPrivateKey(secretKeyPass.toCharArray(), "BC");
PGPSignatureGenerator sGen = new PGPSignatureGenerator(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC");
sGen.initSign(PGPSignature.DIRECT_KEY, pgpPrivKey);
BCPGOutputStream bOut = new BCPGOutputStream(out);
sGen.generateOnePassVersion(false).encode(bOut);
PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
boolean isHumanReadable = true;
spGen.setNotationData(true, isHumanReadable, notationName, notationValue);
PGPSignatureSubpacketVector packetVector = spGen.generate();
sGen.setHashedSubpackets(packetVector);
bOut.flush();
return PGPPublicKey.addCertification(keyToBeSigned, sGen.generate()).getEncoded();
I am mainly interested in programatic solution (java source code) but examples that use some tools will be helpful too.
Thanks!
I think you should extract a java.security.PublicKey from your PGPPublicKey and use that to construct an X509Certificate which can be stored in a keystore.
JcaPGPKeyConverter c = new JcaPGPKeyConverter();
PublicKey publicKey = c.getPublicKey(pgpPublicKey);
// ... Use Bouncy's X509V3CertificateGenerator or X509v3CertificateBuilder
// ... to construct a self-signed cert
X509Certificate x509Certificate = // ...
// ... add cert to KeyStore
To create an X509Certificate from a PublicKey see: Generate random certificates.
If you only want to save the public key, why cannot you just save the key content into Java keystore? Then retrieve the content and convert into a PGPPublicKey object when you need it.
Create a wrapper class first
public class PgpPublicKeyWrapper implements Key {
private final String keyContent;
public PgpPublicKeyWrapper(final String keyContent) {
this.keyContent = keyContent;
}
#Override
public String getAlgorithm() {
return "PGP-PublicKey"; // you can call whatever you want
}
#Override
public String getFormat() {
return "RAW"; // has to be raw format
}
#Override
public byte[] getEncoded() {
return keyContent.getBytes();
}
}
Then you can do this to save it
keyStore.setKeyEntry("think a name for alias", new PgpPublicKeyWrapper(key), PASSWORD, null);
When you want to retrieve it
Key key = this.keyStore.getKey(alias, PASSWORD);
InputStream is = new ByteArrayInputStream(key.getEncoded());
PGPPublicKey publicKey = readPublicKey(is);
For readPublicKey(), you can find a lot of examples online about how to read InputStream to a PGPPublicKey object.

Categories

Resources