Example usage for org.bouncycastle.asn1.x509 GeneralName GeneralName

List of usage examples for org.bouncycastle.asn1.x509 GeneralName GeneralName

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 GeneralName GeneralName.

Prototype

public GeneralName(int tag, String name) 

Source Link

Document

Create a GeneralName for the given tag from the passed in String.

Usage

From source file:org.xwiki.crypto.pkix.params.x509certificate.extension.X509IpAddress.java

License:Open Source License

/**
 * Construct a IP address general name from an ip address.
 *
 * @param ipAddress the ip address./* w  w  w. j a  v  a 2s. co  m*/
 */
public X509IpAddress(String ipAddress) {
    GeneralName name = new GeneralName(GeneralName.iPAddress, ipAddress);
    this.ipAddress = DEROctetString.getInstance(name.getName()).getOctets();
}

From source file:org.xwiki.crypto.pkix.params.x509certificate.extension.X509IpAddress.java

License:Open Source License

@Override
public GeneralName getGeneralName() {
    return new GeneralName(GeneralName.iPAddress, new DEROctetString(this.ipAddress));
}

From source file:org.xwiki.crypto.pkix.params.x509certificate.extension.X509Rfc822Name.java

License:Open Source License

@Override
public GeneralName getGeneralName() {
    return new GeneralName(GeneralName.rfc822Name, this.str);
}

From source file:org.xwiki.crypto.pkix.params.x509certificate.extension.X509URI.java

License:Open Source License

@Override
public GeneralName getGeneralName() {
    return new GeneralName(GeneralName.uniformResourceIdentifier, this.str);
}

From source file:org.xwiki.crypto.x509.internal.X509Keymaker.java

License:Open Source License

/**
 * Create a new X509 client certificate.
 *
 * @param forCert the public key which will be embedded in the certificate, whoever has the matching private key
 *                "owns" the certificate.
 * @param toSignWith the private key in this pair will be used to sign the certificate.
 * @param daysOfValidity number of days the cert should be valid for.
 * @param nonRepudiable this should only be true if the private key is not stored on the server.
 * @param webId the URI to put as the alternative name (for FOAFSSL webId compatibility)
 * @param userName a String representation of the name of the user getting the certificate.
 * @return a new X509 certificate.// w  ww. j  a v  a  2  s. c  o m
 * @throws GeneralSecurityException if something goes wrong.
 */
public synchronized X509Certificate makeClientCertificate(final PublicKey forCert, final KeyPair toSignWith,
        final int daysOfValidity, final boolean nonRepudiable, final String webId, final String userName)
        throws GeneralSecurityException {
    try {
        // the UID (same for issuer since this certificate confers no authority)
        final X509Name dName = new X509Name("UID=" + userName);

        this.prepareGenericCertificate(forCert, daysOfValidity, dName, dName);

        // Not a CA
        certGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

        // Client cert
        certGenerator.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
                new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime));

        // Key Usage extension.
        int keyUsage = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                | KeyUsage.keyAgreement;
        if (nonRepudiable) {
            keyUsage |= KeyUsage.nonRepudiation;
        }
        certGenerator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));

        // Set the authority key identifier to be the CA key which we are using.
        certGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(toSignWith.getPublic()));

        // FOAFSSL compatibility.
        final GeneralNames subjectAltNames = new GeneralNames(
                new GeneralName(GeneralName.uniformResourceIdentifier, webId));
        certGenerator.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames);

        return this.generate(toSignWith);

    } finally {
        // Clean up after ourselves so that it is more difficult to try to extract private keys from the heap.
        this.certGenerator.reset();
    }
}

From source file:se.tillvaxtverket.tsltrust.webservice.daemon.ca.CertificationAuthority.java

License:Open Source License

public AaaCertificate createCertificate(AaaCertificate orgCert, BigInteger certSerial,
        AaaCertificate issuerCert, String algorithm, List<Extension> extensions) {

    AaaCertificate cert = null;/* w  ww.  j  av  a  2s  .c o m*/
    // create a new certificate
    try {
        CertRequestModel reqModel = new CertRequestModel();
        reqModel.setIssuerDN(issuerCert.getSubject());
        reqModel.setPublicKey(orgCert.getCert().getPublicKey());
        reqModel.setSerialNumber(certSerial);
        reqModel.setSubjectDN(orgCert.getSubject());
        reqModel.setNotBefore(orgCert.getNotBefore());
        if (issuerCert.getNotAfter().after(orgCert.getNotAfter())) {
            reqModel.setNotAfter(orgCert.getNotAfter());
        } else {
            reqModel.setNotAfter(issuerCert.getNotAfter());
        }

        // Add AKI
        X509ExtensionUtils extUtil = CertUtils.getX509ExtensionUtils();
        AuthorityKeyIdentifier aki = extUtil.createAuthorityKeyIdentifier(issuerCert);
        extensions.add(new Extension(Extension.authorityKeyIdentifier, false, aki.getEncoded("DER")));

        DistributionPoint dp = new DistributionPoint(
                new DistributionPointName(
                        new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, crlDpUrl))),
                null, null);
        CRLDistPoint cdp = new CRLDistPoint(new DistributionPoint[] { dp });
        extensions.add(new Extension(Extension.cRLDistributionPoints, false, cdp.getEncoded("DER")));

        reqModel.setExtensionList(extensions);
        reqModel.setSigner(
                new JcaContentSignerBuilder(algorithm).build((PrivateKey) key_store.getKey(ROOT, KS_PASSWORD)));

        cert = new AaaCertificate(reqModel);
    } catch (Exception ex) {
        cert = null;
        LOG.warning("Error creating the certificate: " + ex.getMessage());
    }

    return cert;
}

From source file:se.tillvaxtverket.tsltrust.webservice.daemon.ca.CertificationAuthority.java

License:Open Source License

public X509CRLHolder revokeCertificates() {
    long currentTime = System.currentTimeMillis();
    long nextUpdateTime = currentTime + crlValPeriod;
    List<DbCert> certList = CaSQLiteUtil.getCertificates(caDir, true);

    DbCAParam cp = CaSQLiteUtil.getParameter(caDir, CRL_SERIAL_KEY);
    if (cp == null) {
        return null;
    }/*w  w  w. j  a  va  2  s.c o  m*/
    long nextCrlSerial = cp.getIntValue();

    try {

        AaaCRL crl = new AaaCRL(new Date(currentTime), new Date(nextUpdateTime), caRoot,
                (PrivateKey) key_store.getKey(ROOT, KS_PASSWORD), CertFactory.SHA256WITHRSA, crlFile);

        List<Extension> extList = new ArrayList<Extension>();
        // Add AKI
        X509ExtensionUtils extu = CertUtils.getX509ExtensionUtils();
        AuthorityKeyIdentifier aki = extu.createAuthorityKeyIdentifier(caRoot);
        extList.add(new Extension(Extension.authorityKeyIdentifier, false, aki.getEncoded("DER")));

        // CRLNumber to be adjusted to an incremental number
        CRLNumber crlNumber = new CRLNumber(BigInteger.valueOf(nextCrlSerial));
        extList.add(new Extension(Extension.cRLNumber, false, crlNumber.getEncoded("DER")));

        GeneralNames distributionPointName = new GeneralNames(
                new GeneralName(GeneralName.uniformResourceIdentifier, crlDpUrl));
        DistributionPointName dpn = new DistributionPointName(distributionPointName);
        IssuingDistributionPoint idp = new IssuingDistributionPoint(dpn, false, false);
        extList.add(new Extension(Extension.issuingDistributionPoint, true, idp.getEncoded("DER")));

        // IssuingDistributionPoint
        List<CRLEntryData> crlEdList = new ArrayList<>();

        certList.forEach((dbCert) -> {
            Date revTime = new Date();
            BigInteger serialNumber = dbCert.getCertificate().getSerialNumber();
            crlEdList.add(new CRLEntryData(serialNumber, new Date(dbCert.getRevDate()),
                    CRLReason.privilegeWithdrawn));
        });

        crl.updateCrl(new Date(currentTime), new Date(nextUpdateTime), crlEdList, extList);

        logRevocation(certList);

        // receive CRL
        latestCrl = crl.getCrl();
        cp.setIntValue(nextCrlSerial + 1);
        CaSQLiteUtil.storeParameter(cp, caDir);
        // Store CRL
        FileOps.saveByteFile(FileOps.readBinaryFile(crlFile), exportCrlFile);
        return latestCrl;

    } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException
            | CRLException | CertificateException | OperatorCreationException ex) {
        LOG.warning(ex.getMessage());
        return null;
    }
}

From source file:se.tillvaxtverket.tsltrust.webservice.daemon.ca.RootCAFactory.java

License:Open Source License

private static void generateRootCertificate() {

    try {//from w w  w  .  j av  a 2s.c  om
        // Generate root key
        System.out.println("Generating Root RSA key...");
        ca_rsa = generateKeyPair("RSA", CA_KEYLENGTH);
        // Now create the certificates

        //CertRequestModel reqMod = new CertRequestModel();
        Map<SubjectDnType, String> subjNameMap = new HashMap<>();
        subjNameMap.put(SubjectDnType.country, conf.getCaCountry());
        subjNameMap.put(SubjectDnType.orgnaizationName, conf.getCaOrganizationName());
        subjNameMap.put(SubjectDnType.orgnaizationalUnitName, conf.getCaOrgUnitName());

        //            Name rootIssuer;
        //            rootIssuer = new Name();
        //            rootIssuer.addRDN(ObjectID.country, conf.getCaCountry());
        //            rootIssuer.addRDN(ObjectID.organization, conf.getCaOrganizationName());
        //            rootIssuer.addRDN(ObjectID.organizationalUnit, conf.getCaOrgUnitName());
        String modelName = conf.getCaCommonName();
        int idx = modelName.indexOf("####");
        String cName;
        if (idx > -1) {
            cName = modelName.substring(0, idx) + caName + modelName.substring(idx + 4);
        } else {
            cName = caName + " " + modelName;
        }
        subjNameMap.put(SubjectDnType.cn, cName);
        X500Name subjectAndIssuer = CertReqUtils.getDn(subjNameMap);

        //            rootIssuer.addRDN(ObjectID.commonName, cName);
        List<Extension> extList = new ArrayList<>();
        extList.add(
                new Extension(Extension.basicConstraints, false, new BasicConstraints(true).getEncoded("DER")));
        extList.add(new Extension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.digitalSignature)
                        .getEncoded("DER")));
        extList.add(new Extension(Extension.certificatePolicies, false,
                getAnyCertificatePolicies().getEncoded("DER")));

        GeneralName generalName = new GeneralName(GeneralName.uniformResourceIdentifier, caRepSia);
        SubjectInformationAccess sia = new SubjectInformationAccess(SubjectInformationAccess.caRepository,
                generalName);
        extList.add(new Extension(Extension.subjectInfoAccess, false, sia.getEncoded("DER")));

        //
        // create self signed CA cert
        //
        AaaCertificate caRoot = createRootCertificate(subjectAndIssuer, ca_rsa.getPublic(), ca_rsa.getPrivate(),
                CertFactory.SHA256WITHRSA, extList);
        // set the CA cert as trusted root
        X509Certificate[] chain = new X509Certificate[] { caRoot.getCert() };
        addToKeyStore(ca_rsa, chain, ROOT);
        //System.out.println(caRoot.toString());
        //rootIssuer.removeRDN(ObjectID.commonName);

    } catch (Exception ex) {
        LOG.warning(ex.getMessage());
    }
}

From source file:test.be.fedict.eid.applet.PkiTestUtils.java

License:Open Source License

static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, DateTime notBefore,
        DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag,
        int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage)
        throws IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException,
        SignatureException, CertificateException {
    String signatureAlgorithm = "SHA1withRSA";
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();/*ww w.j  a v  a2s.  c  om*/
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm(signatureAlgorithm);
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());
    X509Principal issuerDN;
    if (null != issuerCertificate) {
        issuerDN = new X509Principal(issuerCertificate.getSubjectX500Principal().toString());
    } else {
        issuerDN = new X509Principal(subjectDn);
    }
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom()));

    certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(subjectPublicKey));
    PublicKey issuerPublicKey;
    issuerPublicKey = subjectPublicKey;
    certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerPublicKey));

    if (caFlag) {
        if (-1 == pathLength) {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, false,
                    new BasicConstraints(true));
        } else {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, false,
                    new BasicConstraints(pathLength));
        }
    }

    if (null != crlUri) {
        GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(crlUri));
        GeneralNames gns = new GeneralNames(new DERSequence(gn));
        DistributionPointName dpn = new DistributionPointName(0, gns);
        DistributionPoint distp = new DistributionPoint(dpn, null, null);
        certificateGenerator.addExtension(X509Extensions.CRLDistributionPoints, false, new DERSequence(distp));
    }

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certificateGenerator.addExtension(X509Extensions.AuthorityInfoAccess.getId(), false,
                authorityInformationAccess);
    }

    if (null != keyUsage) {
        certificateGenerator.addExtension(X509Extensions.KeyUsage, true, keyUsage);
    }

    X509Certificate certificate;
    certificate = certificateGenerator.generate(issuerPrivateKey);

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificate.getEncoded()));
    return certificate;
}

From source file:test.integ.be.fedict.trust.util.TestUtils.java

License:Open Source License

public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn,
        PrivateKey issuerPrivateKey, X509Certificate issuerCert, DateTime notBefore, DateTime notAfter,
        String signatureAlgorithm, boolean includeAuthorityKeyIdentifier, boolean caCert,
        boolean timeStampingPurpose, String ocspUri, String crlUri, KeyUsage keyUsage, BigInteger serialNumber)
        throws IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException,
        SignatureException, CertificateException {

    String finalSignatureAlgorithm = signatureAlgorithm;
    if (null == signatureAlgorithm) {
        finalSignatureAlgorithm = "SHA512WithRSAEncryption";
    }/*  ww w .  j  av  a 2s .com*/
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm(finalSignatureAlgorithm);
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());
    X509Principal issuerDN;
    if (null != issuerCert) {
        issuerDN = new X509Principal(issuerCert.getSubjectX500Principal().getName());
    } else {
        issuerDN = new X509Principal(subjectDn);
    }
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(serialNumber);

    certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(subjectPublicKey));
    PublicKey issuerPublicKey;
    if (null != issuerCert) {
        issuerPublicKey = issuerCert.getPublicKey();
    } else {
        issuerPublicKey = subjectPublicKey;
    }
    if (includeAuthorityKeyIdentifier) {
        certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                createAuthorityKeyId(issuerPublicKey));
    }

    certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(caCert));

    if (timeStampingPurpose) {
        certificateGenerator.addExtension(X509Extensions.ExtendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));
    }

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certificateGenerator.addExtension(X509Extensions.AuthorityInfoAccess.getId(), false,
                authorityInformationAccess);
    }

    if (null != crlUri) {
        GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(crlUri));
        GeneralNames gns = new GeneralNames(gn);
        DistributionPointName dpn = new DistributionPointName(0, gns);
        DistributionPoint distp = new DistributionPoint(dpn, null, null);
        certificateGenerator.addExtension(X509Extensions.CRLDistributionPoints, false, new DERSequence(distp));
    }

    if (null != keyUsage) {
        certificateGenerator.addExtension(X509Extensions.KeyUsage, true, keyUsage);
    }

    return certificateGenerator.generate(issuerPrivateKey);

    // /*
    // * Make sure the default certificate provider is active.
    // */
    // CertificateFactory certificateFactory = CertificateFactory
    // .getInstance("X.509");
    // certificate = (X509Certificate) certificateFactory
    // .generateCertificate(new ByteArrayInputStream(certificate
    // .getEncoded()));
    //
    // return certificate;
}