Search in sources :

Example 56 with Request

use of org.bouncycastle.asn1.ocsp.Request in project robovm by robovm.

the class X509AttributeCertificateHolder method getAttributes.

/**
     * Return the attributes, if any associated with this request.
     *
     * @return an array of Attribute, zero length if none present.
     */
public Attribute[] getAttributes() {
    ASN1Sequence seq = attrCert.getAcinfo().getAttributes();
    Attribute[] attrs = new Attribute[seq.size()];
    for (int i = 0; i != seq.size(); i++) {
        attrs[i] = Attribute.getInstance(seq.getObjectAt(i));
    }
    return attrs;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) Attribute(org.bouncycastle.asn1.x509.Attribute)

Example 57 with Request

use of org.bouncycastle.asn1.ocsp.Request in project keywhiz by square.

the class ClientAuthFactory method getClientName.

static Optional<String> getClientName(ContainerRequest request) {
    Principal principal = request.getSecurityContext().getUserPrincipal();
    if (principal == null) {
        return Optional.empty();
    }
    X500Name name = new X500Name(principal.getName());
    RDN[] rdns = name.getRDNs(BCStyle.CN);
    if (rdns.length == 0) {
        logger.warn("Certificate does not contain CN=xxx,...: {}", principal.getName());
        return Optional.empty();
    }
    return Optional.of(IETFUtils.valueToString(rdns[0].getFirst().getValue()));
}
Also used : X500Name(org.bouncycastle.asn1.x500.X500Name) RDN(org.bouncycastle.asn1.x500.RDN) Principal(java.security.Principal)

Example 58 with Request

use of org.bouncycastle.asn1.ocsp.Request in project nhin-d by DirectProject.

the class PKCS11Commands method createCSR.

@Command(name = "CreateCSR", usage = CREATE_CSR)
public void createCSR(String[] args) {
    final String alias = StringArrayUtil.getRequiredValue(args, 0);
    final String commonName = StringArrayUtil.getRequiredValue(args, 1);
    final String subjectAltName = StringArrayUtil.getRequiredValue(args, 2);
    final String keyUsage = StringArrayUtil.getRequiredValue(args, 3);
    // make sure we have a valid keyUsage
    if (!(keyUsage.compareToIgnoreCase("DigitalSignature") == 0 || keyUsage.compareToIgnoreCase("KeyEncipherment") == 0 || keyUsage.compareToIgnoreCase("DualUse") == 0)) {
        System.out.println("Invalid key usage.");
        return;
    }
    final Vector<String> additionalRDNFields = new Vector<String>();
    int cnt = 4;
    String rdnField;
    do {
        rdnField = StringArrayUtil.getOptionalValue(args, cnt++, "");
        if (!StringUtils.isEmpty(rdnField))
            additionalRDNFields.add(rdnField);
    } while (!StringUtils.isEmpty(rdnField));
    try {
        final KeyStore ks = mgr.getKS();
        if (!ks.containsAlias(alias)) {
            System.out.println("Entry with key name " + alias + " does not exist.");
            return;
        }
        final X509Certificate storedCert = (X509Certificate) ks.getCertificate(alias);
        if (storedCert == null) {
            System.out.println("Key name " + alias + " does not contain a certificate that can be exported.  This key may not be an RSA key pair.");
            return;
        }
        final PrivateKey privKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
        if (privKey == null) {
            System.out.println("Failed to object private key.  This key may not be an RSA key pair.");
            return;
        }
        // create the CSR
        //  create the extensions that we want
        final X509ExtensionsGenerator extsGen = new X509ExtensionsGenerator();
        // Key Usage
        int usage;
        if (keyUsage.compareToIgnoreCase("KeyEncipherment") == 0)
            usage = KeyUsage.keyEncipherment;
        else if (keyUsage.compareToIgnoreCase("DigitalSignature") == 0)
            usage = KeyUsage.digitalSignature;
        else
            usage = KeyUsage.keyEncipherment | KeyUsage.digitalSignature;
        extsGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(usage));
        // Subject Alt Name
        int nameType = subjectAltName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
        final GeneralNames altName = new GeneralNames(new GeneralName(nameType, subjectAltName));
        extsGen.addExtension(X509Extensions.SubjectAlternativeName, false, altName);
        // Extended Key Usage
        final Vector<KeyPurposeId> purposes = new Vector<KeyPurposeId>();
        purposes.add(KeyPurposeId.id_kp_emailProtection);
        extsGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(purposes));
        // Basic constraint
        final BasicConstraints bc = new BasicConstraints(false);
        extsGen.addExtension(X509Extensions.BasicConstraints, true, bc);
        // create the extension requests
        final X509Extensions exts = extsGen.generate();
        final ASN1EncodableVector attributes = new ASN1EncodableVector();
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(exts.toASN1Object()));
        attributes.add(attribute);
        final DERSet requestedAttributes = new DERSet(attributes);
        // create the DN
        final StringBuilder dnBuilder = new StringBuilder("CN=").append(commonName);
        for (String field : additionalRDNFields) dnBuilder.append(",").append(field);
        final X500Principal subjectPrin = new X500Principal(dnBuilder.toString());
        final X509Principal xName = new X509Principal(true, subjectPrin.getName());
        // create the CSR
        final PKCS10CertificationRequest request = new PKCS10CertificationRequest("SHA256WITHRSA", xName, storedCert.getPublicKey(), requestedAttributes, privKey, ks.getProvider().getName());
        final byte[] encodedCSR = request.getEncoded();
        final String csrString = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + Base64.encodeBase64String(encodedCSR) + "-----END CERTIFICATE REQUEST-----";
        final File csrFile = new File(alias + "-CSR.pem");
        FileUtils.writeStringToFile(csrFile, csrString);
        System.out.println("CSR written to " + csrFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to create CSR : " + e.getMessage());
    }
}
Also used : PrivateKey(java.security.PrivateKey) Attribute(org.bouncycastle.asn1.x509.Attribute) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERSet(org.bouncycastle.asn1.DERSet) X509Principal(org.bouncycastle.jce.X509Principal) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) X509ExtensionsGenerator(org.bouncycastle.asn1.x509.X509ExtensionsGenerator) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X500Principal(javax.security.auth.x500.X500Principal) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) File(java.io.File) Command(org.nhindirect.common.tooling.Command)

Example 59 with Request

use of org.bouncycastle.asn1.ocsp.Request in project oxAuth by GluuFederation.

the class OCSPCertificateVerifier method validate.

@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;
}
Also used : CertificateID(org.bouncycastle.cert.ocsp.CertificateID) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) CertificateEncodingException(java.security.cert.CertificateEncodingException) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) ValidationStatus(org.xdi.oxauth.cert.validation.model.ValidationStatus) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) Principal(java.security.Principal)

Example 60 with Request

use of org.bouncycastle.asn1.ocsp.Request in project poi by apache.

the class TSPTimeStampService method timeStamp.

@SuppressWarnings("unchecked")
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = CryptoFunctions.getMessageDigest(signatureConfig.getTspDigestAlgo());
    byte[] digest = messageDigest.digest(data);
    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);
    String requestPolicy = signatureConfig.getTspRequestPolicy();
    if (requestPolicy != null) {
        requestGenerator.setReqPolicy(new ASN1ObjectIdentifier(requestPolicy));
    }
    ASN1ObjectIdentifier digestAlgoOid = mapDigestAlgoToOID(signatureConfig.getTspDigestAlgo());
    TimeStampRequest request = requestGenerator.generate(digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();
    // create the HTTP POST request
    Proxy proxy = Proxy.NO_PROXY;
    if (signatureConfig.getProxyUrl() != null) {
        URL proxyUrl = new URL(signatureConfig.getProxyUrl());
        String host = proxyUrl.getHost();
        int port = proxyUrl.getPort();
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getByName(host), (port == -1 ? 80 : port)));
    }
    HttpURLConnection huc = (HttpURLConnection) new URL(signatureConfig.getTspUrl()).openConnection(proxy);
    if (signatureConfig.getTspUser() != null) {
        String userPassword = signatureConfig.getTspUser() + ":" + signatureConfig.getTspPass();
        String encoding = DatatypeConverter.printBase64Binary(userPassword.getBytes(Charset.forName("iso-8859-1")));
        huc.setRequestProperty("Authorization", "Basic " + encoding);
    }
    huc.setRequestMethod("POST");
    huc.setConnectTimeout(20000);
    huc.setReadTimeout(20000);
    // also sets method to POST.
    huc.setDoOutput(true);
    huc.setRequestProperty("User-Agent", signatureConfig.getUserAgent());
    huc.setRequestProperty("Content-Type", signatureConfig.isTspOldProtocol() ? "application/timestamp-request" : // "; charset=ISO-8859-1");
    "application/timestamp-query");
    OutputStream hucOut = huc.getOutputStream();
    hucOut.write(encodedRequest);
    // invoke TSP service
    huc.connect();
    int statusCode = huc.getResponseCode();
    if (statusCode != 200) {
        LOG.log(POILogger.ERROR, "Error contacting TSP server ", signatureConfig.getTspUrl() + ", had status code " + statusCode + "/" + huc.getResponseMessage());
        throw new IOException("Error contacting TSP server " + signatureConfig.getTspUrl() + ", had status code " + statusCode + "/" + huc.getResponseMessage());
    }
    // HTTP input validation
    String contentType = huc.getHeaderField("Content-Type");
    if (null == contentType) {
        throw new RuntimeException("missing Content-Type header");
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(huc.getInputStream(), bos);
    LOG.log(POILogger.DEBUG, "response content: ", HexDump.dump(bos.toByteArray(), 0, 0));
    if (!contentType.startsWith(signatureConfig.isTspOldProtocol() ? "application/timestamp-response" : "application/timestamp-reply")) {
        throw new RuntimeException("invalid Content-Type: " + contentType + // dump the first few bytes
        ": " + HexDump.dump(bos.toByteArray(), 0, 0, 200));
    }
    if (bos.size() == 0) {
        throw new RuntimeException("Content-Length is zero");
    }
    // TSP response parsing and validation
    TimeStampResponse timeStampResponse = new TimeStampResponse(bos.toByteArray());
    timeStampResponse.validate(request);
    if (0 != timeStampResponse.getStatus()) {
        LOG.log(POILogger.DEBUG, "status: " + timeStampResponse.getStatus());
        LOG.log(POILogger.DEBUG, "status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.log(POILogger.DEBUG, "fail info int value: " + failInfo.intValue());
            if (/*PKIFailureInfo.unacceptedPolicy*/
            (1 << 8) == failInfo.intValue()) {
                LOG.log(POILogger.DEBUG, "unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Name signerCertIssuer = signerId.getIssuer();
    LOG.log(POILogger.DEBUG, "signer cert serial number: " + signerCertSerialNumber);
    LOG.log(POILogger.DEBUG, "signer cert issuer: " + signerCertIssuer);
    // TSP signer certificates retrieval
    Collection<X509CertificateHolder> certificates = timeStampToken.getCertificates().getMatches(null);
    X509CertificateHolder signerCert = null;
    Map<X500Name, X509CertificateHolder> certificateMap = new HashMap<X500Name, X509CertificateHolder>();
    for (X509CertificateHolder certificate : certificates) {
        if (signerCertIssuer.equals(certificate.getIssuer()) && signerCertSerialNumber.equals(certificate.getSerialNumber())) {
            signerCert = certificate;
        }
        certificateMap.put(certificate.getSubject(), certificate);
    }
    // TSP signer cert path building
    if (signerCert == null) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new ArrayList<X509Certificate>();
    JcaX509CertificateConverter x509converter = new JcaX509CertificateConverter();
    x509converter.setProvider("BC");
    X509CertificateHolder certificate = signerCert;
    do {
        LOG.log(POILogger.DEBUG, "adding to certificate chain: " + certificate.getSubject());
        tspCertificateChain.add(x509converter.getCertificate(certificate));
        if (certificate.getSubject().equals(certificate.getIssuer())) {
            break;
        }
        certificate = certificateMap.get(certificate.getIssuer());
    } while (null != certificate);
    // verify TSP signer signature
    X509CertificateHolder holder = new X509CertificateHolder(tspCertificateChain.get(0).getEncoded());
    DefaultCMSSignatureAlgorithmNameGenerator nameGen = new DefaultCMSSignatureAlgorithmNameGenerator();
    DefaultSignatureAlgorithmIdentifierFinder sigAlgoFinder = new DefaultSignatureAlgorithmIdentifierFinder();
    DefaultDigestAlgorithmIdentifierFinder hashAlgoFinder = new DefaultDigestAlgorithmIdentifierFinder();
    BcDigestCalculatorProvider calculator = new BcDigestCalculatorProvider();
    BcRSASignerInfoVerifierBuilder verifierBuilder = new BcRSASignerInfoVerifierBuilder(nameGen, sigAlgoFinder, hashAlgoFinder, calculator);
    SignerInformationVerifier verifier = verifierBuilder.build(holder);
    timeStampToken.validate(verifier);
    // verify TSP signer certificate
    if (signatureConfig.getTspValidator() != null) {
        signatureConfig.getTspValidator().validate(tspCertificateChain, revocationData);
    }
    LOG.log(POILogger.DEBUG, "time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());
    return timeStampToken.getEncoded();
}
Also used : DefaultCMSSignatureAlgorithmNameGenerator(org.bouncycastle.cms.DefaultCMSSignatureAlgorithmNameGenerator) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) X500Name(org.bouncycastle.asn1.x500.X500Name) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) URL(java.net.URL) TimeStampResponse(org.bouncycastle.tsp.TimeStampResponse) Proxy(java.net.Proxy) HttpURLConnection(java.net.HttpURLConnection) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) MessageDigest(java.security.MessageDigest) SignerInformationVerifier(org.bouncycastle.cms.SignerInformationVerifier) BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TimeStampRequest(org.bouncycastle.tsp.TimeStampRequest) X509Certificate(java.security.cert.X509Certificate) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) PKIFailureInfo(org.bouncycastle.asn1.cmp.PKIFailureInfo) SignerId(org.bouncycastle.cms.SignerId) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) TimeStampRequestGenerator(org.bouncycastle.tsp.TimeStampRequestGenerator) BcRSASignerInfoVerifierBuilder(org.bouncycastle.cms.bc.BcRSASignerInfoVerifierBuilder) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

IOException (java.io.IOException)47 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)30 Date (java.util.Date)27 DEROctetString (org.bouncycastle.asn1.DEROctetString)26 BigInteger (java.math.BigInteger)23 X509Certificate (java.security.cert.X509Certificate)22 PKIMessage (org.bouncycastle.asn1.cmp.PKIMessage)22 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)20 CertificateException (java.security.cert.CertificateException)18 ArrayList (java.util.ArrayList)17 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)17 X500Name (org.bouncycastle.asn1.x500.X500Name)16 Extension (org.bouncycastle.asn1.x509.Extension)16 Extensions (org.bouncycastle.asn1.x509.Extensions)16 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)15 DERIA5String (org.bouncycastle.asn1.DERIA5String)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 PKIBody (org.bouncycastle.asn1.cmp.PKIBody)13 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)12 GeneralName (org.bouncycastle.asn1.x509.GeneralName)11