Example usage for java.security.cert X509Certificate getSubjectX500Principal

List of usage examples for java.security.cert X509Certificate getSubjectX500Principal

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSubjectX500Principal.

Prototype

public X500Principal getSubjectX500Principal() 

Source Link

Document

Returns the subject (subject distinguished name) value from the certificate as an X500Principal .

Usage

From source file:pl.psnc.synat.wrdz.ru.registries.RemoteRegistryManagerBean.java

@Override
public RemoteRegistry updateRemoteRegistry(RemoteRegistry modified, String certificate)
        throws EntryModificationException {
    RemoteRegistryFilterFactory filterFactory = remoteRegistryDao.createQueryModifier().getQueryFilterFactory();

    QueryFilter<RemoteRegistry> filter = filterFactory.not(filterFactory.byId(modified.getId()));
    filter = filterFactory.and(filter, filterFactory.byLocationUrl(modified.getLocationUrl()));
    List<RemoteRegistry> list = remoteRegistryDao.findBy(filter, false);
    if (list != null && list.size() > 0) {
        throw new EntryModificationException("Registry with given location already extists, try to modify it.");
    }//from ww  w.  j a  v  a 2 s.  c o m

    X509Certificate x509Certificate = loadCertificate(certificate);
    CertificateInformation information = CertificateInformation
            .parseNameString(x509Certificate.getSubjectX500Principal().getName());

    String username = information.getDisplayName().replaceAll(" ", "");

    RemoteRegistry registry = remoteRegistryDao.findById(modified.getId());
    if (registry == null) {
        throw new EntryModificationException("Specified entry not found in the database.");
    }

    if (!username.equals(registry.getUsername())) {
        userManager.deleteSystemUser(registry.getUsername());
        userManager.createSystemUser(username, certificate, information.getDisplayName(),
                information.getDisplayName());
    } else {
        userManager.updateSystemUser(username, certificate);
    }

    registry.setName(modified.getName());
    registry.setLocationUrl(modified.getLocationUrl());
    registry.setDescription(modified.getDescription());
    registry.setHarvested(modified.isHarvested());
    registry.setReadEnabled(modified.isReadEnabled());
    registry.setLatestHarvestDate(null);
    registry.setUsername(username);

    return registry;
}

From source file:be.fedict.trust.service.dao.bean.CertificateAuthorityDAOBean.java

public CertificateAuthorityEntity findCertificateAuthority(X509Certificate certificate) {
    BigInteger serialNumber = certificate.getSerialNumber();
    String key = new String();
    key += certificate.getSubjectX500Principal().toString() + "|" + serialNumber.toString();
    LOG.debug("find (2) CA: " + key);

    return this.entityManager.find(CertificateAuthorityEntity.class,
            //certificate.getSubjectX500Principal().toString());
            key);// w ww .j  ava  2s . c  om
}

From source file:net.sf.jsignpdf.crl.CRLInfo.java

/**
 * Returns (initialized, but maybe empty) set of URLs of CRLs for given
 * certificate.//from   w  w w  .j av  a2s .c o  m
 * 
 * @param aCert
 *          X509 certificate.
 * @return
 */
private Set<String> getCrlUrls(final X509Certificate aCert) {
    final Set<String> tmpResult = new HashSet<String>();
    LOGGER.info(RES.get("console.crlinfo.retrieveCrlUrl", aCert.getSubjectX500Principal().getName()));
    final byte[] crlDPExtension = aCert.getExtensionValue(X509Extension.cRLDistributionPoints.getId());
    if (crlDPExtension != null) {
        CRLDistPoint crlDistPoints = null;
        try {
            crlDistPoints = CRLDistPoint.getInstance(X509ExtensionUtil.fromExtensionValue(crlDPExtension));
        } catch (IOException e) {
            LOGGER.warn("", e);
        }
        if (crlDistPoints != null) {
            final DistributionPoint[] distPoints = crlDistPoints.getDistributionPoints();
            distPoint: for (DistributionPoint dp : distPoints) {
                final DistributionPointName dpName = dp.getDistributionPoint();
                final GeneralNames generalNames = (GeneralNames) dpName.getName();
                if (generalNames != null) {
                    final GeneralName[] generalNameArr = generalNames.getNames();
                    if (generalNameArr != null) {
                        for (final GeneralName generalName : generalNameArr) {
                            if (generalName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                                final DERString derString = (DERString) generalName.getName();
                                final String uri = derString.getString();
                                if (uri != null && uri.startsWith("http")) {
                                    // ||uri.startsWith("ftp")
                                    LOGGER.info(RES.get("console.crlinfo.foundCrlUri", uri));
                                    tmpResult.add(uri);
                                    continue distPoint;
                                }
                            }
                        }
                    }
                    LOGGER.info(RES.get("console.crlinfo.noUrlInDistPoint"));
                }
            }
        }
    } else {
        LOGGER.info(RES.get("console.crlinfo.distPointNotSupported"));
    }
    return tmpResult;
}

From source file:net.solarnetwork.pki.bc.test.BCCertificateServiceTest.java

@Test
public void createCACertificate() throws Exception {
    X509Certificate cert = service.generateCertificationAuthorityCertificate(TEST_CA_DN, publicKey, privateKey);
    assertEquals("Is a CA", Integer.MAX_VALUE, cert.getBasicConstraints()); // should be a CA
    assertEquals("Self signed", cert.getIssuerX500Principal(), cert.getSubjectX500Principal());
}

From source file:com.archivas.clienttools.arcutils.utils.net.SSLCertChain.java

public Map<String, String> getIssuedToDNInfo() {
    X509Certificate cert = getCertificateList().get(0);
    return getDNInfo(cert.getSubjectX500Principal());
}

From source file:net.solarnetwork.pki.bc.test.BCCertificateServiceTest.java

@Test
public void signCertificate() throws Exception {
    X509Certificate cert = service.generateCertificate(TEST_DN, publicKey, privateKey);
    String csr = service.generatePKCS10CertificateRequestString(cert, privateKey);

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048, new SecureRandom());
    KeyPair caKeypair = keyGen.generateKeyPair();
    X509Certificate caCert = service.generateCertificationAuthorityCertificate(TEST_CA_DN,
            caKeypair.getPublic(), caKeypair.getPrivate());

    X509Certificate signed = service.signCertificate(csr, caCert, caKeypair.getPrivate());
    assertEquals("Issuer", caCert.getSubjectX500Principal(), signed.getIssuerX500Principal());
    assertEquals("Subject", cert.getSubjectX500Principal(), signed.getSubjectX500Principal());
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

/**
 * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 *
 * @param dn the distinguished name to use
 * @param publicKey the public key to issue the certificate to
 * @param extensions extensions extracted from the CSR
 * @param issuer the issuer's certificate
 * @param issuerKeyPair the issuer's keypair
 * @param signingAlgorithm the signing algorithm to use
 * @param days the number of days it should be valid for
 * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 * @throws CertificateException if there is an error issuing the certificate
 *///from   w w w . j  a v  a  2s  . co  m
public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions,
        X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days)
        throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())),
                getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);

        certBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey));

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic()));
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                        | KeyUsage.keyAgreement | KeyUsage.nonRepudiation));

        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));

        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(
                new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));

        // (3) subjectAlternativeName
        if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) {
            certBuilder.addExtension(Extension.subjectAlternativeName, false,
                    extensions.getExtensionParsedValue(Extension.subjectAlternativeName));
        }

        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}

From source file:com.zotoh.crypto.CryptoUte.java

private static SMIMESignedGenerator makeSignerGentor(PrivateKey key, Certificate[] certs, SigningAlgo algo)
        throws CertStoreException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        GeneralSecurityException, CertificateEncodingException {

    SMIMESignedGenerator gen = new SMIMESignedGenerator("base64");
    List<Certificate> lst = asList(true, certs);

    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
    SMIMECapabilityVector caps = new SMIMECapabilityVector();

    caps.addCapability(SMIMECapability.dES_EDE3_CBC);
    caps.addCapability(SMIMECapability.rC2_CBC, 128);
    caps.addCapability(SMIMECapability.dES_CBC);

    signedAttrs.add(new SMIMECapabilitiesAttribute(caps));

    X509Certificate x0 = (X509Certificate) certs[0];
    X509Certificate issuer = x0;
    X500Principal issuerDN;//  w  w w .ja  va2  s  . c  om

    if (certs.length > 1) {
        issuer = (X509Certificate) certs[1];
    }

    issuerDN = issuer.getSubjectX500Principal();
    x0 = (X509Certificate) certs[0];

    //
    // add an encryption key preference for encrypted responses -
    // normally this would be different from the signing certificate...
    //

    IssuerAndSerialNumber issAndSer = new IssuerAndSerialNumber(X500Name.getInstance(issuerDN.getEncoded()),
            x0.getSerialNumber());
    Provider prov = Crypto.getInstance().getProvider();

    signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(issAndSer));

    try {
        JcaSignerInfoGeneratorBuilder bdr = new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider(prov).build());
        bdr.setDirectSignature(true);

        ContentSigner cs = new JcaContentSignerBuilder(algo.toString()).setProvider(prov).build(key);

        bdr.setSignedAttributeGenerator(
                new DefaultSignedAttributeTableGenerator(new AttributeTable(signedAttrs)));

        gen.addSignerInfoGenerator(bdr.build(cs, x0));
        gen.addCertificates(new JcaCertStore(lst));

        return gen;
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:fi.laverca.Pkcs7.java

/**
 * Convenience method. Equivalent to calling getSignerCert and
 * then parsing out the CN from the certificate's Subject field.
 * @return Signer CN or null if there's a problem.
 *//*from  w w w . j av  a 2 s .c om*/
public String getSignerCn() {
    try {
        X509Certificate signerCert = this.getSignerCert();
        String dn = signerCert.getSubjectX500Principal().getName();

        String cn = null;
        try {
            LdapName ldapDn = new LdapName(dn);
            List<Rdn> rdns = ldapDn.getRdns();
            for (Rdn r : rdns) {
                if ("CN".equals(r.getType())) {
                    cn = r.getValue().toString();
                }
            }
        } catch (InvalidNameException e) {
            log.warn("Invalid name", e);
        }

        return cn;
    } catch (Throwable t) {
        log.error("Failed to get signer CN: " + t.getMessage());
        return null;
    }
}

From source file:be.fedict.trust.service.bean.CertificateAuthorityLookupBean.java

private void refreshLookupMap() throws CertificateEncodingException, NoSuchAlgorithmException {
    LOG.debug("refreshing lookup map");
    List<CertificateAuthorityEntity> activeCertificateAuthorities = this.certificateAuthorityDAO
            .listActiveCertificateAuthorities();
    Map<String, String> freshLookupMap = new HashMap<String, String>();
    for (CertificateAuthorityEntity certificateAuthority : activeCertificateAuthorities) {
        X509Certificate caCert = certificateAuthority.getCertificate();
        X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(caCert);
        byte[] issuerNameHash = getHash(issuerName.getEncoded());
        String caNameHashKey = Hex.encodeHexString(issuerNameHash);
        String caName = caCert.getSubjectX500Principal().toString();
        freshLookupMap.put(caNameHashKey, caName);
        LOG.debug("lookup entry: " + caNameHashKey + " = " + caName);

    }//from  www .j a va  2 s .c  o  m
    this.lookupMap = freshLookupMap; // concurrency is no problem here
}