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 3rd, 2015, 11:51 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 Is this the right way of generating a root, intermediate and end entity certificate?

I have tried running the examples from the book but most of them are deprecated by this time and require an updated version of bouncy castle. I have rewritten the certificate generation methods bellow:

Code:
/**
     * Generate a sample V1 certificate to use as a CA root certificate
     */
    public static X509Certificate generateRootCert(KeyPair pair) {

        try {
            // 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);
        }
        catch (CertificateException e1) {
            System.out.println("[E] Certificate exception: " +  e1.toString());
            log.warn("[E] Certificate exception: " +  e1.toString());
        }
        catch (Exception e) {
            System.out.println("[E] Certificate exception: " +  e.toString());
            log.warn("[E] Certificate exception: " +  e.toString());
        }
        // Failed to create certificate
        return null;
    }

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

        ASN1Sequence seq = null;

        try {
            seq = (ASN1Sequence) new ASN1InputStream(intKey.getEncoded()).readObject();
        } catch (IOException e) {
            System.out.println("[E] ASN1 sequence exception: " +  e.toString());
            log.warn("[E] ASN1 sequence exception: " +  e.toString());
        }

        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;
        try {
            signer = new JcaContentSignerBuilder(X509_CERTIFICATE_SIGNATURE_ALGORITHM).build(caKey);
        } catch (OperatorCreationException e) {
            System.out.println("[E] ASN1 sequence exception: " +  e.toString());
            log.warn("[E] ASN1 sequence exception: " +  e.toString());
        }
        // 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;
        try {
            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));
        } catch (CertIOException e) {
            System.out.println("[E] Certificate builder exception: " +  e.toString());
            log.warn("[E] Certificate builder exception: " + e.toString());
        }

        // Build/sign the certificate.
        X509CertificateHolder certHolder = certGen.build(signer);

        try {
            X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
            return cert;
        } catch (CertificateException e) {
            System.out.println("[E] Certificate build exception: " +  e.toString());
            log.warn("[E] Certificate build exception: " + e.toString());
        }
        return null;
    }

    /**
     * Generate a sample V3 certificate to use as an end entity certificate
     */
    public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) {
        ASN1Sequence seq = null;

        try {
            seq = (ASN1Sequence) new ASN1InputStream(entityKey.getEncoded()).readObject();
        } catch (IOException e) {
            System.out.println("[E] ASN1 sequence exception: " +  e.toString());
            log.warn("[E] ASN1 sequence exception: " +  e.toString());
        }

        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;
        try {
            signer = new JcaContentSignerBuilder(X509_CERTIFICATE_SIGNATURE_ALGORITHM).build(caKey);
        } catch (OperatorCreationException e) {
            System.out.println("[E] ASN1 sequence exception: " +  e.toString());
            log.warn("[E] ASN1 sequence exception: " +  e.toString());
        }
        // 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;
        try {
            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));
        } catch (CertIOException e) {
            System.out.println("[E] Certificate builder exception: " +  e.toString());
            log.warn("[E] Certificate builder exception: " + e.toString());
        }

        // Build/sign the certificate.
        X509CertificateHolder certHolder = certGen.build(signer);

        try {
            X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
            return cert;
        } catch (CertificateException e) {
            System.out.println("[E] Certificate build exception: " +  e.toString());
            log.warn("[E] Certificate build exception: " + e.toString());
        }
        return null;
    }

/**
     * Generate a X500PrivateCredential for the root entity.
     */
    public static X500PrivateCredential createRootCredential()
            throws Exception {
        KeyPair 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 = 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 = generateRSAKeyPair();
        X509Certificate endCert = generateEndEntityCert(endPair.getPublic(), caKey, caCert);

        return new X500PrivateCredential(endCert, endPair.getPrivate(), END_ENTITY_ALIAS);
    }
Are the new procedures valid?

The code that has been modified is located in the Utils.java file in chapter 9 (the methods have the same contract).

Many thanks in advance.

Last edited by Sebi; November 3rd, 2015 at 02:11 PM..
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
Ch 14 generating entity model AlanWheeler BOOK: Beginning ASP.NET 4.5 : in C# and VB 2 April 30th, 2014 07:51 AM
unable to find the manifest signing certificate in the certificate store kgmmurugesh Visual Studio 2008 0 November 16th, 2011 07:31 AM
Oracle back-end MS-Access 2003 client front-end Corey Access 2 February 16th, 2007 08:31 AM
Oracle Back End - MS Access Front End - Multi User ckaliveas Oracle 1 February 1st, 2007 06:00 AM
problem while generating report,through front end anukagni Access 8 January 21st, 2006 02:07 AM



All times are GMT -4. The time now is 11:51 PM.


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