Search in sources :

Example 96 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project xipki by xipki.

the class AbstractOcspRequestor method buildRequest.

// method ask
private OCSPRequest buildRequest(X509Certificate caCert, BigInteger[] serialNumbers, byte[] nonce, RequestOptions requestOptions) throws OcspRequestorException {
    HashAlgo hashAlgo = HashAlgo.getInstance(requestOptions.getHashAlgorithmId());
    if (hashAlgo == null) {
        throw new OcspRequestorException("unknown HashAlgo " + requestOptions.getHashAlgorithmId().getId());
    }
    List<AlgorithmIdentifier> prefSigAlgs = requestOptions.getPreferredSignatureAlgorithms();
    XiOCSPReqBuilder reqBuilder = new XiOCSPReqBuilder();
    List<Extension> extensions = new LinkedList<>();
    if (nonce != null) {
        extensions.add(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)));
    }
    if (prefSigAlgs != null && prefSigAlgs.size() > 0) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (AlgorithmIdentifier algId : prefSigAlgs) {
            vec.add(new DERSequence(algId));
        }
        ASN1Sequence extnValue = new DERSequence(vec);
        Extension extn;
        try {
            extn = new Extension(ObjectIdentifiers.id_pkix_ocsp_prefSigAlgs, false, new DEROctetString(extnValue));
        } catch (IOException ex) {
            throw new OcspRequestorException(ex.getMessage(), ex);
        }
        extensions.add(extn);
    }
    if (CollectionUtil.isNonEmpty(extensions)) {
        reqBuilder.setRequestExtensions(new Extensions(extensions.toArray(new Extension[0])));
    }
    try {
        DEROctetString issuerNameHash = new DEROctetString(hashAlgo.hash(caCert.getSubjectX500Principal().getEncoded()));
        TBSCertificate tbsCert;
        try {
            tbsCert = TBSCertificate.getInstance(caCert.getTBSCertificate());
        } catch (CertificateEncodingException ex) {
            throw new OcspRequestorException(ex);
        }
        DEROctetString issuerKeyHash = new DEROctetString(hashAlgo.hash(tbsCert.getSubjectPublicKeyInfo().getPublicKeyData().getOctets()));
        for (BigInteger serialNumber : serialNumbers) {
            CertID certId = new CertID(hashAlgo.getAlgorithmIdentifier(), issuerNameHash, issuerKeyHash, new ASN1Integer(serialNumber));
            reqBuilder.addRequest(certId);
        }
        if (requestOptions.isSignRequest()) {
            synchronized (signerLock) {
                if (signer == null) {
                    if (StringUtil.isBlank(signerType)) {
                        throw new OcspRequestorException("signerType is not configured");
                    }
                    if (StringUtil.isBlank(signerConf)) {
                        throw new OcspRequestorException("signerConf is not configured");
                    }
                    X509Certificate cert = null;
                    if (StringUtil.isNotBlank(signerCertFile)) {
                        try {
                            cert = X509Util.parseCert(signerCertFile);
                        } catch (CertificateException ex) {
                            throw new OcspRequestorException("could not parse certificate " + signerCertFile + ": " + ex.getMessage());
                        }
                    }
                    try {
                        signer = getSecurityFactory().createSigner(signerType, new SignerConf(signerConf), cert);
                    } catch (Exception ex) {
                        throw new OcspRequestorException("could not create signer: " + ex.getMessage());
                    }
                }
            // end if
            }
            // end synchronized
            reqBuilder.setRequestorName(signer.getBcCertificate().getSubject());
            X509CertificateHolder[] certChain0 = signer.getBcCertificateChain();
            Certificate[] certChain = new Certificate[certChain0.length];
            for (int i = 0; i < certChain.length; i++) {
                certChain[i] = certChain0[i].toASN1Structure();
            }
            ConcurrentBagEntrySigner signer0;
            try {
                signer0 = signer.borrowSigner();
            } catch (NoIdleSignerException ex) {
                throw new OcspRequestorException("NoIdleSignerException: " + ex.getMessage());
            }
            try {
                return reqBuilder.build(signer0.value(), certChain);
            } finally {
                signer.requiteSigner(signer0);
            }
        } else {
            return reqBuilder.build();
        }
    // end if
    } catch (OCSPException | IOException ex) {
        throw new OcspRequestorException(ex.getMessage(), ex);
    }
}
Also used : HashAlgo(org.xipki.security.HashAlgo) CertID(org.bouncycastle.asn1.ocsp.CertID) CertificateException(java.security.cert.CertificateException) Extensions(org.bouncycastle.asn1.x509.Extensions) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) SignerConf(org.xipki.security.SignerConf) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ConcurrentBagEntrySigner(org.xipki.security.ConcurrentBagEntrySigner) LinkedList(java.util.LinkedList) X509Certificate(java.security.cert.X509Certificate) OcspNonceUnmatchedException(org.xipki.ocsp.client.api.OcspNonceUnmatchedException) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) OcspResponseException(org.xipki.ocsp.client.api.OcspResponseException) OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) CertificateEncodingException(java.security.cert.CertificateEncodingException) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) ResponderUnreachableException(org.xipki.ocsp.client.api.ResponderUnreachableException) OcspTargetUnmatchedException(org.xipki.ocsp.client.api.OcspTargetUnmatchedException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) InvalidOcspResponseException(org.xipki.ocsp.client.api.InvalidOcspResponseException) Extension(org.bouncycastle.asn1.x509.Extension) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 97 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project xipki by xipki.

the class XiOCSPReqBuilder method generateRequest.

private OCSPRequest generateRequest(ContentSigner contentSigner, Certificate[] chain) throws OCSPException {
    Iterator<RequestObject> it = list.iterator();
    ASN1EncodableVector requests = new ASN1EncodableVector();
    while (it.hasNext()) {
        try {
            requests.add(((RequestObject) it.next()).toRequest());
        } catch (Exception ex) {
            throw new OCSPException("exception creating Request", ex);
        }
    }
    TBSRequest tbsReq = new TBSRequest(requestorName, new DERSequence(requests), requestExtensions);
    Signature signature = null;
    if (contentSigner != null) {
        if (requestorName == null) {
            throw new OCSPException("requestorName must be specified if request is signed.");
        }
        try {
            // CHECKSTYLE:SKIP
            OutputStream sOut = contentSigner.getOutputStream();
            sOut.write(tbsReq.getEncoded(ASN1Encoding.DER));
            sOut.close();
        } catch (Exception ex) {
            throw new OCSPException("exception processing TBSRequest: " + ex, ex);
        }
        DERBitString bitSig = new DERBitString(contentSigner.getSignature());
        AlgorithmIdentifier sigAlgId = contentSigner.getAlgorithmIdentifier();
        if (chain != null && chain.length > 0) {
            ASN1EncodableVector vec = new ASN1EncodableVector();
            for (int i = 0; i != chain.length; i++) {
                vec.add(chain[i]);
            }
            signature = new Signature(sigAlgId, bitSig, new DERSequence(vec));
        } else {
            signature = new Signature(sigAlgId, bitSig);
        }
    }
    return new OCSPRequest(tbsReq, signature);
}
Also used : OutputStream(java.io.OutputStream) DERBitString(org.bouncycastle.asn1.DERBitString) TBSRequest(org.bouncycastle.asn1.ocsp.TBSRequest) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) Signature(org.bouncycastle.asn1.ocsp.Signature) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) OCSPRequest(org.bouncycastle.asn1.ocsp.OCSPRequest)

Example 98 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project xipki by xipki.

the class OcspQa method checkOcsp.

public ValidationResult checkOcsp(OCSPResp response, IssuerHash issuerHash, List<BigInteger> serialNumbers, Map<BigInteger, byte[]> encodedCerts, OcspError expectedOcspError, Map<BigInteger, OcspCertStatus> expectedOcspStatuses, Map<BigInteger, Date> expectedRevTimes, OcspResponseOption responseOption, boolean noSigVerify) {
    ParamUtil.requireNonNull("response", response);
    ParamUtil.requireNonEmpty("serialNumbers", serialNumbers);
    ParamUtil.requireNonEmpty("expectedOcspStatuses", expectedOcspStatuses);
    ParamUtil.requireNonNull("responseOption", responseOption);
    List<ValidationIssue> resultIssues = new LinkedList<ValidationIssue>();
    int status = response.getStatus();
    // Response status
    ValidationIssue issue = new ValidationIssue("OCSP.STATUS", "response.status");
    resultIssues.add(issue);
    if (expectedOcspError != null) {
        if (status != expectedOcspError.getStatus()) {
            issue.setFailureMessage("is '" + status + "', but expected '" + expectedOcspError.getStatus() + "'");
        }
    } else {
        if (status != 0) {
            issue.setFailureMessage("is '" + status + "', but expected '0'");
        }
    }
    if (status != 0) {
        return new ValidationResult(resultIssues);
    }
    ValidationIssue encodingIssue = new ValidationIssue("OCSP.ENCODING", "response encoding");
    resultIssues.add(encodingIssue);
    BasicOCSPResp basicResp;
    try {
        basicResp = (BasicOCSPResp) response.getResponseObject();
    } catch (OCSPException ex) {
        encodingIssue.setFailureMessage(ex.getMessage());
        return new ValidationResult(resultIssues);
    }
    SingleResp[] singleResponses = basicResp.getResponses();
    issue = new ValidationIssue("OCSP.RESPONSES.NUM", "number of single responses");
    resultIssues.add(issue);
    if (singleResponses == null || singleResponses.length == 0) {
        issue.setFailureMessage("received no status from server");
        return new ValidationResult(resultIssues);
    }
    final int n = singleResponses.length;
    if (n != serialNumbers.size()) {
        issue.setFailureMessage("is '" + n + "', but expected '" + serialNumbers.size() + "'");
        return new ValidationResult(resultIssues);
    }
    boolean hasSignature = basicResp.getSignature() != null;
    // check the signature if available
    if (noSigVerify) {
        issue = new ValidationIssue("OCSP.SIG", (hasSignature ? "signature presence (Ignore)" : "signature presence"));
    } else {
        issue = new ValidationIssue("OCSP.SIG", "signature presence");
    }
    resultIssues.add(issue);
    if (!hasSignature) {
        issue.setFailureMessage("response is not signed");
    }
    if (hasSignature & !noSigVerify) {
        // signature algorithm
        issue = new ValidationIssue("OCSP.SIG.ALG", "signature algorithm");
        resultIssues.add(issue);
        String expectedSigalgo = responseOption.getSignatureAlgName();
        if (expectedSigalgo != null) {
            AlgorithmIdentifier sigAlg = basicResp.getSignatureAlgorithmID();
            try {
                String sigAlgName = AlgorithmUtil.getSignatureAlgoName(sigAlg);
                if (!AlgorithmUtil.equalsAlgoName(sigAlgName, expectedSigalgo)) {
                    issue.setFailureMessage("is '" + sigAlgName + "', but expected '" + expectedSigalgo + "'");
                }
            } catch (NoSuchAlgorithmException ex) {
                issue.setFailureMessage("could not extract the signature algorithm");
            }
        }
        // end if (expectedSigalgo != null)
        // signer certificate
        ValidationIssue sigSignerCertIssue = new ValidationIssue("OCSP.SIGNERCERT", "signer certificate");
        resultIssues.add(sigSignerCertIssue);
        // signature validation
        ValidationIssue sigValIssue = new ValidationIssue("OCSP.SIG.VALIDATION", "signature validation");
        resultIssues.add(sigValIssue);
        X509CertificateHolder respSigner = null;
        X509CertificateHolder[] responderCerts = basicResp.getCerts();
        if (responderCerts == null || responderCerts.length < 1) {
            sigSignerCertIssue.setFailureMessage("no responder certificate is contained in the response");
            sigValIssue.setFailureMessage("could not find certificate to validate signature");
        } else {
            ResponderID respId = basicResp.getResponderId().toASN1Primitive();
            X500Name respIdByName = respId.getName();
            byte[] respIdByKey = respId.getKeyHash();
            for (X509CertificateHolder cert : responderCerts) {
                if (respIdByName != null) {
                    if (cert.getSubject().equals(respIdByName)) {
                        respSigner = cert;
                    }
                } else {
                    byte[] spkiSha1 = HashAlgo.SHA1.hash(cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());
                    if (Arrays.equals(respIdByKey, spkiSha1)) {
                        respSigner = cert;
                    }
                }
                if (respSigner != null) {
                    break;
                }
            }
            if (respSigner == null) {
                sigSignerCertIssue.setFailureMessage("no responder certificate match the ResponderId");
                sigValIssue.setFailureMessage("could not find certificate matching the" + " ResponderId to validate signature");
            }
        }
        if (respSigner != null) {
            issue = new ValidationIssue("OCSP.SIGNERCERT.TRUST", "signer certificate validation");
            resultIssues.add(issue);
            for (int i = 0; i < singleResponses.length; i++) {
                SingleResp singleResp = singleResponses[i];
                if (!respSigner.isValidOn(singleResp.getThisUpdate())) {
                    issue.setFailureMessage(String.format("responder certificate is not valid on the thisUpdate[%d]: %s", i, singleResp.getThisUpdate()));
                }
            }
            // end for
            X509Certificate respIssuer = responseOption.getRespIssuer();
            if (!issue.isFailed() && respIssuer != null) {
                X509Certificate jceRespSigner;
                try {
                    jceRespSigner = X509Util.toX509Cert(respSigner.toASN1Structure());
                    if (X509Util.issues(respIssuer, jceRespSigner)) {
                        jceRespSigner.verify(respIssuer.getPublicKey());
                    } else {
                        issue.setFailureMessage("responder signer is not trusted");
                    }
                } catch (Exception ex) {
                    issue.setFailureMessage("responder signer is not trusted");
                }
            }
            try {
                PublicKey responderPubKey = KeyUtil.generatePublicKey(respSigner.getSubjectPublicKeyInfo());
                ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(responderPubKey);
                boolean sigValid = basicResp.isSignatureValid(cvp);
                if (!sigValid) {
                    sigValIssue.setFailureMessage("signature is invalid");
                }
            } catch (Exception ex) {
                sigValIssue.setFailureMessage("could not validate signature");
            }
        }
    // end if
    }
    // end if (hasSignature)
    // nonce
    Extension nonceExtn = basicResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
    resultIssues.add(checkOccurrence("OCSP.NONCE", nonceExtn, responseOption.getNonceOccurrence()));
    boolean extendedRevoke = basicResp.getExtension(ObjectIdentifiers.id_pkix_ocsp_extendedRevoke) != null;
    for (int i = 0; i < singleResponses.length; i++) {
        SingleResp singleResp = singleResponses[i];
        BigInteger serialNumber = singleResp.getCertID().getSerialNumber();
        OcspCertStatus expectedStatus = expectedOcspStatuses.get(serialNumber);
        Date expectedRevTime = null;
        if (expectedRevTimes != null) {
            expectedRevTime = expectedRevTimes.get(serialNumber);
        }
        byte[] encodedCert = null;
        if (encodedCerts != null) {
            encodedCert = encodedCerts.get(serialNumber);
        }
        List<ValidationIssue> issues = checkSingleCert(i, singleResp, issuerHash, expectedStatus, encodedCert, expectedRevTime, extendedRevoke, responseOption.getNextUpdateOccurrence(), responseOption.getCerthashOccurrence(), responseOption.getCerthashAlgId());
        resultIssues.addAll(issues);
    }
    return new ValidationResult(resultIssues);
}
Also used : ResponderID(org.bouncycastle.asn1.ocsp.ResponderID) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X500Name(org.bouncycastle.asn1.x500.X500Name) ValidationResult(org.xipki.common.qa.ValidationResult) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) PublicKey(java.security.PublicKey) ValidationIssue(org.xipki.common.qa.ValidationIssue) LinkedList(java.util.LinkedList) X509Certificate(java.security.cert.X509Certificate) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Date(java.util.Date) Extension(org.bouncycastle.asn1.x509.Extension) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger)

Example 99 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project xipki by xipki.

the class X509CaCmpResponderImpl method verifyPopo.

// method revokePendingCertificates
private boolean verifyPopo(CertificateRequestMessage certRequest, boolean allowRaPopo) {
    int popType = certRequest.getProofOfPossessionType();
    if (popType == CertificateRequestMessage.popRaVerified && allowRaPopo) {
        return true;
    }
    if (popType != CertificateRequestMessage.popSigningKey) {
        LOG.error("unsupported POP type: " + popType);
        return false;
    }
    // check the POP signature algorithm
    ProofOfPossession pop = certRequest.toASN1Structure().getPopo();
    POPOSigningKey popoSign = POPOSigningKey.getInstance(pop.getObject());
    AlgorithmIdentifier popoAlgId = popoSign.getAlgorithmIdentifier();
    AlgorithmValidator algoValidator = getCmpControl().getPopoAlgoValidator();
    if (!algoValidator.isAlgorithmPermitted(popoAlgId)) {
        String algoName;
        try {
            algoName = AlgorithmUtil.getSignatureAlgoName(popoAlgId);
        } catch (NoSuchAlgorithmException ex) {
            algoName = popoAlgId.getAlgorithm().getId();
        }
        LOG.error("POPO signature algorithm {} not permitted", algoName);
        return false;
    }
    try {
        PublicKey publicKey = securityFactory.generatePublicKey(certRequest.getCertTemplate().getPublicKey());
        ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(publicKey);
        return certRequest.isValidSigningKeyPOP(cvp);
    } catch (InvalidKeyException | IllegalStateException | CRMFException ex) {
        LogUtil.error(LOG, ex);
    }
    return false;
}
Also used : AlgorithmValidator(org.xipki.security.AlgorithmValidator) PublicKey(java.security.PublicKey) ProofOfPossession(org.bouncycastle.asn1.crmf.ProofOfPossession) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) CRMFException(org.bouncycastle.cert.crmf.CRMFException) POPOSigningKey(org.bouncycastle.asn1.crmf.POPOSigningKey) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Example 100 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project xipki by xipki.

the class CsrGenAction method execute0.

@Override
protected Object execute0() throws Exception {
    hashAlgo = hashAlgo.trim().toUpperCase();
    if (hashAlgo.indexOf('-') != -1) {
        hashAlgo = hashAlgo.replaceAll("-", "");
    }
    if (needExtensionTypes == null) {
        needExtensionTypes = new LinkedList<>();
    }
    if (wantExtensionTypes == null) {
        wantExtensionTypes = new LinkedList<>();
    }
    // SubjectAltNames
    List<Extension> extensions = new LinkedList<>();
    ASN1OctetString extnValue = createExtnValueSubjectAltName();
    if (extnValue != null) {
        ASN1ObjectIdentifier oid = Extension.subjectAlternativeName;
        extensions.add(new Extension(oid, false, extnValue));
        needExtensionTypes.add(oid.getId());
    }
    // SubjectInfoAccess
    extnValue = createExtnValueSubjectInfoAccess();
    if (extnValue != null) {
        ASN1ObjectIdentifier oid = Extension.subjectInfoAccess;
        extensions.add(new Extension(oid, false, extnValue));
        needExtensionTypes.add(oid.getId());
    }
    // Keyusage
    if (isNotEmpty(keyusages)) {
        Set<KeyUsage> usages = new HashSet<>();
        for (String usage : keyusages) {
            usages.add(KeyUsage.getKeyUsage(usage));
        }
        org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages);
        ASN1ObjectIdentifier extType = Extension.keyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }
    // ExtendedKeyusage
    if (isNotEmpty(extkeyusages)) {
        ExtendedKeyUsage extValue = X509Util.createExtendedUsage(textToAsn1ObjectIdentifers(extkeyusages));
        ASN1ObjectIdentifier extType = Extension.extendedKeyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }
    // QcEuLimitValue
    if (isNotEmpty(qcEuLimits)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (String m : qcEuLimits) {
            StringTokenizer st = new StringTokenizer(m, ":");
            try {
                String currencyS = st.nextToken();
                String amountS = st.nextToken();
                String exponentS = st.nextToken();
                Iso4217CurrencyCode currency;
                try {
                    int intValue = Integer.parseInt(currencyS);
                    currency = new Iso4217CurrencyCode(intValue);
                } catch (NumberFormatException ex) {
                    currency = new Iso4217CurrencyCode(currencyS);
                }
                int amount = Integer.parseInt(amountS);
                int exponent = Integer.parseInt(exponentS);
                MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent);
                QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue, monterayValue);
                vec.add(statment);
            } catch (Exception ex) {
                throw new Exception("invalid qc-eu-limit '" + m + "'");
            }
        }
        ASN1ObjectIdentifier extType = Extension.qCStatements;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }
    // biometricInfo
    if (biometricType != null && biometricHashAlgo != null && biometricFile != null) {
        TypeOfBiometricData tmpBiometricType = StringUtil.isNumber(biometricType) ? new TypeOfBiometricData(Integer.parseInt(biometricType)) : new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType));
        ASN1ObjectIdentifier tmpBiometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo);
        byte[] biometricBytes = IoUtil.read(biometricFile);
        MessageDigest md = MessageDigest.getInstance(tmpBiometricHashAlgo.getId());
        md.reset();
        byte[] tmpBiometricDataHash = md.digest(biometricBytes);
        DERIA5String tmpSourceDataUri = null;
        if (biometricUri != null) {
            tmpSourceDataUri = new DERIA5String(biometricUri);
        }
        BiometricData biometricData = new BiometricData(tmpBiometricType, new AlgorithmIdentifier(tmpBiometricHashAlgo), new DEROctetString(tmpBiometricDataHash), tmpSourceDataUri);
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(biometricData);
        ASN1ObjectIdentifier extType = Extension.biometricInfo;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    } else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) {
    // Do nothing
    } else {
        throw new Exception("either all of biometric triples (type, hash algo, file)" + " must be set or none of them should be set");
    }
    for (Extension addExt : getAdditionalExtensions()) {
        extensions.add(addExt);
    }
    needExtensionTypes.addAll(getAdditionalNeedExtensionTypes());
    wantExtensionTypes.addAll(getAdditionalWantExtensionTypes());
    if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
        ExtensionExistence ee = new ExtensionExistence(textToAsn1ObjectIdentifers(needExtensionTypes), textToAsn1ObjectIdentifers(wantExtensionTypes));
        extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false, ee.toASN1Primitive().getEncoded()));
    }
    ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain, gm));
    Map<ASN1ObjectIdentifier, ASN1Encodable> attributes = new HashMap<>();
    if (CollectionUtil.isNonEmpty(extensions)) {
        attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new Extensions(extensions.toArray(new Extension[0])));
    }
    if (StringUtil.isNotBlank(challengePassword)) {
        attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(challengePassword));
    }
    SubjectPublicKeyInfo subjectPublicKeyInfo;
    if (signer.getCertificate() != null) {
        Certificate cert = Certificate.getInstance(signer.getCertificate().getEncoded());
        subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo();
    } else {
        subjectPublicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signer.getPublicKey());
    }
    X500Name subjectDn = getSubject(subject);
    PKCS10CertificationRequest csr = generateRequest(signer, subjectPublicKeyInfo, subjectDn, attributes);
    File file = new File(outputFilename);
    saveVerbose("saved CSR to file", file, csr.getEncoded());
    return null;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) TypeOfBiometricData(org.bouncycastle.asn1.x509.qualified.TypeOfBiometricData) BiometricData(org.bouncycastle.asn1.x509.qualified.BiometricData) QCStatement(org.bouncycastle.asn1.x509.qualified.QCStatement) HashMap(java.util.HashMap) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.xipki.security.KeyUsage) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) X500Name(org.bouncycastle.asn1.x500.X500Name) Extensions(org.bouncycastle.asn1.x509.Extensions) Iso4217CurrencyCode(org.bouncycastle.asn1.x509.qualified.Iso4217CurrencyCode) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) MessageDigest(java.security.MessageDigest) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) TypeOfBiometricData(org.bouncycastle.asn1.x509.qualified.TypeOfBiometricData) HashSet(java.util.HashSet) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) MonetaryValue(org.bouncycastle.asn1.x509.qualified.MonetaryValue) LinkedList(java.util.LinkedList) BadInputException(org.xipki.security.exception.BadInputException) InvalidOidOrNameException(org.xipki.security.exception.InvalidOidOrNameException) XiSecurityException(org.xipki.security.exception.XiSecurityException) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) Extension(org.bouncycastle.asn1.x509.Extension) StringTokenizer(java.util.StringTokenizer) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) ExtensionExistence(org.xipki.security.ExtensionExistence) SignatureAlgoControl(org.xipki.security.SignatureAlgoControl) File(java.io.File) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) Certificate(org.bouncycastle.asn1.x509.Certificate)

Aggregations

AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)111 IOException (java.io.IOException)47 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)35 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)35 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)32 BigInteger (java.math.BigInteger)29 X509Certificate (java.security.cert.X509Certificate)27 X500Name (org.bouncycastle.asn1.x500.X500Name)27 DEROctetString (org.bouncycastle.asn1.DEROctetString)21 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)20 KeyPair (java.security.KeyPair)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)19 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)19 Date (java.util.Date)18 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)18 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)17 DERSequence (org.bouncycastle.asn1.DERSequence)16 KeyPairGenerator (java.security.KeyPairGenerator)15 PublicKey (java.security.PublicKey)14 InvalidKeyException (java.security.InvalidKeyException)13