Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > Java > Other Java > BOOK: Beginning Cryptography with Java
Password Reminder
Register
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
BOOK: Beginning Cryptography with Java
This is the forum to discuss the Wrox book Beginning Cryptography with Java by David Hook; ISBN: 9780764596339
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Beginning Cryptography with Java section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old November 8th, 2015, 11:52 AM
Registered User
Points: 27, Level: 1
Points: 27, Level: 1 Points: 27, Level: 1 Points: 27, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Nov 2015
Posts: 6
Thanks: 1
Thanked 0 Times in 0 Posts
Default Java KeyStore not storing whole certificate chain

I'm using the following code to generate a certificate chain with a root certificate, an intermediate and an end certificate:

TestCertificates.java
Code:
public class TestCertificates {
     private static final int VALIDITY_PERIOD = 7 * 24 * 60 * 60 * 1000; // one week
    /**
     * Generate a sample V1 certificate to use as a CA root certificate
     */
    public static X509Certificate generateRootCert(KeyPair pair) throws Exception {

    // Pick the public-key signature algorithm to sign certificates. We are using RSA
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(X509_CERTIFICATE_SIGNATURE_ALGORITHM);
    // Pick the algorithm to perform the hashing on the information to be signed. We
    // sign the resulting hash
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    // Retrieve the private key which is used to sign the certificate
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    // Retrieve the pulic key information used by the subject to verify
    // the signature
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    // Define the validity period. The certificate may expire before the
    // end date but not after.
    Date startDate = new Date(System.currentTimeMillis());
    Date endDate = new Date(System.currentTimeMillis() + VALIDITY_PERIOD);
    X500Name name = new X500Name("CN=Root");
    // Create unique serial number for the certificate (need to check if it
    // it's actually unique)
    BigInteger serialNum = BigInteger.valueOf(new SecureRandom().nextLong());
    // Generate the actual certificate
    X509v1CertificateBuilder certGen = new X509v1CertificateBuilder(name, serialNum, startDate, endDate, name, subPubKeyInfo);
    // Sign it
    X509CertificateHolder certificateHolder = certGen.build(sigGen);

    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);

}

/**
 * Generate a sample V3 certificate to use as an intermediate CA certificate
 */
public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert) throws Exception {

    ASN1Sequence seq = null;

    seq = (ASN1Sequence) new ASN1InputStream(intKey.getEncoded()).readObject();
    SubjectPublicKeyInfo parentPubKeyInfo = new SubjectPublicKeyInfo(seq);
    // Define the validity period. The certificate may expire before the
    // end date but not after.
    Date startDate = new Date(System.currentTimeMillis());
    Date endDate = new Date(System.currentTimeMillis() + VALIDITY_PERIOD);
    ContentSigner signer = null;

    signer = new JcaContentSignerBuilder(X509_CERTIFICATE_SIGNATURE_ALGORITHM).build(caKey);

    // Create unique serial number for the certificate (need to check if it
    // it's actually unique)
    BigInteger serialNum = BigInteger.valueOf(new SecureRandom().nextLong());
    X509v3CertificateBuilder certGen = null;

    certGen = new JcaX509v3CertificateBuilder(
            caCert,
            serialNum,
            startDate,
            endDate,
            new X500Principal("CN=Intermediate Certificate"),
            intKey)
            .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 = certGen.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);

    return cert;
}

/**
 * Generate a sample V3 certificate to use as an end entity certificate
 */
public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception {
    ASN1Sequence seq = null;
    seq = (ASN1Sequence) new ASN1InputStream(entityKey.getEncoded()).readObject();
    SubjectPublicKeyInfo parentPubKeyInfo = new SubjectPublicKeyInfo(seq);
    // Define the validity period. The certificate may expire before the
    // end date but not after.
    Date startDate = new Date(System.currentTimeMillis());
    Date endDate = new Date(System.currentTimeMillis() + VALIDITY_PERIOD);
    ContentSigner signer = null;

    signer = new JcaContentSignerBuilder(X509_CERTIFICATE_SIGNATURE_ALGORITHM).build(caKey);

    // Create unique serial number for the certificate (need to check if it
    // it's actually unique)
    BigInteger serialNum = BigInteger.valueOf(new SecureRandom().nextLong());

    X509v3CertificateBuilder certGen = null;

    certGen = new JcaX509v3CertificateBuilder(
            caCert,
            serialNum,
            startDate,
            endDate,
            new X500Principal("CN=End Certificate"),
            entityKey)
            .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.keyCertSign |
                                    X509KeyUsage.cRLSign |
                                    X509KeyUsage.dataEncipherment));


    // Build/sign the certificate.
    X509CertificateHolder certHolder = certGen.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);

    return cert;
}

/**
 * Generate a X500PrivateCredential for the root entity.
 */
public static X500PrivateCredential createRootCredential() throws Exception {
    KeyPair rootPair = null;

    rootPair = generateRSAKeyPair();

    X509Certificate rootCert = generateRootCert(rootPair);

    return new X500PrivateCredential(rootCert, rootPair.getPrivate(), ROOT_ALIAS);
}

/**
 * Generate a X500PrivateCredential for the intermediate entity.
 */
public static X500PrivateCredential createIntermediateCredential(
        PrivateKey caKey,
        X509Certificate caCert) throws Exception {
    KeyPair interPair = null;

    interPair = generateRSAKeyPair();

    X509Certificate interCert = generateIntermediateCert(interPair.getPublic(), caKey, caCert);

    return new X500PrivateCredential(interCert, interPair.getPrivate(), INTERMEDIATE_ALIAS);
}

/**
 * Generate a X500PrivateCredential for the end entity.
 */
public static X500PrivateCredential createEndEntityCredential(
        PrivateKey caKey,
        X509Certificate caCert) throws Exception {
    KeyPair endPair = null;

    endPair = generateRSAKeyPair();

    X509Certificate endCert = generateEndEntityCert(endPair.getPublic(), caKey, caCert);

    return new X500PrivateCredential(endCert, endPair.getPrivate(), END_ENTITY_ALIAS);
}

public static void main(String[] args) {
    // Retrieve root, intermediate and end entity credentials
    X500PrivateCredential rootCredential = createRootCredential();
    X500PrivateCredential interCredential = createIntermediateCredential(rootCredential.getPrivateKey(), rootCredential.getCertificate());
    X500PrivateCredential endCredential = createEndEntityCredential(interCredential.getPrivateKey(), interCredential.getCertificate());

    // client credentials
    KeyStore keyStore = null;

    keyStore = KeyStore.getInstance("PKCS12", "BC");
    keyStore.load(null, null);
    keyStore.setKeyEntry("client", endCredential.getPrivateKey(), "clientPassword",
            new Certificate[]{endCredential.getCertificate(), interCredential.getCertificate(), rootCredential.getCertificate()});
    keyStore.store(new FileOutputStream("client.p12", "clientPassword");

    // trust store for client
    keyStore = KeyStore.getInstance("JKS");

    keyStore.load(null, null);

    keyStore.setCertificateEntry("trust", rootCredential.getCertificate());

    keyStore.store(new FileOutputStream("trust.jks", "trustPassword");

    // server credentials
    keyStore = KeyStore.getInstance("JKS");

    keyStore.load(null, null);

    keyStore.setKeyEntry("server", rootCredential.getPrivateKey(), "serverPassword",
            new Certificate[]{rootCredential.getCertificate()});

    keyStore.store(new FileOutputStream("server.jks", "serverPassword");
}
}
The certificates are generated (they are present in memory and all fields appear to be valid) and written to the key store client.p12.

However, when viewing the contents of the file only a single entry is present (there is no intermediate or end certificate):

Code:
$ keytool -list -keystore client.p12 -storepass clientPassword -storetype PKCS12

Keystore type: PKCS12
Keystore provider: SunJSSE

Your keystore contains 1 entry

client, Nov 8, 2015, PrivateKeyEntry,
Certificate fingerprint (SHA1): B9:0D:E9:99:64:9F:49:66:3A:F6:3F:19:A7:94:59:F9:38:B8:5B:29
Why are the remaining certificates not present?
Could it be because of fields such that the Issuer not being set when creating the intermediate and the end certificate?

The code is taken from chapters 9 and 10.

Edit:

I have created a git repository with the minimum functionality:

github

Last edited by Sebi; November 8th, 2015 at 04:22 PM..
Reply With Quote
  #2 (permalink)  
Old November 9th, 2015, 08:32 AM
dgh dgh is offline
Wrox Author
Points: 864, Level: 11
Points: 864, Level: 11 Points: 864, Level: 11 Points: 864, Level: 11
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Aug 2005
Location: , , .
Posts: 206
Thanks: 0
Thanked 20 Times in 20 Posts
Default

For PKCS#12 to accept a certificate chain properly you must be able to form a valid certpath from it. The chain will not be rebuilt otherwise.

Regards,

David
Reply With Quote
  #3 (permalink)  
Old November 9th, 2015, 08:35 AM
Registered User
Points: 27, Level: 1
Points: 27, Level: 1 Points: 27, Level: 1 Points: 27, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Nov 2015
Posts: 6
Thanks: 1
Thanked 0 Times in 0 Posts
Default

Quote:
Originally Posted by dgh View Post
For PKCS#12 to accept a certificate chain properly you must be able to form a valid certpath from it. The chain will not be rebuilt otherwise.

Regards,

David
Why is the certpath created by the above code not valid? I have asked another question in which the entire certificate chain is shown.

Bellow is the question containing the whole chain (root, intermediate and end entity certificates).
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
unable to find the manifest signing certificate in the certificate store kgmmurugesh Visual Studio 2008 0 November 16th, 2011 07:31 AM
Storing password using encryption from JAVA inderjeet_79 Java Databases 3 October 11th, 2007 04:11 AM
java security certificate issue getsreenuk Apache Tomcat 0 March 3rd, 2007 05:49 AM
Encrypted private keys in keystore tomhay BOOK: Beginning Cryptography with Java 2 December 10th, 2006 08:35 AM
java 1.5 certificate issues drt2928 Pro Java 0 May 23rd, 2006 12:39 PM



All times are GMT -4. The time now is 05:15 PM.


Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.