Example usage for java.security.cert X509Certificate getSerialNumber

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

Introduction

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

Prototype

public abstract BigInteger getSerialNumber();

Source Link

Document

Gets the serialNumber value from the certificate.

Usage

From source file:org.globus.pkcs11.PKCS11Util.java

/**
 * Loads a certificate onto the PKCS11 device and labels it with the specified
 * label/*  w w  w  .j a v  a  2s . c om*/
 */
public static PKCS11Object instantiateUserCert(X509Certificate userCert, String label, byte[] id)
        throws CertificateEncodingException {

    Name issuer = (Name) userCert.getIssuerDN();
    Name subject = (Name) userCert.getSubjectDN();

    byte[] issuerBytes = issuer.getEncoded();
    byte[] subjectBytes = subject.getEncoded();

    if (label == null) {
        label = subject.toString();
    }

    logger.debug("Instantiating user cert with label " + label + " on device");
    //X_509 CERTIFICATE
    int[] certAttributes = { PKCS11Object.CLASS, PKCS11Object.TOKEN, PKCS11Object.LABEL,
            PKCS11Object.CERTIFICATE_TYPE, PKCS11Object.ID, PKCS11Object.SUBJECT, PKCS11Object.ISSUER,
            PKCS11Object.SERIAL_NUMBER, PKCS11Object.VALUE };

    Object[] certAttrValues = { PKCS11Object.CERTIFICATE, PKCS11Object.TRUE, label, PKCS11Object.X_509, id,
            subjectBytes, issuerBytes, userCert.getSerialNumber().toByteArray(), userCert.getEncoded() };

    return session.createObject(certAttributes, certAttrValues);
}

From source file:mitm.common.security.cms.SignerIdentifierImpl.java

public SignerIdentifierImpl(X509Certificate certificate) throws IOException {
    this(certificate.getIssuerX500Principal(), certificate.getSerialNumber(),
            X509CertificateInspector.getSubjectKeyIdentifier(certificate));
}

From source file:com.xwiki.authentication.sts.STSTokenValidator.java

/**
  * validateToken(SignableSAMLObject samlToken)
  * Validates Token from SAMLlObject - returns boolen
  * Validates Token - exitracting sertificate from samlToken.
  * And validates it. Returning true or false according on validation results.
  * @param samlToken SignableSAMLObject/*  w w w  . ja v a2  s  .  c o  m*/
  * @return boolean valid => true, not valid => false
  */
private static boolean validateToken(SignableSAMLObject samlToken)
        throws SecurityException, ValidationException, ConfigurationException, UnmarshallingException,
        CertificateException, KeyException {

    // Validate XML structure
    samlToken.validate(true);

    Signature signature = samlToken.getSignature();
    X509Certificate certificate = certFromToken(samlToken);

    // Certificate data
    log.debug("certificate issuerDN: " + certificate.getIssuerDN());
    log.debug("certificate issuerUniqueID: " + certificate.getIssuerUniqueID());
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal());
    log.debug("certificate notBefore: " + certificate.getNotBefore());
    log.debug("certificate notAfter: " + certificate.getNotAfter());
    log.debug("certificate serialNumber: " + certificate.getSerialNumber());
    log.debug("certificate sigAlgName: " + certificate.getSigAlgName());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate signature: " + new String(certificate.getSignature()));
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal().toString());
    log.debug("certificate publicKey: " + certificate.getPublicKey());
    log.debug("certificate subjectDN: " + certificate.getSubjectDN());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate version: " + certificate.getVersion());

    BasicX509Credential cred = new BasicX509Credential();
    cred.setEntityCertificate(certificate);

    // Credential data
    cred.setEntityId(entityId);
    log.debug("cred entityId: " + cred.getEntityId());
    log.debug("cred usageType: " + cred.getUsageType());
    log.debug("cred credentalContextSet: " + cred.getCredentalContextSet());
    log.debug("cred hashCode: " + cred.hashCode());
    log.debug("cred privateKey: " + cred.getPrivateKey());
    log.debug("cred publicKey: " + cred.getPublicKey());
    log.debug("cred secretKey: " + cred.getSecretKey());
    log.debug("cred entityCertificateChain: " + cred.getEntityCertificateChain());

    ArrayList<Credential> trustedCredentials = new ArrayList<Credential>();
    trustedCredentials.add(cred);

    CollectionCredentialResolver credResolver = new CollectionCredentialResolver(trustedCredentials);
    KeyInfoCredentialResolver kiResolver = SecurityTestHelper.buildBasicInlineKeyInfoResolver();
    ExplicitKeySignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine(credResolver, kiResolver);

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(entityId));

    Base64 decoder = new Base64();
    // In trace mode write certificate in the file
    if (log.isTraceEnabled()) {
        String certEncoded = new String(decoder.encode(certificate.getEncoded()));
        try {
            FileUtils.writeStringToFile(new File("/tmp/Certificate.cer"),
                    "-----BEGIN CERTIFICATE-----\n" + certEncoded + "\n-----END CERTIFICATE-----");
            log.trace("Certificate file was saved in: /tmp/Certificate.cer");
        } catch (IOException e1) {
            log.error(e1);
        }
    }
    return engine.validate(signature, criteriaSet);
}

From source file:org.cesecore.certificates.ocsp.CanLogCache.java

/**
 * Checks if a certificate is valid Does also print a WARN if the certificate is about to expire.
 * /*w  w  w  .  j av  a  2 s  .c o  m*/
 * @param signerCert the certificate to be tested
 * @return true if the certificate is valid
 */
private static boolean isCertificateValid(X509Certificate signerCert) {
    try {
        signerCert.checkValidity();
    } catch (CertificateExpiredException e) {
        log.error(intres.getLocalizedMessage("ocsp.errorcerthasexpired", signerCert.getSerialNumber(),
                signerCert.getIssuerDN()));
        return false;
    } catch (CertificateNotYetValidException e) {
        log.error(intres.getLocalizedMessage("ocsp.errornotyetvalid", signerCert.getSerialNumber(),
                signerCert.getIssuerDN()));
        return false;
    }
    final long warnBeforeExpirationTime = OcspConfiguration.getWarningBeforeExpirationTime();
    if (warnBeforeExpirationTime < 1) {
        return true;
    }
    final Date warnDate = new Date(new Date().getTime() + warnBeforeExpirationTime);
    try {
        signerCert.checkValidity(warnDate);
    } catch (CertificateExpiredException e) {
        log.warn(intres.getLocalizedMessage("ocsp.warncertwillexpire", signerCert.getSerialNumber(),
                signerCert.getIssuerDN(), signerCert.getNotAfter()));
    } catch (CertificateNotYetValidException e) {
        throw new Error("This should never happen.", e);
    }
    if (!log.isDebugEnabled()) {
        return true;
    }
    log.debug("Time for \"certificate will soon expire\" not yet reached. You will be warned after: "
            + new Date(signerCert.getNotAfter().getTime() - warnBeforeExpirationTime));
    return true;
}

From source file:org.casbah.provider.openssl.OpenSslCAProviderTest.java

@Test
public void testSign() throws CertificateException, IOException, CAProviderException {

    rollbackPreviousTests();/*from  ww w.  ja  va 2  s.c  om*/

    String csr = FileUtils.readFileToString(new File(targetDir, "/client/requests/03.csr"));
    OpenSslCAProvider provider = new OpenSslCAProvider(OPENSSL, new File(targetDir, CAROOT), PASSWORD);
    X509Certificate cert = provider.sign(csr);
    assertNotNull(cert);
    assertEquals(new BigInteger("03"), cert.getSerialNumber());
    System.out.println(cert.getIssuerX500Principal().getName());
}

From source file:org.apache.xml.security.keys.content.x509.XMLX509IssuerSerial.java

/**
 * Constructor XMLX509IssuerSerial//from  ww  w .  j a  v  a2 s. c om
 *
 * @param doc
 * @param x509certificate
 */
public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) {
    this(doc, RFC2253Parser.normalize(x509certificate.getIssuerDN().getName()),
            x509certificate.getSerialNumber());
}

From source file:com.axway.ebxml.KeyInfoWriter.java

/**
 * Builds the X509Data element sub-element of the KeyInfo element
 * @param doc Containing document to create the element for. Cannot be null.
 * @param cert <code>X509Certificate</code> to create the <code>X509Data</code> element for. Cannot be null.
 * @return Populated <code>X509Data</code>
 * @throws XMLSecurityException/* w  w w .j  ava 2  s  .co  m*/
 */
private X509Data buildX509Data(org.w3c.dom.Document doc, X509Certificate cert) throws XMLSecurityException {
    X509Data x509Data;
    x509Data = new X509Data(doc);
    x509Data.addIssuerSerial(cert.getIssuerDN().getName(), cert.getSerialNumber());
    x509Data.addSubjectName(cert);
    x509Data.addCertificate(cert);
    return x509Data;
}

From source file:org.ejbca.core.model.ca.publisher.custpubl2.CertSernoCustomLdapPublisher.java

private String getUidCertSernoDN(Certificate incert, String username, String userDN) {
    // Construct the userDN with the certificate serial number as UID
    X509Certificate xcert = (X509Certificate) incert;
    String certSerNo = xcert.getSerialNumber().toString();
    String snfromuser = CertTools.getPartFromDN(userDN, "UID");
    if (StringUtils.isNotEmpty(snfromuser)) {
        log.info("User '" + username + "' aready has a UID in DN, this will be replaced by Cert Serial No: "
                + snfromuser);//from   w w w. j  a va  2  s.c  o m
        StringUtils.replace(userDN, snfromuser, certSerNo);
    } else {
        if (StringUtils.isEmpty(userDN)) {
            userDN = "UID=" + certSerNo;
        } else {
            userDN += ",UID=" + certSerNo;
        }
    }
    return userDN;
}

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);/*  ww  w  .  ja  v a 2s .c  om*/
}

From source file:org.springframework.security.saml.trust.UntrustedCertificateException.java

@Override
public String getMessage() {
    StringBuilder sb = new StringBuilder(150);
    sb.append(super.getMessage());
    if (x509Certificates != null && x509Certificates.length > 0) {
        sb.append(/*from  w w  w . ja va 2 s  .c om*/
                "\n\nFollow certificates (in PEM format) presented by the peer. Content between being/end certificate (including) can be stored in a file and imported using keytool, e.g. 'keytool -importcert -file cert.cer -alias certAlias -keystore keystore.jks'). Make sure the presented certificates are issued by your trusted CA before adding them to the keystore.\n\n");
        for (X509Certificate cert : x509Certificates) {
            sb.append("Subject: ").append(cert.getSubjectDN()).append("\n");
            sb.append("Serial number: ").append(cert.getSerialNumber()).append("\n");
            appendThumbPrint(cert, sb);
            sb.append("\n");
            appendCertificate(cert, sb);
            sb.append("\n");
        }
    }
    return sb.toString();
}