org.bouncycastle.asn1.x509.CRLReason Java Examples

The following examples show how to use org.bouncycastle.asn1.x509.CRLReason. 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: TestCRLCodec.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteCRLX509() throws IOException,
    OperatorCreationException, CertificateException, CRLException {

  X500Name issuer = x509CertificateHolder.getIssuer();
  Date now = new Date();
  X509v2CRLBuilder builder = new X509v2CRLBuilder(issuer, now);
  builder.addCRLEntry(x509CertificateHolder.getSerialNumber(), now,
                      CRLReason.cACompromise);

  byte[] crlBytes = TMP_CRL_ENTRY.getBytes();
  try (InputStream inStream = new ByteArrayInputStream(crlBytes)) {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509CRL crl = (X509CRL)cf.generateCRL(inStream);

    CRLCodec crlCodec = new CRLCodec(securityConfig);
    crlCodec.writeCRL(crl);

    // verify file generated or not
    File crlFile =
        Paths.get(crlCodec.getLocation().toString(),
                  this.securityConfig.getCrlName()).toFile();

    assertTrue(crlFile.exists());
  }
}
 
Example #2
Source File: TestCRLCodec.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetX509CRLFromCRLHolder() throws IOException,
    OperatorCreationException, CertificateException, CRLException {

  X500Name issuer = x509CertificateHolder.getIssuer();
  Date now = new Date();
  X509v2CRLBuilder builder = new X509v2CRLBuilder(issuer, now);
  builder.addCRLEntry(x509CertificateHolder.getSerialNumber(), now,
                      CRLReason.cACompromise);

  JcaContentSignerBuilder contentSignerBuilder =
      new JcaContentSignerBuilder(securityConfig.getSignatureAlgo());

  contentSignerBuilder.setProvider(securityConfig.getProvider());
  PrivateKey privateKey = keyPair.getPrivate();
  X509CRLHolder cRLHolder =
      builder.build(contentSignerBuilder.build(privateKey));

  CRLCodec crlCodec = new CRLCodec(securityConfig);

  X509CRL crl = crlCodec.getX509CRL(cRLHolder);
  assertNotNull(crl);
}
 
Example #3
Source File: OCSPUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static OCSPRevocationStatus unknownStatus() {
    return new OCSPRevocationStatus() {
        @Override
        public RevocationStatus getRevocationStatus() {
            return RevocationStatus.UNKNOWN;
        }

        @Override
        public Date getRevocationTime() {
            return new Date(System.currentTimeMillis());
        }

        @Override
        public CRLReason getRevocationReason() {
            return CRLReason.lookup(CRLReason.unspecified);
        }
    };
}
 
Example #4
Source File: TestCRLCodec.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetX509CRL() throws IOException,
    OperatorCreationException, CertificateException, CRLException {

  X500Name issuer = x509CertificateHolder.getIssuer();
  Date now = new Date();
  X509v2CRLBuilder builder = new X509v2CRLBuilder(issuer, now);
  builder.addCRLEntry(x509CertificateHolder.getSerialNumber(), now,
                      CRLReason.cACompromise);

  JcaContentSignerBuilder contentSignerBuilder =
      new JcaContentSignerBuilder(securityConfig.getSignatureAlgo());

  contentSignerBuilder.setProvider(securityConfig.getProvider());
  PrivateKey privateKey = keyPair.getPrivate();
  X509CRLHolder cRLHolder =
      builder.build(contentSignerBuilder.build(privateKey));

  CRLCodec crlCodec = new CRLCodec(securityConfig);
  crlCodec.writeCRL(cRLHolder, this.securityConfig.getCrlName(), true);

  X509CRLEntryHolder entryHolder =
      cRLHolder.getRevokedCertificate(BigInteger.ONE);
  assertNotNull(entryHolder);

  String pemEncodedString = crlCodec.getPEMEncodedString(cRLHolder);
  assertNotNull(pemEncodedString);

  // Verify header and footer of PEM encoded String
  String header = "-----BEGIN X509 CRL-----";
  String footer = "-----END X509 CRL-----";
  assertTrue(pemEncodedString.contains(header));
  assertTrue(pemEncodedString.contains(footer));
}
 
Example #5
Source File: RestCaClient.java    From xipki with Apache License 2.0 5 votes vote down vote up
public boolean revokeCert(BigInteger serialNumber, CRLReason reason) throws Exception {
  StringBuilder sb = new StringBuilder(200);
  sb.append(caUrl).append("/revoke-cert?ca-sha1=").append(caCertSha1Fp);
  sb.append("&serial-number=0X").append(serialNumber.toString(16));
  sb.append("&reason=").append(reason.getValue().intValue());
  String url = sb.toString();
  return simpleHttpGet(url);
}
 
Example #6
Source File: CmpCaClient.java    From xipki with Apache License 2.0 5 votes vote down vote up
public boolean revokeCert(BigInteger serialNumber, CRLReason reason) throws Exception {
  ProtectedPKIMessageBuilder builder = new ProtectedPKIMessageBuilder(
      PKIHeader.CMP_2000, requestorSubject, responderSubject);
  builder.setMessageTime(new Date());
  builder.setTransactionID(randomTransactionId());
  builder.setSenderNonce(randomSenderNonce());

  CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
  certTempBuilder.setIssuer(caSubject);
  certTempBuilder.setSerialNumber(new ASN1Integer(serialNumber));

  AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSubjectKeyIdentifier);
  byte[] encodedAki = aki.getEncoded();

  Extension extAki = new Extension(Extension.authorityKeyIdentifier, false, encodedAki);
  Extensions certTempExts = new Extensions(extAki);
  certTempBuilder.setExtensions(certTempExts);

  ASN1Enumerated asn1Reason = new ASN1Enumerated(reason.getValue().intValue());
  Extensions exts = new Extensions(
      new Extension(Extension.reasonCode, true, new DEROctetString(asn1Reason.getEncoded())));
  RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);

  RevReqContent content = new RevReqContent(revDetails);
  builder.setBody(new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content));
  ProtectedPKIMessage request = build(builder);

  PKIMessage response = transmit(request, null);
  return parseRevocationResult(response, serialNumber);
}
 
Example #7
Source File: X509Ca.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static Extension createReasonExtension(int reasonCode) {
  CRLReason crlReason = CRLReason.lookup(reasonCode);
  try {
    return new Extension(Extension.reasonCode, false, crlReason.getEncoded());
  } catch (IOException ex) {
    throw new IllegalArgumentException("error encoding reason: " + ex.getMessage(), ex);
  }
}
 
Example #8
Source File: TestCRLCodec.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Test
public void testWriteCRL() throws IOException, OperatorCreationException {

  X500Name issuer = x509CertificateHolder.getIssuer();
  Date now = new Date();
  X509v2CRLBuilder builder = new X509v2CRLBuilder(issuer, now);
  builder.addCRLEntry(x509CertificateHolder.getSerialNumber(), now,
                      CRLReason.cACompromise);

  JcaContentSignerBuilder contentSignerBuilder =
      new JcaContentSignerBuilder(securityConfig.getSignatureAlgo());

  contentSignerBuilder.setProvider(securityConfig.getProvider());
  PrivateKey privateKey = keyPair.getPrivate();
  X509CRLHolder cRLHolder =
      builder.build(contentSignerBuilder.build(privateKey));

  CRLCodec crlCodec = new CRLCodec(securityConfig);
  crlCodec.writeCRL(cRLHolder, this.securityConfig.getCrlName(), true);

  X509CRLEntryHolder entryHolder =
      cRLHolder.getRevokedCertificate(BigInteger.ONE);
  assertNotNull(entryHolder);

  // verify file generation
  File crlFile =
      Paths.get(crlCodec.getLocation().toString(),
                this.securityConfig.getCrlName()).toFile();
  assertTrue(crlFile.exists());

  try (BufferedReader reader = new BufferedReader(new FileReader(crlFile))){

    // Verify contents of the file
    String header = reader.readLine();
    assertEquals("-----BEGIN X509 CRL-----", header);

    String footer = null;
    String line = null;
    while ((line = reader.readLine()) != null) {
      footer = line;
    }
    assertEquals("-----END X509 CRL-----", footer);
  }
}
 
Example #9
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private String getReasonCodeStringValue(byte[] value) throws IOException {
	// @formatter:off

	/*
	 * ReasonCode ::= { CRLReason }
	 *
	 * CRLReason ::= ASN1Enumerated { unspecified (0), keyCompromise (1),
	 * cACompromise (2), affiliationChanged (3), superseded (4),
	 * cessationOfOperation (5), certificateHold (6), removeFromCRL (8),
	 * privilegeWithdrawn (9), aACompromise (10) }
	 */

	// @formatter:on

	StringBuilder sb = new StringBuilder();

	CRLReason crlReason = CRLReason.getInstance(value);

	long crlReasonLong = crlReason.getValue().longValue();

	if (crlReasonLong == CRLReason.unspecified) {
		sb.append(res.getString("UnspecifiedCrlReason"));
	} else if (crlReasonLong == CRLReason.keyCompromise) {
		sb.append(res.getString("KeyCompromiseCrlReason"));
	} else if (crlReasonLong == CRLReason.cACompromise) {
		sb.append(res.getString("CaCompromiseCrlReason"));
	} else if (crlReasonLong == CRLReason.affiliationChanged) {
		sb.append(res.getString("AffiliationChangedCrlReason"));
	} else if (crlReasonLong == CRLReason.superseded) {
		sb.append(res.getString("SupersededCrlReason"));
	} else if (crlReasonLong == CRLReason.cessationOfOperation) {
		sb.append(res.getString("CessationOfOperationCrlReason"));
	} else if (crlReasonLong == CRLReason.certificateHold) {
		sb.append(res.getString("CertificateHoldCrlReason"));
	} else if (crlReasonLong == CRLReason.removeFromCRL) {
		sb.append(res.getString("RemoveFromCrlCrlReason"));
	} else if (crlReasonLong == CRLReason.privilegeWithdrawn) {
		sb.append(res.getString("PrivilegeWithdrawnCrlReason"));
	} else
		// CRLReason.aACompromise
	{
		sb.append(res.getString("AaCompromiseCrlReason"));
	}

	sb.append(NEWLINE);

	return sb.toString();
}
 
Example #10
Source File: TlsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static X509CRLHolder createCRL() throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    SelfSignedX509CertificateAndSigningKey muneraSelfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder()
            .setDn(MUNERASOFT_DN)
            .setKeyAlgorithmName("RSA")
            .setSignatureAlgorithmName("SHA256withRSA")
            .addExtension(false, "BasicConstraints", "CA:true,pathlen:2147483647")
            .build();
    X509Certificate muneraCertificate = muneraSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();

    Calendar calendar = Calendar.getInstance();
    Date currentDate = calendar.getTime();
    calendar.add(Calendar.YEAR, 1);
    Date nextYear = calendar.getTime();
    calendar.add(Calendar.YEAR, -1);
    calendar.add(Calendar.SECOND, -30);
    Date revokeDate = calendar.getTime();

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(
            new X500Name(MUNERASOFT_DN.getName()),
            currentDate
    );
    crlBuilder.addExtension(
            Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(muneraCertificate.getPublicKey())
    );
    crlBuilder.addExtension(
            Extension.cRLNumber, false, new CRLNumber(BigInteger.valueOf(4110))
    );
    crlBuilder.addCRLEntry(
            new BigInteger("1005"),
            revokeDate,
            CRLReason.unspecified
    );
    crlBuilder.addCRLEntry(
            new BigInteger("1006"),
            revokeDate,
            CRLReason.unspecified
    );
    return crlBuilder.setNextUpdate(nextYear).build(
            new JcaContentSignerBuilder("SHA256withRSA")
                    .setProvider("BC")
                    .build(muneraSelfSignedX509CertificateAndSigningKey.getSigningKey())
    );
}
 
Example #11
Source File: RestCaClientExample.java    From xipki with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  //System.setProperty("javax.net.debug", "all");
  try {
    RestCaClient client = new RestCaClient(CA_URL, USER, PASSWORD);

    client.init();

    // retrieve CA certificate
    printCert("===== CA Certificate (REST) =====", client.getCaCert());

    // Enroll certificate - RSA
    MyKeypair kp = generateRsaKeypair();
    CertificationRequest csr = genCsr(kp, getSubject());
    X509Certificate cert = client.requestCert(CERT_PROFILE, csr);
    printCert("===== RSA (REST) =====", cert);

    // Enroll certificate - EC
    kp = generateEcKeypair();
    csr = genCsr(kp, getSubject());
    cert = client.requestCert(CERT_PROFILE, csr);
    printCert("===== EC (REST) =====", cert);

    // Enroll certificate - DSA
    kp = generateDsaKeypair();
    csr = genCsr(kp, getSubject());
    cert = client.requestCert(CERT_PROFILE, csr);
    printCert("===== DSA =====", cert);

    BigInteger serialNumber = cert.getSerialNumber();
    // Suspend certificate
    boolean flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.certificateHold));
    if (flag) {
      System.out.println("(REST) suspended certificate");
    } else {
      System.err.println("(REST) suspending certificate failed");
    }

    // Unsuspend certificate
    flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.removeFromCRL));
    if (flag) {
      System.out.println("(REST) unsuspended certificate");
    } else {
      System.err.println("(REST) unsuspending certificate failed");
    }

    // Revoke certificate
    flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.keyCompromise));
    if (flag) {
      System.out.println("(REST) revoked certificate");
    } else {
      System.err.println("(REST) revoking certificate failed");
    }

    client.close();
  } catch (Exception ex) {
    ex.printStackTrace();
    System.exit(-1);
  }
}
 
Example #12
Source File: RestCaClient.java    From xipki with Apache License 2.0 4 votes vote down vote up
public boolean unrevokeCert(BigInteger serialNumber) throws Exception {
  return revokeCert(serialNumber, CRLReason.lookup(CRLReason.removeFromCRL));
}
 
Example #13
Source File: CmpCaClient.java    From xipki with Apache License 2.0 4 votes vote down vote up
public boolean unrevokeCert(BigInteger serialNumber) throws Exception {
  return revokeCert(serialNumber, CRLReason.lookup(CRLReason.removeFromCRL));
}
 
Example #14
Source File: OCSPUtils.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private static OCSPRevocationStatus singleResponseToRevocationStatus(final SingleResp singleResponse) throws CertPathValidatorException {
    final CertificateStatus certStatus = singleResponse.getCertStatus();

    int revocationReason = CRLReason.unspecified;
    Date revocationTime = null;
    RevocationStatus status = RevocationStatus.UNKNOWN;
    if (certStatus == CertificateStatus.GOOD) {
        status = RevocationStatus.GOOD;
    } else if (certStatus instanceof RevokedStatus) {
        RevokedStatus revoked = (RevokedStatus)certStatus;
        revocationTime = revoked.getRevocationTime();
        status = RevocationStatus.REVOKED;
        if (revoked.hasRevocationReason()) {
            revocationReason = revoked.getRevocationReason();
        }
    } else if (certStatus instanceof UnknownStatus) {
        status = RevocationStatus.UNKNOWN;
    } else {
        throw new CertPathValidatorException("Unrecognized revocation status received from OCSP.");
    }

    final RevocationStatus finalStatus = status;
    final Date finalRevocationTime = revocationTime;
    final int finalRevocationReason = revocationReason;
    return new OCSPRevocationStatus() {
        @Override
        public RevocationStatus getRevocationStatus() {
            return finalStatus;
        }

        @Override
        public Date getRevocationTime() {
            return finalRevocationTime;
        }

        @Override
        public CRLReason getRevocationReason() {
            return CRLReason.lookup(finalRevocationReason);
        }
    };
}
 
Example #15
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Get Reason Code (2.5.29.21) extension value as a string.
 *
 * <pre>
 * ReasonCode ::= { CRLReason }
 * CRLReason ::= ENUMERATED {
 *     unspecified             (0),
 *     keyCompromise           (1),
 *     cACompromise            (2),
 *     affiliationChanged      (3),
 *     superseded              (4),
 *     cessationOfOperation    (5),
 *     certificateHold         (6),
 *     removeFromCRL           (8),
 *     privilegeWithdrawn      (9),
 *     aACompromise           (10) }
 * </pre>
 *
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getReasonCodeStringValue(byte[] bValue)
    throws IOException
{
	int iRc = CRLReason.getInstance(ASN1Primitive.fromByteArray(bValue)).getValue().intValue();
	String sRc = getRes("CrlReason." + iRc, "UnrecognisedCrlReasonString");
	return MessageFormat.format(sRc, iRc);
}
 
Example #16
Source File: OCSPUtils.java    From keycloak with Apache License 2.0 votes vote down vote up
CRLReason getRevocationReason();