Search in sources :

Example 36 with X509Certificate

use of java.security.cert.X509Certificate in project OpenAttestation by OpenAttestation.

the class X509Builder method build.

public X509Certificate build() {
    if (certificateVersion == null) {
        v3();
    }
    if (certificateValidity == null) {
        // 1 year default
        expires(365, TimeUnit.DAYS);
    }
    if (certificateSerialNumber == null) {
        randomSerial();
    }
    if (certificateSubjectName == null) {
        if (commonName != null || organizationUnit != null || organizationName != null || country != null) {
            try {
                subjectName(new X500Name(commonName, organizationUnit, organizationName, country));
            } catch (Exception e) {
                fault(e, "commonName(%s) organizationUnit(%s) organizationName(%s) country(%s)", commonName, organizationUnit, organizationName, country);
            }
        }
    }
    if (certificateIssuerName == null) {
        //}
        if (commonName != null || organizationUnit != null || organizationName != null || country != null) {
            try {
                issuerName(new X500Name(commonName, organizationUnit, organizationName, country));
            } catch (Exception e) {
                fault(e, "commonName(%s) organizationUnit(%s) organizationName(%s) country(%s)", commonName, organizationUnit, organizationName, country);
            }
        }
    }
    if (subjectPublicKey == null) {
        fault("missing subject public key");
    }
    // Note: alternativeName is optional so we don't have any defaults or errors for it here
    if (algorithm == null) {
        // algorithm.getName() == SHA256withRSA
        algorithm(new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid));
    }
    //}
    try {
        if (getFaults().isEmpty()) {
            // Sign the cert to identify the algorithm that's used.
            X509CertImpl cert = new X509CertImpl(info);
            // NoSuchAlgorithMException, InvalidKeyException, NoSuchProviderException, , SignatureException
            cert.sign(issuerPrivateKey, algorithm.getName());
            /*
                 * for some unknown reason, if we return the "cert" now then all 
                 * the optioanl fields such as getBasicConstraints() and 
                 * getKeyUsage() are missing even though they are included if you 
                 * call getEncoded() ... but if you re-create the certificate
                 * then those fields are present in the re-created certificate.
                 */
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert2 = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));
            return cert2;
        }
        return null;
    } catch (Exception e) {
        fault(e, "cannot sign certificate");
        return null;
    } finally {
        done();
    }
}
Also used : CertificateAlgorithmId(sun.security.x509.CertificateAlgorithmId) AlgorithmId(sun.security.x509.AlgorithmId) ByteArrayInputStream(java.io.ByteArrayInputStream) X509CertImpl(sun.security.x509.X509CertImpl) X500Name(sun.security.x509.X500Name) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 37 with X509Certificate

use of java.security.cert.X509Certificate in project OpenAttestation by OpenAttestation.

the class X509Util method decodeDerCertificate.

/**
     * Reads a DER-encoded certificate and creates a corresponding X509Certificate
     * object.
     * @param certificateBytes
     * @return
     * @throws CertificateException 
     */
public static X509Certificate decodeDerCertificate(byte[] certificateBytes) throws CertificateException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
    return cert;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 38 with X509Certificate

use of java.security.cert.X509Certificate in project OpenAttestation by OpenAttestation.

the class TrustFirstCertificateTlsPolicy method addServerCertificatesToRepository.

private void addServerCertificatesToRepository(X509Certificate[] xcs) {
    for (X509Certificate cert : xcs) {
        System.out.println("server certificate: " + cert.getSubjectX500Principal().getName());
    }
    for (int i = 0; i < xcs.length; i++) {
        try {
            // CertificateExpiredException, CertificateNotYetValidEception
            xcs[i].checkValidity();
            log.info("Saving certificate {}", xcs[i].getSubjectX500Principal().getName());
            // KeyManagementException
            repository.addCertificate(xcs[i]);
        } catch (Exception e) {
            log.trace("TrustFirstCertificateTlsPolicy addServerCertificateToRepository cert was not valid. trying to save next cert");
        // don't throw an exception because we may be able to save other certificates? throw new CertificateException("Unable to save server certificate", e);
        }
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) CertificateException(java.security.cert.CertificateException)

Example 39 with X509Certificate

use of java.security.cert.X509Certificate in project OpenAttestation by OpenAttestation.

the class ArrayCertificateRepositoryTest method testGetCertificateForAddress.

@Test
public void testGetCertificateForAddress() throws Exception {
    X509Certificate x509 = arrayCertificateRepository.getCertificateForAddress(new InternetAddress("OATServer"));
    assertNotNull(x509);
    assertSame(x509, keystore[0]);
}
Also used : InternetAddress(com.intel.mtwilson.util.net.InternetAddress) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Example 40 with X509Certificate

use of java.security.cert.X509Certificate in project OpenAttestation by OpenAttestation.

the class CertificateUtils method generateSelfSignedX509Certificate.

/**
	 * Generate a self signed X509 certificate with Bouncy Castle.
	 * @throws SignatureException 
	 * @throws IllegalStateException 
	 * @throws InvalidKeyException 
	 * @throws CertificateEncodingException 
	 */
public static X509Certificate generateSelfSignedX509Certificate() throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, InvalidKeyException, IllegalStateException, SignatureException {
    Security.addProvider(new BouncyCastleProvider());
    int validityDays = 3652;
    // GENERATE THE PUBLIC/PRIVATE RSA KEY PAIR
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
    keyPairGenerator.initialize(1024, new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    // GENERATE THE X509 CERTIFICATE
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal dnName = new X500Principal("CN=OATServer");
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setSubjectDN(dnName);
    // use the same
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis()));
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);
    certGen.setNotAfter(expiry.getTime());
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");
    return cert;
}
Also used : KeyPair(java.security.KeyPair) X509V1CertificateGenerator(org.bouncycastle.x509.X509V1CertificateGenerator) Calendar(java.util.Calendar) SecureRandom(java.security.SecureRandom) X500Principal(javax.security.auth.x500.X500Principal) KeyPairGenerator(java.security.KeyPairGenerator) X509Certificate(java.security.cert.X509Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

X509Certificate (java.security.cert.X509Certificate)1706 IOException (java.io.IOException)336 CertificateException (java.security.cert.CertificateException)272 ByteArrayInputStream (java.io.ByteArrayInputStream)260 CertificateFactory (java.security.cert.CertificateFactory)251 ArrayList (java.util.ArrayList)232 Certificate (java.security.cert.Certificate)227 KeyStore (java.security.KeyStore)177 PrivateKey (java.security.PrivateKey)150 InputStream (java.io.InputStream)134 File (java.io.File)112 KeyStoreException (java.security.KeyStoreException)112 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)111 GeneralSecurityException (java.security.GeneralSecurityException)100 Test (org.junit.Test)90 List (java.util.List)89 PublicKey (java.security.PublicKey)88 X509TrustManager (javax.net.ssl.X509TrustManager)80 X500Principal (javax.security.auth.x500.X500Principal)76 HashSet (java.util.HashSet)64