Example usage for org.bouncycastle.asn1 DEROctetString DEROctetString

List of usage examples for org.bouncycastle.asn1 DEROctetString DEROctetString

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 DEROctetString DEROctetString.

Prototype

public DEROctetString(ASN1Encodable obj) throws IOException 

Source Link

Document

Constructor from the encoding of an ASN.1 object.

Usage

From source file:org.xipki.commons.remotep11.server.CmpResponder.java

License:Open Source License

private PKIMessage doProcessPkiMessage(final LocalP11CryptServicePool p11CryptServicePool,
        final String moduleName, final InfoTypeAndValue itv, final PKIHeader respHeader)
        throws BadAsn1ObjectException, P11TokenException, CertificateException, XiSecurityException,
        InvalidKeyException {//  ww w  . jav a 2  s . c  o  m
    ASN1Sequence seq = Asn1Util.getSequence(itv.getInfoValue());
    Asn1Util.requireRange(seq, 3, 3);
    int protocolVersion = Asn1Util.getInteger(seq.getObjectAt(0)).intValue();
    int action = Asn1Util.getInteger(seq.getObjectAt(1)).intValue();
    ASN1Encodable reqValue = seq.getObjectAt(2);

    P11CryptService p11CryptService = p11CryptServicePool.getP11CryptService(moduleName);
    ASN1Encodable respItvInfoValue = null;

    if (P11ProxyConstants.ACTION_addCert == action) {
        Asn1EntityIdAndCert asn1 = Asn1EntityIdAndCert.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getEntityId());
        X509Certificate cert = X509Util.toX509Cert(asn1.getCertificate());
        slot.addCert(asn1.getEntityId().getObjectId().getObjectId(), cert);
    } else if (P11ProxyConstants.ACTION_genKeypair_DSA == action) {
        Asn1GenDSAKeypairParams asn1 = Asn1GenDSAKeypairParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        P11ObjectIdentifier keyId = slot.generateDSAKeypair(asn1.getP(), asn1.getQ(), asn1.getG(),
                asn1.getLabel());
        respItvInfoValue = new Asn1P11EntityIdentifier(asn1.getSlotId().getSlotId(), keyId);
    } else if (P11ProxyConstants.ACTION_genKeypair_EC == action) {
        Asn1GenECKeypairParams asn1 = Asn1GenECKeypairParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        P11ObjectIdentifier keyId = slot.generateECKeypair(asn1.getCurveId().getId(), asn1.getLabel());
        respItvInfoValue = new Asn1P11EntityIdentifier(asn1.getSlotId().getSlotId(), keyId);
    } else if (P11ProxyConstants.ACTION_genKeypair_RSA == action) {
        Asn1GenRSAKeypairParams asn1 = Asn1GenRSAKeypairParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        P11ObjectIdentifier keyId = slot.generateRSAKeypair(asn1.getKeysize(), asn1.getPublicExponent(),
                asn1.getLabel());
        respItvInfoValue = new Asn1P11EntityIdentifier(asn1.getSlotId().getSlotId(), keyId);
    } else if (P11ProxyConstants.ACTION_getCertificate == action) {
        P11EntityIdentifier entityId = Asn1P11EntityIdentifier.getInstance(reqValue).getEntityId();
        X509Certificate cert = p11CryptService.getIdentity(entityId).getCertificate();
        respItvInfoValue = Certificate.getInstance(cert.getEncoded());
    } else if (P11ProxyConstants.ACTION_getCertIdentifiers == action
            || P11ProxyConstants.ACTION_getIdentityIdentifiers == action) {
        Asn1P11SlotIdentifier slotId = Asn1P11SlotIdentifier.getInstance(reqValue);
        P11Slot slot = p11CryptService.getModule().getSlot(slotId.getSlotId());
        Set<P11ObjectIdentifier> objectIds;
        if (P11ProxyConstants.ACTION_getCertIdentifiers == action) {
            objectIds = slot.getCertIdentifiers();
        } else {
            objectIds = slot.getIdentityIdentifiers();
        }
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (P11ObjectIdentifier objectId : objectIds) {
            vec.add(new Asn1P11ObjectIdentifier(objectId));
        }
        respItvInfoValue = new DERSequence(vec);
    } else if (P11ProxyConstants.ACTION_getMechanisms == action) {
        P11SlotIdentifier slotId = Asn1P11SlotIdentifier.getInstance(reqValue).getSlotId();
        Set<Long> mechs = p11CryptService.getSlot(slotId).getMechanisms();
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (Long mech : mechs) {
            vec.add(new ASN1Integer(mech));
        }
        respItvInfoValue = new DERSequence(vec);
    } else if (P11ProxyConstants.ACTION_getPublicKey == action) {
        P11EntityIdentifier identityId = Asn1P11EntityIdentifier.getInstance(reqValue).getEntityId();
        PublicKey pubKey = p11CryptService.getIdentity(identityId).getPublicKey();
        if (pubKey == null) {
            throw new P11UnknownEntityException(identityId);
        }

        respItvInfoValue = KeyUtil.createSubjectPublicKeyInfo(pubKey);
    } else if (P11ProxyConstants.ACTION_getSlotIds == action) {
        List<P11SlotIdentifier> slotIds = p11CryptService.getModule().getSlotIdentifiers();

        ASN1EncodableVector vector = new ASN1EncodableVector();
        for (P11SlotIdentifier slotId : slotIds) {
            vector.add(new Asn1P11SlotIdentifier(slotId));
        }
        respItvInfoValue = new DERSequence(vector);
    } else if (P11ProxyConstants.ACTION_removeCerts == action) {
        Asn1P11EntityIdentifier asn1 = Asn1P11EntityIdentifier.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1);
        slot.removeCerts(asn1.getObjectId().getObjectId());
    } else if (P11ProxyConstants.ACTION_removeIdentity == action) {
        Asn1P11EntityIdentifier asn1 = Asn1P11EntityIdentifier.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1);
        slot.removeIdentity(asn1.getObjectId().getObjectId());
    } else if (P11ProxyConstants.ACTION_sign == action) {
        Asn1SignTemplate signTemplate = Asn1SignTemplate.getInstance(reqValue);
        long mechanism = signTemplate.getMechanism().getMechanism();
        Asn1P11Params tmpParams = signTemplate.getMechanism().getParams();
        ASN1Encodable asn1Params = null;
        if (tmpParams != null) {
            asn1Params = tmpParams.getP11Params();
        }
        P11Params params = null;
        if (asn1Params instanceof Asn1RSAPkcsPssParams) {
            params = Asn1RSAPkcsPssParams.getInstance(asn1Params).getPkcsPssParams();
        } else if (asn1Params != null) {
            throw new BadAsn1ObjectException("unknown SignTemplate.params");
        }

        byte[] content = signTemplate.getMessage();
        P11Identity identity = p11CryptService.getIdentity(signTemplate.getIdentityId().getEntityId());
        byte[] signature = identity.sign(mechanism, params, content);
        respItvInfoValue = new DEROctetString(signature);
    } else if (P11ProxyConstants.ACTION_updateCerificate == action) {
        Asn1EntityIdAndCert asn1 = Asn1EntityIdAndCert.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getEntityId());
        slot.updateCertificate(asn1.getEntityId().getObjectId().getObjectId(),
                X509Util.toX509Cert(asn1.getCertificate()));
    } else if (P11ProxyConstants.ACTION_removeObjects == action) {
        Asn1RemoveObjectsParams asn1 = Asn1RemoveObjectsParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        int num = slot.removeObjects(asn1.getObjectId(), asn1.getObjectLabel());
        respItvInfoValue = new ASN1Integer(num);
    } else {
        final String statusMessage = "unsupported XiPKI action code '" + action + "'";
        return createRejectionPkiMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
    }

    ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(new ASN1Integer(protocolVersion));
    vec.add(new ASN1Integer(action));
    if (respItvInfoValue != null) {
        vec.add(respItvInfoValue);
    }

    InfoTypeAndValue respItv = new InfoTypeAndValue(ObjectIdentifiers.id_xipki_cmp_cmpGenmsg,
            new DERSequence(vec));
    GenRepContent genRepContent = new GenRepContent(respItv);
    PKIBody respBody = new PKIBody(PKIBody.TYPE_GEN_REP, genRepContent);
    return new PKIMessage(respHeader, respBody);
}

From source file:org.xipki.commons.security.pkcs11.emulator.EmulatorP11Slot.java

License:Open Source License

private void savePkcs11PublicKey(final byte[] id, final String label, final PublicKey publicKey)
        throws P11TokenException {
    String hexId = Hex.toHexString(id).toLowerCase();

    StringBuilder sb = new StringBuilder(100);
    sb.append(PROP_ID).append('=').append(hexId).append('\n');
    sb.append(PROP_LABEL).append('=').append(label).append('\n');

    if (publicKey instanceof RSAPublicKey) {
        sb.append(PROP_ALGORITHM).append('=');
        sb.append(PKCSObjectIdentifiers.rsaEncryption.getId());
        sb.append('\n');

        sb.append(PROP_RSA_MODUS).append('=');

        RSAPublicKey rsaKey = (RSAPublicKey) publicKey;
        sb.append(Hex.toHexString(rsaKey.getModulus().toByteArray()));
        sb.append('\n');

        sb.append(PROP_RSA_PUBLIC_EXPONENT).append('=');
        sb.append(Hex.toHexString(rsaKey.getPublicExponent().toByteArray()));
        sb.append('\n');
    } else if (publicKey instanceof DSAPublicKey) {
        sb.append(PROP_ALGORITHM).append('=');
        sb.append(X9ObjectIdentifiers.id_dsa.getId());
        sb.append('\n');

        sb.append(PROP_DSA_PRIME).append('=');
        DSAPublicKey dsaKey = (DSAPublicKey) publicKey;
        sb.append(Hex.toHexString(dsaKey.getParams().getP().toByteArray()));
        sb.append('\n');

        sb.append(PROP_DSA_SUBPRIME).append('=');
        sb.append(Hex.toHexString(dsaKey.getParams().getQ().toByteArray()));
        sb.append('\n');

        sb.append(PROP_DSA_BASE).append('=');
        sb.append(Hex.toHexString(dsaKey.getParams().getG().toByteArray()));
        sb.append('\n');

        sb.append(PROP_DSA_VALUE).append('=');
        sb.append(Hex.toHexString(dsaKey.getY().toByteArray()));
        sb.append('\n');
    } else if (publicKey instanceof ECPublicKey) {
        sb.append(PROP_ALGORITHM).append('=');
        sb.append(X9ObjectIdentifiers.id_ecPublicKey.getId());
        sb.append('\n');

        ECPublicKey ecKey = (ECPublicKey) publicKey;
        ECParameterSpec paramSpec = ecKey.getParams();

        // ecdsaParams
        org.bouncycastle.jce.spec.ECParameterSpec bcParamSpec = EC5Util.convertSpec(paramSpec, false);
        ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(bcParamSpec);
        if (curveOid == null) {
            throw new P11TokenException("EC public key is not of namedCurve");
        }/*w ww .ja  va 2  s . c  o m*/

        byte[] encodedParams;
        try {
            if (namedCurveSupported) {
                encodedParams = curveOid.getEncoded();
            } else {
                encodedParams = ECNamedCurveTable.getByOID(curveOid).getEncoded();
            }
        } catch (IOException | NullPointerException ex) {
            throw new P11TokenException(ex.getMessage(), ex);
        }

        sb.append(PROP_EC_ECDSA_PARAMS).append('=');
        sb.append(Hex.toHexString(encodedParams));
        sb.append('\n');

        // EC point
        java.security.spec.ECPoint pointW = ecKey.getW();
        int keysize = (paramSpec.getOrder().bitLength() + 7) / 8;
        byte[] ecPoint = new byte[1 + keysize * 2];
        ecPoint[0] = 4; // uncompressed
        bigIntToBytes("Wx", pointW.getAffineX(), ecPoint, 1, keysize);
        bigIntToBytes("Wy", pointW.getAffineY(), ecPoint, 1 + keysize, keysize);

        byte[] encodedEcPoint;
        try {
            encodedEcPoint = new DEROctetString(ecPoint).getEncoded();
        } catch (IOException ex) {
            throw new P11TokenException("could not ASN.1 encode the ECPoint");
        }
        sb.append(PROP_EC_EC_POINT).append('=');
        sb.append(Hex.toHexString(encodedEcPoint));
        sb.append('\n');
    } else {
        throw new IllegalArgumentException("unsupported public key " + publicKey.getClass().getName());
    }

    try {
        IoUtil.save(new File(pubKeyDir, hexId + INFO_FILE_SUFFIX), sb.toString().getBytes());
    } catch (IOException ex) {
        throw new P11TokenException(ex.getMessage(), ex);
    }
}

From source file:org.xipki.commons.security.pkcs11.proxy.Asn1P11ObjectIdentifier.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(new DEROctetString(objectId.getId()));
    vec.add(new DERUTF8String(objectId.getLabel()));
    return new DERSequence(vec);
}

From source file:org.xipki.commons.security.pkcs11.proxy.Asn1SignTemplate.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vector = new ASN1EncodableVector();
    vector.add(identityId);// ww w.  j a  v a2s. c  o  m
    vector.add(mechanism);
    vector.add(new DEROctetString(message));
    return new DERSequence(vector);
}

From source file:org.xipki.commons.security.pkcs11.proxy.ProxyP11Module.java

License:Open Source License

private PKIHeader buildPkiHeader(final ASN1OctetString tid) {
    PKIHeaderBuilder hdrBuilder = new PKIHeaderBuilder(PKIHeader.CMP_2000, sender, recipient);
    hdrBuilder.setMessageTime(new ASN1GeneralizedTime(new Date()));

    ASN1OctetString tmpTid = (tid == null) ? new DEROctetString(randomTransactionId()) : tid;
    hdrBuilder.setTransactionID(tmpTid);

    return hdrBuilder.build();
}

From source file:org.xipki.commons.security.shell.CertRequestGenCommandSupport.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    hashAlgo = hashAlgo.trim().toUpperCase();
    if (hashAlgo.indexOf('-') != -1) {
        hashAlgo = hashAlgo.replaceAll("-", "");
    }//from  ww  w .  j  a  v  a  2 s. com

    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));

    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;
}

From source file:org.xipki.commons.security.shell.p12.P12ComplexCertRequestGenCmd.java

License:Open Source License

@Override
protected ASN1OctetString createExtnValueSubjectAltName() throws BadInputException {
    if (!isEmpty(subjectAltNames)) {
        throw new BadInputException("subjectAltNames must be null");
    }/*from w w w. ja v a2  s.co  m*/
    GeneralNames names = createComplexGeneralNames("SAN-");
    try {
        return new DEROctetString(names);
    } catch (IOException ex) {
        throw new BadInputException(ex.getMessage(), ex);
    }
}

From source file:org.xipki.commons.security.shell.p12.P12ComplexCertRequestGenCmd.java

License:Open Source License

@Override
protected ASN1OctetString createExtnValueSubjectInfoAccess() throws BadInputException {
    if (!isEmpty(subjectInfoAccesses)) {
        throw new BadInputException("subjectInfoAccess must be null");
    }/*from   w w w  .j  a v a2  s . c om*/
    ASN1EncodableVector vec = new ASN1EncodableVector();

    GeneralName[] names = createComplexGeneralNames("SIA-").getNames();

    ASN1EncodableVector vec2 = new ASN1EncodableVector();
    vec2.add(ObjectIdentifiers.id_ad_caRepository);
    vec2.add(names[0]);
    vec.add(new DERSequence(vec2));

    for (int i = 1; i < names.length; i++) {
        vec2 = new ASN1EncodableVector();
        vec2.add(new ASN1ObjectIdentifier("2.3.4." + i));
        vec2.add(names[i]);
        vec.add(new DERSequence(vec2));
    }

    try {
        return new DEROctetString(new DERSequence(vec));
    } catch (IOException ex) {
        throw new BadInputException(ex.getMessage(), ex);
    }
}

From source file:org.xipki.ocsp.client.impl.AbstractOCSPRequestor.java

License:Open Source License

private OCSPReq buildRequest(final X509Certificate caCert, final BigInteger[] serialNumbers, final byte[] nonce,
        final RequestOptions requestOptions) throws OCSPRequestorException {
    ASN1ObjectIdentifier hashAlgId = requestOptions.getHashAlgorithmId();
    List<AlgorithmIdentifier> prefSigAlgs = requestOptions.getPreferredSignatureAlgorithms();

    DigestCalculator digestCalculator;/*ww  w.jav  a 2  s. c o  m*/
    if (NISTObjectIdentifiers.id_sha224.equals(hashAlgId)) {
        digestCalculator = new SHA224DigestCalculator();
    } else if (NISTObjectIdentifiers.id_sha256.equals(hashAlgId)) {
        digestCalculator = new SHA256DigestCalculator();
    } else if (NISTObjectIdentifiers.id_sha384.equals(hashAlgId)) {
        digestCalculator = new SHA384DigestCalculator();
    } else if (NISTObjectIdentifiers.id_sha512.equals(hashAlgId)) {
        digestCalculator = new SHA512DigestCalculator();
    } else {
        digestCalculator = new SHA1DigestCalculator();
    }

    OCSPReqBuilder reqBuilder = new OCSPReqBuilder();
    List<Extension> extensions = new LinkedList<>();
    if (nonce != null) {
        Extension extn = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                new DEROctetString(nonce));
        extensions.add(extn);
    }

    if (prefSigAlgs != null && prefSigAlgs.size() > 0) {
        ASN1EncodableVector v = new ASN1EncodableVector();
        for (AlgorithmIdentifier algId : prefSigAlgs) {
            ASN1Sequence prefSigAlgObj = new DERSequence(algId);
            v.add(prefSigAlgObj);
        }

        ASN1Sequence extnValue = new DERSequence(v);
        Extension extn;
        try {
            extn = new Extension(id_pkix_ocsp_prefSigAlgs, false, new DEROctetString(extnValue));
        } catch (IOException e) {
            throw new OCSPRequestorException(e.getMessage(), e);
        }
        extensions.add(extn);
    }

    if (CollectionUtil.isNotEmpty(extensions)) {
        reqBuilder.setRequestExtensions(new Extensions(extensions.toArray(new Extension[0])));
    }

    try {
        for (BigInteger serialNumber : serialNumbers) {
            CertificateID certID = new CertificateID(digestCalculator,
                    new X509CertificateHolder(caCert.getEncoded()), 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 e) {
                            throw new OCSPRequestorException(
                                    "could not parse certificate " + signerCertFile + ": " + e.getMessage());
                        }
                    }

                    try {
                        signer = getSecurityFactory().createSigner(signerType, signerConf, cert);
                    } catch (Exception e) {
                        throw new OCSPRequestorException("could not create signer: " + e.getMessage());
                    }
                }
            }

            ContentSigner singleSigner;
            try {
                singleSigner = signer.borrowContentSigner();
            } catch (NoIdleSignerException e) {
                throw new OCSPRequestorException("NoIdleSignerException: " + e.getMessage());
            }

            reqBuilder.setRequestorName(signer.getCertificateAsBCObject().getSubject());
            try {
                return reqBuilder.build(singleSigner, signer.getCertificateChainAsBCObjects());
            } finally {
                signer.returnContentSigner(singleSigner);
            }
        } else {
            return reqBuilder.build();
        }
    } catch (OCSPException | CertificateEncodingException | IOException e) {
        throw new OCSPRequestorException(e.getMessage(), e);
    }
}

From source file:org.xipki.pki.ca.certprofile.commonpki.AdmissionSyntaxOption.java

License:Open Source License

public AdmissionSyntaxOption(final boolean critical, final GeneralName admissionAuthority,
        final List<AdmissionsOption> admissionsList) {
    this.critical = critical;
    this.admissionAuthority = admissionAuthority;
    this.admissionsList = ParamUtil.requireNonEmpty("admissionsList", admissionsList);

    boolean bo = false;
    for (AdmissionsOption ao : admissionsList) {
        for (ProfessionInfoOption pio : ao.getProfessionInfos()) {
            if (pio.getRegistrationNumberOption() != null
                    && pio.getRegistrationNumberOption().getRegex() != null) {
                bo = true;//from w  w w.  j  a v  a  2 s .  c  o m
                break;
            }
        }
        if (bo) {
            break;
        }
    }
    this.inputFromRequestRequired = bo;
    if (this.inputFromRequestRequired) {
        extensionValue = null;
        return;
    }

    ASN1EncodableVector vec = new ASN1EncodableVector();
    for (AdmissionsOption ao : admissionsList) {
        List<ProfessionInfoOption> piList = ao.getProfessionInfos();
        ProfessionInfo[] pis = new ProfessionInfo[piList.size()];

        for (int i = 0; i < pis.length; i++) {
            ProfessionInfoOption pio = piList.get(i);
            DirectoryString[] professionItems = null;
            int size = pio.getProfessionItems().size();
            professionItems = new DirectoryString[size];
            for (int j = 0; j < size; j++) {
                professionItems[j] = new DirectoryString(pio.getProfessionItems().get(j));
            }

            ASN1OctetString addProfessionInfo = null;
            if (pio.getAddProfessionalInfo() != null) {
                addProfessionInfo = new DEROctetString(pio.getAddProfessionalInfo());
            }

            String registrationNumber = null;
            if (pio.getRegistrationNumberOption() != null) {
                registrationNumber = pio.getRegistrationNumberOption().getConstant();
            }
            pis[i] = new ProfessionInfo(pio.getNamingAuthority(), professionItems,
                    pio.getProfessionOids().toArray(new ASN1ObjectIdentifier[0]), registrationNumber,
                    addProfessionInfo);
        }

        vec.add(new Admissions(ao.getAdmissionAuthority(), ao.getNamingAuthority(), pis));
    }

    extensionValue = new ExtensionValue(critical,
            new AdmissionSyntax(admissionAuthority, new DERSequence(vec)));
}