Java Code Examples for java.security.cert.X509Certificate#getSerialNumber()

The following examples show how to use java.security.cert.X509Certificate#getSerialNumber() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RequestInfoController.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private void setCerts(HttpServletRequest httpServletRequest, RequestInfo requestInfo) throws CertificateEncodingException {
    X509Certificate[] certs = (X509Certificate[]) httpServletRequest.getAttribute("javax.servlet.request.X509Certificate");
    if (certs == null) return;

    requestInfo.signed = certs.length > 0;
    requestInfo.certs = new Certificate[certs.length];
    for (int i = 0; i < certs.length; i++) {
        final X509Certificate cert = certs[i];
        final Certificate certDto = new Certificate(
            cert.getSerialNumber(),
            Base64.getEncoder().encodeToString(cert.getPublicKey().getEncoded()),
            Base64.getEncoder().encodeToString(cert.getEncoded())
        );
        requestInfo.certs[i] = certDto;
    }
}
 
Example 2
Source File: PKCS7.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the X.509 certificate listed in this PKCS7 block
 * which has a matching serial number and Issuer name, or
 * null if one is not found.
 *
 * @param serial the serial number of the certificate to retrieve.
 * @param issuerName the Distinguished Name of the Issuer.
 */
public X509Certificate getCertificate(BigInteger serial, X500Name issuerName) {
    if (certificates != null) {
        if (certIssuerNames == null)
            populateCertIssuerNames();
        for (int i = 0; i < certificates.length; i++) {
            X509Certificate cert = certificates[i];
            BigInteger thisSerial = cert.getSerialNumber();
            if (serial.equals(thisSerial)
                && issuerName.equals(certIssuerNames[i]))
            {
                return cert;
            }
        }
    }
    return null;
}
 
Example 3
Source File: PublicKeySecurityHandler.java    From sambox with Apache License 2.0 6 votes vote down vote up
private void appendCertInfo(StringBuilder extraInfo, KeyTransRecipientId ktRid,
        X509Certificate certificate, X509CertificateHolder materialCert)
{
    BigInteger ridSerialNumber = ktRid.getSerialNumber();
    if (ridSerialNumber != null)
    {
        String certSerial = "unknown";
        BigInteger certSerialNumber = certificate.getSerialNumber();
        if (certSerialNumber != null)
        {
            certSerial = certSerialNumber.toString(16);
        }
        extraInfo.append("serial-#: rid ");
        extraInfo.append(ridSerialNumber.toString(16));
        extraInfo.append(" vs. cert ");
        extraInfo.append(certSerial);
        extraInfo.append(" issuer: rid \'");
        extraInfo.append(ktRid.getIssuer());
        extraInfo.append("\' vs. cert \'");
        extraInfo.append(materialCert == null ? "null" : materialCert.getIssuer());
        extraInfo.append("\' ");
    }
}
 
Example 4
Source File: BlacklistingTrustManager.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
    throws CertificateException
{
  trustManager.checkServerTrusted(chain, authType);

  for (X509Certificate certificate : chain) {
    for (Pair<String, BigInteger> blacklistedSerial : BLACKLIST) {
      if (certificate.getIssuerDN().getName().equals(blacklistedSerial.first()) &&
          certificate.getSerialNumber().equals(blacklistedSerial.second()))
      {
        throw new CertificateException("Blacklisted Serial: " + certificate.getSerialNumber());
      }
    }
  }

}
 
Example 5
Source File: AttributeCertificateHolder.java    From ripple-lib-java with ISC License 6 votes vote down vote up
public AttributeCertificateHolder(X509Certificate cert)
    throws CertificateParsingException
{
    X509Principal name;

    try
    {
        name = PrincipalUtil.getIssuerX509Principal(cert);
    }
    catch (Exception e)
    {
        throw new CertificateParsingException(e.getMessage());
    }

    holder = new Holder(new IssuerSerial(generateGeneralNames(name),
        new ASN1Integer(cert.getSerialNumber())));
}
 
Example 6
Source File: PKCS7.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the X.509 certificate listed in this PKCS7 block
 * which has a matching serial number and Issuer name, or
 * null if one is not found.
 *
 * @param serial the serial number of the certificate to retrieve.
 * @param issuerName the Distinguished Name of the Issuer.
 */
public X509Certificate getCertificate(BigInteger serial, X500Name issuerName) {
    if (certificates != null) {
        if (certIssuerNames == null)
            populateCertIssuerNames();
        for (int i = 0; i < certificates.length; i++) {
            X509Certificate cert = certificates[i];
            BigInteger thisSerial = cert.getSerialNumber();
            if (serial.equals(thisSerial)
                && issuerName.equals(certIssuerNames[i]))
            {
                return cert;
            }
        }
    }
    return null;
}
 
Example 7
Source File: PKCS7.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the X.509 certificate listed in this PKCS7 block
 * which has a matching serial number and Issuer name, or
 * null if one is not found.
 *
 * @param serial the serial number of the certificate to retrieve.
 * @param issuerName the Distinguished Name of the Issuer.
 */
public X509Certificate getCertificate(BigInteger serial, X500Name issuerName) {
    if (certificates != null) {
        if (certIssuerNames == null)
            populateCertIssuerNames();
        for (int i = 0; i < certificates.length; i++) {
            X509Certificate cert = certificates[i];
            BigInteger thisSerial = cert.getSerialNumber();
            if (serial.equals(thisSerial)
                && issuerName.equals(certIssuerNames[i]))
            {
                return cert;
            }
        }
    }
    return null;
}
 
Example 8
Source File: OcspRequestBuilder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * ATTENTION: The returned {@link OCSPReq} is not re-usable/cacheable! It contains a one-time nonce
 * and CA's will (should) reject subsequent requests that have the same nonce value.
 */
public OCSPReq build() throws OCSPException, IOException, CertificateEncodingException {
    SecureRandom generator = checkNotNull(this.generator, "generator");
    DigestCalculator calculator = checkNotNull(this.calculator, "calculator");
    X509Certificate certificate = checkNotNull(this.certificate, "certificate");
    X509Certificate issuer = checkNotNull(this.issuer, "issuer");

    BigInteger serial = certificate.getSerialNumber();

    CertificateID certId = new CertificateID(calculator,
            new X509CertificateHolder(issuer.getEncoded()), serial);

    OCSPReqBuilder builder = new OCSPReqBuilder();
    builder.addRequest(certId);

    byte[] nonce = new byte[8];
    generator.nextBytes(nonce);

    Extension[] extensions = new Extension[] {
            new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                    new DEROctetString(nonce)) };

    builder.setRequestExtensions(new Extensions(extensions));

    return builder.build();
}
 
Example 9
Source File: NonStandardNames.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example 10
Source File: NonStandardNames.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example 11
Source File: XMLX509IssuerSerial.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor XMLX509IssuerSerial
 *
 * @param doc
 * @param x509certificate
 */
public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) {
    this(
        doc,
        x509certificate.getIssuerX500Principal().getName(),
        x509certificate.getSerialNumber()
    );
}
 
Example 12
Source File: XMLX509IssuerSerial.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor XMLX509IssuerSerial
 *
 * @param doc
 * @param x509certificate
 */
public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) {
    this(
        doc,
        x509certificate.getIssuerX500Principal().getName(),
        x509certificate.getSerialNumber()
    );
}
 
Example 13
Source File: XMLX509IssuerSerial.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor XMLX509IssuerSerial
 *
 * @param doc
 * @param x509certificate
 */
public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) {
    this(
        doc,
        x509certificate.getIssuerX500Principal().getName(),
        x509certificate.getSerialNumber()
    );
}
 
Example 14
Source File: NonStandardNames.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example 15
Source File: SSLSocketFactoryFactory.java    From PADListener with GNU General Public License v2.0 5 votes vote down vote up
private void initSerials() throws GeneralSecurityException {
    Enumeration<String> e = keystoreCert.aliases();
    while (e.hasMoreElements()) {
        String alias = (String) e.nextElement();
        X509Certificate cert = (X509Certificate) keystoreCert
                .getCertificate(alias);
        BigInteger serial = cert.getSerialNumber();
        serials.add(serial);
    }
}
 
Example 16
Source File: NonStandardNames.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example 17
Source File: NonStandardNames.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example 18
Source File: X509CRLImpl.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Construct an X509IssuerSerial from an X509Certificate.
 */
X509IssuerSerial(X509Certificate cert) {
    this(cert.getIssuerX500Principal(), cert.getSerialNumber());
}
 
Example 19
Source File: OCSPCertificateVerifier.java    From oxAuth with MIT License 4 votes vote down vote up
@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) {
	X509Certificate issuer = issuers.get(0);
	ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.OCSP, CertificateValidity.UNKNOWN);

	try {
		Principal subjectX500Principal = certificate.getSubjectX500Principal();

		String ocspUrl = getOCSPUrl(certificate);
		if (ocspUrl == null) {
			log.error("OCSP URL for '" + subjectX500Principal + "' is empty");
			return status;
		}

		log.debug("OCSP URL for '" + subjectX500Principal + "' is '" + ocspUrl + "'");

		DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1);
		CertificateID certificateId = new CertificateID(digestCalculator, new JcaX509CertificateHolder(certificate), certificate.getSerialNumber());

		// Generate OCSP request
		OCSPReq ocspReq = generateOCSPRequest(certificateId);

		// Get OCSP response from server
		OCSPResp ocspResp = requestOCSPResponse(ocspUrl, ocspReq);
		if (ocspResp.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
			log.error("OCSP response is invalid!");
			status.setValidity(CertificateValidity.INVALID);
			return status;
		}

		boolean foundResponse = false;
		BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();
		SingleResp[] singleResps = basicOCSPResp.getResponses();
		for (SingleResp singleResp : singleResps) {
			CertificateID responseCertificateId = singleResp.getCertID();
			if (!certificateId.equals(responseCertificateId)) {
				continue;
			}

			foundResponse = true;

			log.debug("OCSP validationDate: " + validationDate);
			log.debug("OCSP thisUpdate: " + singleResp.getThisUpdate());
			log.debug("OCSP nextUpdate: " + singleResp.getNextUpdate());

			status.setRevocationObjectIssuingTime(basicOCSPResp.getProducedAt());

			Object certStatus = singleResp.getCertStatus();
			if (certStatus == CertificateStatus.GOOD) {
				log.debug("OCSP status is valid for '" + certificate.getSubjectX500Principal() + "'");
				status.setValidity(CertificateValidity.VALID);
			} else {
				if (singleResp.getCertStatus() instanceof RevokedStatus) {
					log.warn("OCSP status is revoked for: " + subjectX500Principal);
					if (validationDate.before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) {
						log.warn("OCSP revocation time after the validation date, the certificate '" + subjectX500Principal + "' was valid at " + validationDate);
						status.setValidity(CertificateValidity.VALID);
					} else {
						Date revocationDate = ((RevokedStatus) singleResp.getCertStatus()).getRevocationTime();
						log.info("OCSP for certificate '" + subjectX500Principal + "' is revoked since " + revocationDate);
						status.setRevocationDate(revocationDate);
						status.setRevocationObjectIssuingTime(singleResp.getThisUpdate());
						status.setValidity(CertificateValidity.REVOKED);
					}
				}
			}
		}

		if (!foundResponse) {
			log.error("There is no matching OCSP response entries");
		}
	} catch (Exception ex) {
		log.error("OCSP exception: ", ex);
	}

	return status;
}
 
Example 20
Source File: DefaultCertificateClient.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
/**
 * Load all certificates from configured location.
 * */
private void loadAllCertificates() {
  // See if certs directory exists in file system.
  Path certPath = securityConfig.getCertificateLocation(component);
  if (Files.exists(certPath) && Files.isDirectory(certPath)) {
    getLogger().info("Loading certificate from location:{}.",
        certPath);
    File[] certFiles = certPath.toFile().listFiles();

    if (certFiles != null) {
      CertificateCodec certificateCodec =
          new CertificateCodec(securityConfig, component);
      long latestCaCertSerailId = -1L;
      for (File file : certFiles) {
        if (file.isFile()) {
          try {
            X509CertificateHolder x509CertificateHolder = certificateCodec
                .readCertificate(certPath, file.getName());
            X509Certificate cert =
                CertificateCodec.getX509Certificate(x509CertificateHolder);
            if (cert != null && cert.getSerialNumber() != null) {
              if (cert.getSerialNumber().toString().equals(certSerialId)) {
                x509Certificate = cert;
              }
              certificateMap.putIfAbsent(cert.getSerialNumber().toString(),
                  cert);
              if (file.getName().startsWith(CA_CERT_PREFIX)) {
                String certFileName = FilenameUtils.getBaseName(
                    file.getName());
                long tmpCaCertSerailId = NumberUtils.toLong(
                    certFileName.substring(CA_CERT_PREFIX_LEN));
                if (tmpCaCertSerailId > latestCaCertSerailId) {
                  latestCaCertSerailId = tmpCaCertSerailId;
                }
              }
              getLogger().info("Added certificate from file:{}.",
                  file.getAbsolutePath());
            } else {
              getLogger().error("Error reading certificate from file:{}",
                  file);
            }
          } catch (java.security.cert.CertificateException | IOException e) {
            getLogger().error("Error reading certificate from file:{}.",
                file.getAbsolutePath(), e);
          }
        }
      }
      if (latestCaCertSerailId != -1) {
        caCertId = Long.toString(latestCaCertSerailId);
      }
    }
  }
}