org.bouncycastle.asn1.x509.Extensions Java Examples

The following examples show how to use org.bouncycastle.asn1.x509.Extensions. 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: CertificateUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #2
Source File: LogSignatureVerifier.java    From certificate-transparency-java with Apache License 2.0 6 votes vote down vote up
private List<Extension> getExtensionsWithoutPoisonAndSCT(
    Extensions extensions, Extension replacementX509authorityKeyIdentifier) {
  ASN1ObjectIdentifier[] extensionsOidsArray = extensions.getExtensionOIDs();
  Iterator<ASN1ObjectIdentifier> extensionsOids = Arrays.asList(extensionsOidsArray).iterator();

  // Order is important, which is why a list is used.
  ArrayList<Extension> outputExtensions = new ArrayList<Extension>();
  while (extensionsOids.hasNext()) {
    ASN1ObjectIdentifier extn = extensionsOids.next();
    String extnId = extn.getId();
    if (extnId.equals(CTConstants.POISON_EXTENSION_OID)) {
      // Do nothing - skip copying this extension
    } else if (extnId.equals(CTConstants.SCT_CERTIFICATE_OID)) {
      // Do nothing - skip copying this extension
    } else if ((extnId.equals(X509_AUTHORITY_KEY_IDENTIFIER))
        && (replacementX509authorityKeyIdentifier != null)) {
      // Use the real issuer's authority key identifier, since it's present.
      outputExtensions.add(replacementX509authorityKeyIdentifier);
    } else {
      // Copy the extension as-is.
      outputExtensions.add(extensions.getExtension(extn));
    }
  }
  return outputExtensions;
}
 
Example #3
Source File: OcspClientBouncyCastle.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generates an OCSP request using BouncyCastle.
 * @param issuerCert	certificate of the issues
 * @param serialNumber	serial number
 * @return	an OCSP request
 * @throws OCSPException
 * @throws IOException
 */
private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException, OperatorException, CertificateEncodingException {
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    
    JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder();
    DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build();
    DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1);
    // Generate the id for the certificate we are looking for
    CertificateID id = new CertificateID(digestCalculator, new JcaX509CertificateHolder(issuerCert), serialNumber);
    
    // basic request generation with nonce
    OCSPReqBuilder gen = new OCSPReqBuilder();
    
    gen.addRequest(id);
    
    // create details for nonce extension
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded()));
    gen.setRequestExtensions(new Extensions(new Extension[]{ext}));
    
    return gen.build();
}
 
Example #4
Source File: CertificateUtils.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #5
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #6
Source File: TlsHelperTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}
 
Example #7
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 6 votes vote down vote up
private void checkExtnNameConstraints(StringBuilder failureMsg, byte[] extensionValue,
    Extensions requestedExtns, ExtensionControl extControl) {
  NameConstraints conf = nameConstraints;
  if (conf == null) {
    checkConstantExtnValue(Extension.nameConstraints, failureMsg, extensionValue, requestedExtns,
        extControl);
    return;
  }

  org.bouncycastle.asn1.x509.NameConstraints tmpNameConstraints =
      org.bouncycastle.asn1.x509.NameConstraints.getInstance(extensionValue);

  checkExtnNameConstraintsSubtrees(failureMsg, "PermittedSubtrees",
      tmpNameConstraints.getPermittedSubtrees(),  conf.getPermittedSubtrees());
  checkExtnNameConstraintsSubtrees(failureMsg, "ExcludedSubtrees",
      tmpNameConstraints.getExcludedSubtrees(), conf.getExcludedSubtrees());
}
 
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: TestCertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
private void verifyServiceId(Extensions extensions) {
  GeneralNames gns =
      GeneralNames.fromExtensions(
          extensions, Extension.subjectAlternativeName);
  GeneralName[] names = gns.getNames();
  for(int i=0; i < names.length; i++) {
    if(names[i].getTagNo() == GeneralName.otherName) {
      ASN1Encodable asn1Encodable = names[i].getName();
      Iterator iterator = ((DLSequence) asn1Encodable).iterator();
      while (iterator.hasNext()) {
        Object o = iterator.next();
        if (o instanceof ASN1ObjectIdentifier) {
          String oid = o.toString();
          Assert.assertEquals(oid, "2.16.840.1.113730.3.1.34");
        }
        if (o instanceof DERTaggedObject) {
          String serviceName = ((DERTaggedObject)o).getObject().toString();
          Assert.assertEquals(serviceName, "OzoneMarketingCluster003");
        }
      }
    }
  }
}
 
Example #10
Source File: Crypto.java    From athenz with Apache License 2.0 6 votes vote down vote up
public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) {

        List<String> ipAddresses = new ArrayList<>();
        Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        for (Attribute attribute : attributes) {
            for (ASN1Encodable value : attribute.getAttributeValues()) {
                Extensions extensions = Extensions.getInstance(value);
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                ///CLOVER:OFF
                if (gns == null) {
                    continue;
                }
                ///CLOVER:ON
                for (GeneralName name : gns.getNames()) {
                    if (name.getTagNo() == GeneralName.iPAddress) {
                        try {
                            InetAddress addr = InetAddress.getByAddress(((DEROctetString) name.getName()).getOctets());
                            ipAddresses.add(addr.getHostAddress());
                        } catch (UnknownHostException ignored) {
                        }
                    }
                }
            }
        }
        return ipAddresses;
    }
 
Example #11
Source File: SelfSignedCertBuilder.java    From xipki with Apache License 2.0 6 votes vote down vote up
private static void addExtensions(X509v3CertificateBuilder certBuilder,
    IdentifiedCertprofile profile, X500Name requestedSubject, X500Name grantedSubject,
    Extensions extensions, SubjectPublicKeyInfo requestedPublicKeyInfo,
    PublicCaInfo publicCaInfo, Date notBefore, Date notAfter)
    throws CertprofileException, IOException, BadCertTemplateException {
  ExtensionValues extensionTuples = profile.getExtensions(requestedSubject, grantedSubject,
      extensions, requestedPublicKeyInfo, publicCaInfo, null, notBefore, notAfter);
  if (extensionTuples == null) {
    return;
  }

  for (ASN1ObjectIdentifier extType : extensionTuples.getExtensionTypes()) {
    ExtensionValue extValue = extensionTuples.getExtensionValue(extType);
    certBuilder.addExtension(extType, extValue.isCritical(), extValue.getValue());
  }
}
 
Example #12
Source File: OnlineOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private byte[] buildOCSPRequest(final CertificateID certId, BigInteger nonce) throws DSSException {
	try {
		final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
		ocspReqBuilder.addRequest(certId);
		/*
		 * The nonce extension is used to bind a request to a response to
		 * prevent replay attacks. RFC 6960 (OCSP) section 4.1.2 such
		 * extensions SHOULD NOT be flagged as critical
		 */
		if (nonce != null) {
			DEROctetString encodedNonceValue = new DEROctetString(
					new DEROctetString(nonce.toByteArray()).getEncoded());
			Extension extension = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, encodedNonceValue);
			Extensions extensions = new Extensions(extension);
			ocspReqBuilder.setRequestExtensions(extensions);
		}
		final OCSPReq ocspReq = ocspReqBuilder.build();
		final byte[] ocspReqData = ocspReq.getEncoded();
		return ocspReqData;
	} catch (OCSPException | IOException e) {
		throw new DSSException("Cannot build OCSP Request", e);
	}
}
 
Example #13
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Generates an CSR with the extension specified.
 * This function is used to get an Invalid CSR and test that PKI profile
 * rejects these invalid extensions, Hence the function name, by itself it
 * is a well formed CSR, but our PKI profile will treat it as invalid CSR.
 *
 * @param kPair - Key Pair.
 * @return CSR  - PKCS10CertificationRequest
 * @throws OperatorCreationException - on Error.
 */
private PKCS10CertificationRequest getInvalidCSR(KeyPair kPair,
    Extensions extensions) throws OperatorCreationException {
  X500NameBuilder namebuilder =
      new X500NameBuilder(X500Name.getDefaultStyle());
  namebuilder.addRDN(BCStyle.CN, "invalidCert");
  PKCS10CertificationRequestBuilder p10Builder =
      new JcaPKCS10CertificationRequestBuilder(namebuilder.build(),
          keyPair.getPublic());
  p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
      extensions);
  JcaContentSignerBuilder csBuilder =
      new JcaContentSignerBuilder(this.securityConfig.getSignatureAlgo());
  ContentSigner signer = csBuilder.build(keyPair.getPrivate());
  return p10Builder.build(signer);
}
 
Example #14
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Assert that if DNS is marked critical our PKI profile will reject it.
 * @throws IOException - on Error.
 * @throws OperatorCreationException - on Error.
 */
@Test
public void testInvalidExtensionsWithCriticalDNS() throws IOException,
    OperatorCreationException {
  Extensions dnsExtension = getSANExtension(GeneralName.dNSName,
      "ozone.hadoop.org",
      true);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, dnsExtension);
  assertFalse(testApprover.verfiyExtensions(csr));
  // This tests should pass, hence the assertTrue
  dnsExtension = getSANExtension(GeneralName.dNSName,
      "ozone.hadoop.org",
      false);
  csr = getInvalidCSR(keyPair, dnsExtension);
  assertTrue(testApprover.verfiyExtensions(csr));
}
 
Example #15
Source File: TlsHelper.java    From nifi with Apache License 2.0 6 votes vote down vote up
public static Extensions createDomainAlternativeNamesExtensions(List<String> domainAlternativeNames, String requestedDn) throws IOException {
    List<GeneralName> namesList = new ArrayList<>();

    try {
        final String cn = IETFUtils.valueToString(new X500Name(requestedDn).getRDNs(BCStyle.CN)[0].getFirst().getValue());
        namesList.add(new GeneralName(GeneralName.dNSName, cn));
    } catch (Exception e) {
        throw new IOException("Failed to extract CN from request DN: " + requestedDn, e);
    }

    if (domainAlternativeNames != null) {
        for (String alternativeName : domainAlternativeNames) {
             namesList.add(new GeneralName(IPAddress.isValid(alternativeName) ? GeneralName.iPAddress : GeneralName.dNSName, alternativeName));
         }
    }

    GeneralNames subjectAltNames = new GeneralNames(namesList.toArray(new GeneralName[]{}));
    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    return extGen.generate();
}
 
Example #16
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that  invalid extensions cause a failure in validation. We will fail
 * if rfc222 type names are added, we also add the extension as both
 * critical and non-critical fashion to verify that the we catch both cases.
 *
 * @throws SCMSecurityException - on Error.
 */

@Test
public void testInvalidExtensionsWithEmail()
    throws IOException, OperatorCreationException {
  Extensions emailExtension = getSANExtension(GeneralName.rfc822Name,
      "[email protected]", false);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, emailExtension);
  assertFalse(testApprover.verfiyExtensions(csr));

  emailExtension = getSANExtension(GeneralName.rfc822Name, "bilbo" +
      "@apache.org", true);
  csr = getInvalidCSR(keyPair, emailExtension);
  assertFalse(testApprover.verfiyExtensions(csr));

}
 
Example #17
Source File: TlsHelperTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}
 
Example #18
Source File: CertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
private Extensions createExtensions() throws IOException {
  List<Extension> extensions = new ArrayList<>();

  // Add basic extension
  if(ca) {
    extensions.add(getBasicExtension());
  }

  // Add key usage extension
  extensions.add(getKeyUsageExtension());

  // Add subject alternate name extension
  Optional<Extension> san = getSubjectAltNameExtension();
  if (san.isPresent()) {
    extensions.add(san.get());
  }

  return new Extensions(
      extensions.toArray(new Extension[extensions.size()]));
}
 
Example #19
Source File: BaseApprover.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * This function verifies all extensions in the certificate.
 *
 * @param request - CSR
 * @return - true if the extensions are acceptable by the profile, false
 * otherwise.
 */
boolean verfiyExtensions(PKCS10CertificationRequest request) {
  Objects.requireNonNull(request);
  /*
   * Inside a CSR we have
   *  1. A list of Attributes
   *    2. Inside each attribute a list of extensions.
   *      3. We need to walk thru the each extension and verify they
   *      are expected and we can put that into a certificate.
   */

  for (Attribute attr : getAttributes(request)) {
    for (Extensions extensionsList : getExtensionsList(attr)) {
      for (Extension extension : getIndividualExtension(extensionsList)) {
        if (!profile.validateExtension(extension)) {
          LOG.error("Failed to verify extension. {}",
              extension.getExtnId().getId());
          return false;
        }
      }
    }
  }
  return true;
}
 
Example #20
Source File: CaUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static Extensions getExtensions(CertificationRequestInfo csr) {
  Args.notNull(csr, "csr");
  ASN1Set attrs = csr.getAttributes();
  for (int i = 0; i < attrs.size(); i++) {
    Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
    if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
      return Extensions.getInstance(attr.getAttributeValues()[0]);
    }
  }
  return null;
}
 
Example #21
Source File: CmpAgent.java    From xipki with Apache License 2.0 5 votes vote down vote up
private PKIMessage buildUnrevokeOrRemoveCertRequest(UnrevokeOrRemoveCertRequest request,
    int reasonCode) throws CmpClientException {
  PKIHeader header = buildPkiHeader(null);

  List<UnrevokeOrRemoveCertRequest.Entry> requestEntries = request.getRequestEntries();
  List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
  for (UnrevokeOrRemoveCertRequest.Entry requestEntry : requestEntries) {
    CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
    certTempBuilder.setIssuer(requestEntry.getIssuer());
    certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));
    byte[] aki = requestEntry.getAuthorityKeyIdentifier();
    if (aki != null) {
      Extensions certTempExts = getCertTempExtensions(aki);
      certTempBuilder.setExtensions(certTempExts);
    }

    Extension[] extensions = new Extension[1];

    try {
      ASN1Enumerated reason = new ASN1Enumerated(reasonCode);
      extensions[0] = new Extension(Extension.reasonCode, true,
              new DEROctetString(reason.getEncoded()));
    } catch (IOException ex) {
      throw new CmpClientException(ex.getMessage(), ex);
    }
    Extensions exts = new Extensions(extensions);

    RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
    revDetailsArray.add(revDetails);
  }

  RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
  PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
  return new PKIMessage(header, body);
}
 
Example #22
Source File: CertTemplateData.java    From xipki with Apache License 2.0 5 votes vote down vote up
public CertTemplateData(X500Name subject, SubjectPublicKeyInfo publicKeyInfo,
    Date notBefore, Date notAfter, Extensions extensions, String certprofileName,
    ASN1Integer certReqId, boolean caGenerateKeypair) {
  this.publicKeyInfo = publicKeyInfo;
  this.subject = Args.notNull(subject, "subject");
  this.certprofileName = Args.toNonBlankLower(certprofileName, "certprofileName");
  this.extensions = extensions;
  this.notBefore = notBefore;
  this.notAfter = notAfter;
  this.certReqId = certReqId;
  this.caGenerateKeypair = caGenerateKeypair;
}
 
Example #23
Source File: CmpAgent.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static Extensions getCertTempExtensions(byte[] authorityKeyIdentifier)
    throws CmpClientException {
  AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(authorityKeyIdentifier);
  byte[] encodedAki;
  try {
    encodedAki = aki.getEncoded();
  } catch (IOException ex) {
    throw new CmpClientException("could not encoded AuthorityKeyIdentifier", ex);
  }
  Extension extAki = new Extension(Extension.authorityKeyIdentifier, false, encodedAki);
  Extensions certTempExts = new Extensions(extAki);
  return certTempExts;
}
 
Example #24
Source File: X509Util.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static byte[] getCoreExtValue(Extensions extensions, ASN1ObjectIdentifier extnType) {
  Args.notNull(extensions, "extensions");
  Args.notNull(extnType, "extnType");
  Extension extn = extensions.getExtension(extnType);
  if (extn == null) {
    return null;
  }

  return extn.getExtnValue().getOctets();
}
 
Example #25
Source File: BaseApprover.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Extension decoded into a Java Collection.
 * @param extensions - A set of Extensions in ASN.1.
 * @return List of Decoded Extensions.
 */
List<Extension> getIndividualExtension(Extensions extensions) {
  Objects.requireNonNull(extensions);
  List<Extension> extenList = new ArrayList<>();
  for (ASN1ObjectIdentifier id : extensions.getExtensionOIDs()) {
    if (id != null) {
      Extension ext = extensions.getExtension(id);
      if (ext != null) {
        extenList.add(ext);
      }
    }
  }
  return extenList;
}
 
Example #26
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private void checkExtnPolicyMappings(StringBuilder failureMsg, byte[] extensionValue,
    Extensions requestedExtns, ExtensionControl extControl) {
  PolicyMappings conf = policyMappings;
  if (conf == null) {
    checkConstantExtnValue(Extension.policyMappings, failureMsg, extensionValue,
        requestedExtns, extControl);
    return;
  }

  ASN1Sequence isPolicyMappings = DERSequence.getInstance(extensionValue);
  Map<String, String> isMap = new HashMap<>();
  int size = isPolicyMappings.size();
  for (int i = 0; i < size; i++) {
    ASN1Sequence seq = ASN1Sequence.getInstance(isPolicyMappings.getObjectAt(i));
    CertPolicyId issuerDomainPolicy = CertPolicyId.getInstance(seq.getObjectAt(0));
    CertPolicyId subjectDomainPolicy = CertPolicyId.getInstance(seq.getObjectAt(1));
    isMap.put(issuerDomainPolicy.getId(), subjectDomainPolicy.getId());
  }

  for (PolicyIdMappingType m : conf.getMappings()) {
    String expIssuerDomainPolicy = m.getIssuerDomainPolicy().getOid();
    String expSubjectDomainPolicy = m.getSubjectDomainPolicy().getOid();

    String isSubjectDomainPolicy = isMap.remove(expIssuerDomainPolicy);
    if (isSubjectDomainPolicy == null) {
      failureMsg.append("issuerDomainPolicy '").append(expIssuerDomainPolicy)
        .append("' is absent but is required; ");
    } else if (!isSubjectDomainPolicy.equals(expSubjectDomainPolicy)) {
      addViolation(failureMsg, "subjectDomainPolicy for issuerDomainPolicy",
          isSubjectDomainPolicy, expSubjectDomainPolicy);
    }
  }

  if (CollectionUtil.isNotEmpty(isMap)) {
    failureMsg.append("issuerDomainPolicies '").append(isMap.keySet())
      .append("' are present but not expected; ");
  }
}
 
Example #27
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private void checkExtnTlsFeature(StringBuilder failureMsg, byte[] extensionValue,
    Extensions requestedExtns, ExtensionControl extControl) {
  TlsFeature conf = tlsFeature;
  if (tlsFeature == null) {
    checkConstantExtnValue(Extn.id_pe_tlsfeature, failureMsg, extensionValue,
        requestedExtns, extControl);
    return;
  }

  Set<String> isFeatures = new HashSet<>();
  ASN1Sequence seq = ASN1Sequence.getInstance(extensionValue);
  final int n = seq.size();
  for (int i = 0; i < n; i++) {
    ASN1Integer asn1Feature = ASN1Integer.getInstance(seq.getObjectAt(i));
    isFeatures.add(asn1Feature.getPositiveValue().toString());
  }

  Set<String> expFeatures = new HashSet<>();
  for (DescribableInt m : conf.getFeatures()) {
    expFeatures.add(Integer.toString(m.getValue()));
  }

  Set<String> diffs = strInBnotInA(expFeatures, isFeatures);
  if (CollectionUtil.isNotEmpty(diffs)) {
    failureMsg.append("features ").append(diffs).append(" are present but not expected; ");
  }

  diffs = strInBnotInA(isFeatures, expFeatures);
  if (CollectionUtil.isNotEmpty(diffs)) {
    failureMsg.append("features ").append(diffs).append(" are absent but are required; ");
  }
}
 
Example #28
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 #29
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private byte[] getExpectedExtValue(ASN1ObjectIdentifier type, Extensions requestedExtns,
    ExtensionControl extControl) {
  if (constantExtensions != null && constantExtensions.containsKey(type)) {
    return constantExtensions.get(type).getValue();
  } else if (requestedExtns != null && extControl.isRequest()) {
    Extension reqExt = requestedExtns.getExtension(type);
    if (reqExt != null) {
      return reqExt.getExtnValue().getOctets();
    }
  }

  return null;
}
 
Example #30
Source File: MyUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static PKCS10CertificationRequest generateRequest(PrivateKey privatekey,
    SubjectPublicKeyInfo subjectPublicKeyInfo, X500Name subjectDn,
    String challengePassword, List<Extension> extensions)
    throws OperatorCreationException {
  Args.notNull(privatekey, "privatekey");
  Args.notNull(subjectPublicKeyInfo, "subjectPublicKeyInfo");
  Args.notNull(subjectDn, "subjectDn");

  Map<ASN1ObjectIdentifier, ASN1Encodable> attributes =
      new HashMap<ASN1ObjectIdentifier, ASN1Encodable>();

  if (StringUtil.isNotBlank(challengePassword)) {
    DERPrintableString asn1Pwd = new DERPrintableString(challengePassword);
    attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, asn1Pwd);
  }

  if (CollectionUtil.isNotEmpty(extensions)) {
    Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0]));
    attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, asn1Extensions);
  }

  PKCS10CertificationRequestBuilder csrBuilder =
      new PKCS10CertificationRequestBuilder(subjectDn, subjectPublicKeyInfo);

  if (attributes != null) {
    for (ASN1ObjectIdentifier attrType : attributes.keySet()) {
      csrBuilder.addAttribute(attrType, attributes.get(attrType));
    }
  }

  ContentSigner contentSigner = new JcaContentSignerBuilder(
      ScepUtil.getSignatureAlgorithm(privatekey, HashAlgo.SHA1)).build(privatekey);
  return csrBuilder.build(contentSigner);
}