Example usage for org.bouncycastle.asn1 ASN1Integer ASN1Integer

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

Introduction

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

Prototype

public ASN1Integer(byte[] bytes) 

Source Link

Document

Construct an INTEGER from the passed in byte array.

Usage

From source file:org.xipki.ca.client.impl.X509CmpRequestor.java

License:Open Source License

public CRLResultType downloadCRL(final BigInteger crlNumber, final RequestResponseDebug debug)
        throws CmpRequestorException, PKIErrorException {
    Integer action = null;/*ww w .  j ava 2s .  com*/
    PKIMessage request;
    if (crlNumber == null) {
        ASN1ObjectIdentifier type = CMPObjectIdentifiers.it_currentCRL;
        request = buildMessageWithGeneralMsgContent(type, null);
    } else {
        action = XipkiCmpConstants.ACTION_GET_CRL_WITH_SN;
        request = buildMessageWithXipkAction(action, new ASN1Integer(crlNumber));
    }

    PKIResponse response = signAndSend(request, debug);
    return evaluateCRLResponse(response, action);
}

From source file:org.xipki.ca.client.impl.X509CmpRequestor.java

License:Open Source License

private PKIMessage buildRevokeCertRequest(final RevokeCertRequestType request) throws CmpRequestorException {
    PKIHeader header = buildPKIHeader(null);

    List<RevokeCertRequestEntryType> requestEntries = request.getRequestEntries();
    List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
    for (RevokeCertRequestEntryType requestEntry : requestEntries) {
        CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
        certTempBuilder.setIssuer(requestEntry.getIssuer());
        certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));

        Date invalidityDate = requestEntry.getInvalidityDate();
        Extension[] extensions = new Extension[invalidityDate == null ? 1 : 2];

        try {/*  ww  w.ja  v  a2 s .  c  om*/
            ASN1Enumerated reason = new ASN1Enumerated(requestEntry.getReason());
            extensions[0] = new Extension(Extension.reasonCode, true, new DEROctetString(reason.getEncoded()));

            if (invalidityDate != null) {
                ASN1GeneralizedTime time = new ASN1GeneralizedTime(invalidityDate);
                extensions[1] = new Extension(Extension.invalidityDate, true,
                        new DEROctetString(time.getEncoded()));
            }
        } catch (IOException e) {
            throw new CmpRequestorException(e.getMessage(), e);
        }
        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);
}

From source file:org.xipki.ca.client.impl.X509CmpRequestor.java

License:Open Source License

private PKIMessage buildUnrevokeOrRemoveCertRequest(final UnrevokeOrRemoveCertRequestType request,
        final int reasonCode) throws CmpRequestorException {
    PKIHeader header = buildPKIHeader(null);

    List<IssuerSerialEntryType> requestEntries = request.getRequestEntries();
    List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
    for (IssuerSerialEntryType requestEntry : requestEntries) {
        CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
        certTempBuilder.setIssuer(requestEntry.getIssuer());
        certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));

        Extension[] extensions = new Extension[1];

        try {//from   w  w  w  . j  av  a  2s. c  om
            ASN1Enumerated reason = new ASN1Enumerated(reasonCode);
            extensions[0] = new Extension(Extension.reasonCode, true, new DEROctetString(reason.getEncoded()));
        } catch (IOException e) {
            throw new CmpRequestorException(e.getMessage(), e);
        }
        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);
}

From source file:org.xipki.ca.client.impl.X509CmpRequestor.java

License:Open Source License

public CAInfo retrieveCAInfo(final String caName, final RequestResponseDebug debug)
        throws CmpRequestorException, PKIErrorException {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(2));
    ASN1Sequence acceptVersions = new DERSequence(v);

    int action = XipkiCmpConstants.ACTION_GET_CAINFO;
    PKIMessage request = buildMessageWithXipkAction(action, acceptVersions);
    PKIResponse response = signAndSend(request, debug);
    ASN1Encodable itvValue = extractXipkiActionRepContent(response, action);
    DERUTF8String utf8Str = DERUTF8String.getInstance(itvValue);
    String systemInfoStr = utf8Str.getString();

    LOG.debug("CAInfo for CA {}: {}", caName, systemInfoStr);
    Document doc;//from ww w .j  a  v  a 2  s .  co m
    try {
        doc = xmlDocBuilder.parse(new ByteArrayInputStream(systemInfoStr.getBytes("UTF-8")));
    } catch (SAXException | IOException e) {
        throw new CmpRequestorException(
                "could not parse the returned systemInfo for CA " + caName + ": " + e.getMessage(), e);
    }

    final String namespace = null;
    Element root = doc.getDocumentElement();
    String s = root.getAttribute("version");
    if (StringUtil.isBlank(s)) {
        s = root.getAttributeNS(namespace, "version");
    }

    int version = StringUtil.isBlank(s) ? 1 : Integer.parseInt(s);

    if (version == 2) {
        X509Certificate caCert;

        String b64CACert = XMLUtil.getValueOfFirstElementChild(root, namespace, "CACert");
        try {
            caCert = X509Util.parseBase64EncodedCert(b64CACert);
        } catch (CertificateException | IOException e) {
            throw new CmpRequestorException("could no parse the CA certificate", e);
        }

        Element profilesElement = XMLUtil.getFirstElementChild(root, namespace, "certprofiles");
        Set<CertprofileInfo> profiles = new HashSet<>();
        Set<String> profileNames = new HashSet<>();
        if (profilesElement != null) {
            List<Element> profileElements = XMLUtil.getElementChilden(profilesElement, namespace,
                    "certprofile");

            for (Element element : profileElements) {
                String name = XMLUtil.getValueOfFirstElementChild(element, namespace, "name");
                String type = XMLUtil.getValueOfFirstElementChild(element, namespace, "type");
                String conf = XMLUtil.getValueOfFirstElementChild(element, namespace, "conf");
                CertprofileInfo profile = new CertprofileInfo(name, type, conf);
                profiles.add(profile);
                profileNames.add(name);
                if (LOG.isDebugEnabled()) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("configured for CA ").append(caName).append(" certprofile (");
                    sb.append("name=").append(name).append(", ");
                    sb.append("type=").append(type).append(", ");
                    sb.append("conf=").append(conf).append(")");
                    LOG.debug(sb.toString());
                }
            }
        }

        LOG.info("CA {} supports profiles {}", caName, profileNames);
        return new CAInfo(caCert, profiles);
    } else {
        throw new CmpRequestorException("unknown CAInfo version " + version);
    }
}

From source file:org.xipki.ca.server.impl.X509CA.java

License:Open Source License

private X509CRL generateCRL(final boolean deltaCRL, final Date thisUpdate, final Date nextUpdate,
        final AuditEvent auditEvent) throws OperationException {
    X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
    if (crlSigner == null) {
        throw new OperationException(ErrorCode.INSUFFICIENT_PERMISSION, "CRL generation is not allowed");
    }//from   www . ja  v a2 s .c  o m

    LOG.info("     START generateCRL: ca={}, deltaCRL={}, nextUpdate={}",
            new Object[] { caInfo.getName(), deltaCRL, nextUpdate });

    if (auditEvent != null) {
        auditEvent.addEventData(new AuditEventData("crlType", deltaCRL ? "DELTA_CRL" : "FULL_CRL"));
        if (nextUpdate != null) {
            String value;
            synchronized (dateFormat) {
                value = dateFormat.format(nextUpdate);
            }
            auditEvent.addEventData(new AuditEventData("nextUpdate", value));
        } else {
            auditEvent.addEventData(new AuditEventData("nextUpdate", "NULL"));
        }
    }

    if (nextUpdate != null) {
        if (nextUpdate.getTime() - thisUpdate.getTime() < 10 * 60 * MS_PER_SECOND) {
            // less than 10 minutes
            throw new OperationException(ErrorCode.CRL_FAILURE, "nextUpdate and thisUpdate are too close");
        }
    }

    CRLControl crlControl = crlSigner.getCRLControl();
    boolean successfull = false;

    try {
        ConcurrentContentSigner _crlSigner = crlSigner.getSigner();

        CRLControl control = crlSigner.getCRLControl();

        boolean directCRL = _crlSigner == null;
        X500Name crlIssuer = directCRL ? caInfo.getPublicCAInfo().getX500Subject()
                : X500Name.getInstance(_crlSigner.getCertificate().getSubjectX500Principal().getEncoded());

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(crlIssuer, thisUpdate);
        if (nextUpdate != null) {
            crlBuilder.setNextUpdate(nextUpdate);
        }

        BigInteger startSerial = BigInteger.ONE;
        final int numEntries = 100;

        X509CertWithDBCertId caCert = caInfo.getCertificate();
        List<CertRevInfoWithSerial> revInfos;
        boolean isFirstCRLEntry = true;

        Date notExpireAt;
        if (control.isIncludeExpiredCerts()) {
            notExpireAt = new Date(0);
        } else {
            // 10 minutes buffer
            notExpireAt = new Date(thisUpdate.getTime() - 600L * MS_PER_SECOND);
        }

        do {
            if (deltaCRL) {
                revInfos = certstore.getCertificatesForDeltaCRL(caCert, startSerial, numEntries,
                        control.isOnlyContainsCACerts(), control.isOnlyContainsUserCerts());
            } else {
                revInfos = certstore.getRevokedCertificates(caCert, notExpireAt, startSerial, numEntries,
                        control.isOnlyContainsCACerts(), control.isOnlyContainsUserCerts());
            }

            BigInteger maxSerial = BigInteger.ONE;

            for (CertRevInfoWithSerial revInfo : revInfos) {
                BigInteger serial = revInfo.getSerial();
                if (serial.compareTo(maxSerial) > 0) {
                    maxSerial = serial;
                }

                CRLReason reason = revInfo.getReason();
                Date revocationTime = revInfo.getRevocationTime();
                Date invalidityTime = revInfo.getInvalidityTime();
                if (invalidityTime != null && invalidityTime.equals(revocationTime)) {
                    invalidityTime = null;
                }

                if (directCRL || isFirstCRLEntry == false) {
                    if (invalidityTime != null) {
                        crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, reason.getCode(),
                                invalidityTime);
                    } else {
                        crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, reason.getCode());
                    }
                    continue;
                }

                List<Extension> extensions = new ArrayList<>(3);
                if (reason != CRLReason.UNSPECIFIED) {
                    Extension ext = createReasonExtension(reason.getCode());
                    extensions.add(ext);
                }
                if (invalidityTime != null) {
                    Extension ext = createInvalidityDateExtension(invalidityTime);
                    extensions.add(ext);
                }

                Extension ext = createCertificateIssuerExtension(caInfo.getPublicCAInfo().getX500Subject());
                extensions.add(ext);

                Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0]));
                crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, asn1Extensions);
                isFirstCRLEntry = false;
            } // end for

            startSerial = maxSerial.add(BigInteger.ONE);

        } while (revInfos.size() >= numEntries);
        // end do

        BigInteger crlNumber = caInfo.nextCRLNumber();
        if (auditEvent != null) {
            auditEvent.addEventData(new AuditEventData("crlNumber", crlNumber.toString()));
        }

        boolean onlyUserCerts = crlControl.isOnlyContainsUserCerts();
        boolean onlyCACerts = crlControl.isOnlyContainsCACerts();
        if (onlyUserCerts && onlyCACerts) {
            throw new RuntimeException("should not reach here, onlyUserCerts and onlyCACerts are both true");
        }

        try {
            // AuthorityKeyIdentifier
            byte[] akiValues = directCRL ? caInfo.getPublicCAInfo().getSubjectKeyIdentifer()
                    : crlSigner.getSubjectKeyIdentifier();
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(akiValues);
            crlBuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);

            // add extension CRL Number
            crlBuilder.addExtension(Extension.cRLNumber, false, new ASN1Integer(crlNumber));

            // IssuingDistributionPoint
            if (onlyUserCerts == true || onlyCACerts == true || directCRL == false) {
                IssuingDistributionPoint idp = new IssuingDistributionPoint((DistributionPointName) null, // distributionPoint,
                        onlyUserCerts, // onlyContainsUserCerts,
                        onlyCACerts, // onlyContainsCACerts,
                        (ReasonFlags) null, // onlySomeReasons,
                        directCRL == false, // indirectCRL,
                        false // onlyContainsAttributeCerts
                );

                crlBuilder.addExtension(Extension.issuingDistributionPoint, true, idp);
            }
        } catch (CertIOException e) {
            final String message = "crlBuilder.addExtension";
            if (LOG.isErrorEnabled()) {
                LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
            }
            LOG.debug(message, e);
            throw new OperationException(ErrorCode.INVALID_EXTENSION, e.getMessage());
        }

        startSerial = BigInteger.ONE;
        if (deltaCRL == false && control.isEmbedsCerts()) // XiPKI extension
        {
            ASN1EncodableVector vector = new ASN1EncodableVector();

            List<BigInteger> serials;

            do {
                serials = certstore.getCertSerials(caCert, notExpireAt, startSerial, numEntries, false,
                        onlyCACerts, onlyUserCerts);

                BigInteger maxSerial = BigInteger.ONE;
                for (BigInteger serial : serials) {
                    if (serial.compareTo(maxSerial) > 0) {
                        maxSerial = serial;
                    }

                    X509CertificateInfo certInfo;
                    try {
                        certInfo = certstore.getCertificateInfoForSerial(caCert, serial);
                    } catch (CertificateException e) {
                        throw new OperationException(ErrorCode.SYSTEM_FAILURE,
                                "CertificateException: " + e.getMessage());
                    }

                    Certificate cert = Certificate.getInstance(certInfo.getCert().getEncodedCert());

                    ASN1EncodableVector v = new ASN1EncodableVector();
                    v.add(cert);
                    String profileName = certInfo.getProfileName();
                    if (StringUtil.isNotBlank(profileName)) {
                        v.add(new DERUTF8String(certInfo.getProfileName()));
                    }
                    ASN1Sequence certWithInfo = new DERSequence(v);

                    vector.add(certWithInfo);
                } // end for

                startSerial = maxSerial.add(BigInteger.ONE);
            } while (serials.size() >= numEntries);
            // end fo

            try {
                crlBuilder.addExtension(ObjectIdentifiers.id_xipki_ext_crlCertset, false, new DERSet(vector));
            } catch (CertIOException e) {
                throw new OperationException(ErrorCode.INVALID_EXTENSION, "CertIOException: " + e.getMessage());
            }
        }

        ConcurrentContentSigner concurrentSigner = (_crlSigner == null) ? caInfo.getSigner(null) : _crlSigner;

        ContentSigner contentSigner;
        try {
            contentSigner = concurrentSigner.borrowContentSigner();
        } catch (NoIdleSignerException e) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + e.getMessage());
        }

        X509CRLHolder crlHolder;
        try {
            crlHolder = crlBuilder.build(contentSigner);
        } finally {
            concurrentSigner.returnContentSigner(contentSigner);
        }

        try {
            X509CRL crl = new X509CRLObject(crlHolder.toASN1Structure());
            publishCRL(crl);

            successfull = true;
            LOG.info("SUCCESSFUL generateCRL: ca={}, crlNumber={}, thisUpdate={}",
                    new Object[] { caInfo.getName(), crlNumber, crl.getThisUpdate() });

            if (deltaCRL) {
                return crl;
            }

            // clean up the CRL
            try {
                cleanupCRLs();
            } catch (Throwable t) {
                LOG.warn("could not cleanup CRLs.{}: {}", t.getClass().getName(), t.getMessage());
            }
            return crl;
        } catch (CRLException e) {
            throw new OperationException(ErrorCode.CRL_FAILURE, "CRLException: " + e.getMessage());
        }
    } finally {
        if (successfull == false) {
            LOG.info("    FAILED generateCRL: ca={}", caInfo.getName());
        }
    }
}

From source file:org.xipki.ca.server.impl.X509CACmpResponder.java

License:Open Source License

/**
 * handle the PKI body with the choice {@code p10cr}<br/>
 * Since it is not possible to add attribute to the PKCS#10 request, the certificate profile
 * must be specified in the attribute regInfo-utf8Pairs (1.3.6.1.5.5.7.5.2.1) within
 * PKIHeader.generalInfo/*www  . j a  v a2s .  c  om*/
 *
 */
private PKIBody processP10cr(final CmpRequestorInfo requestor, final String user, final ASN1OctetString tid,
        final PKIHeader reqHeader, final CertificationRequest p10cr, final long confirmWaitTime,
        final boolean sendCaCert, final AuditEvent auditEvent) throws InsuffientPermissionException {
    // verify the POP first
    CertResponse certResp;
    ASN1Integer certReqId = new ASN1Integer(-1);

    AuditChildEvent childAuditEvent = null;
    if (auditEvent != null) {
        childAuditEvent = new AuditChildEvent();
        auditEvent.addChildAuditEvent(childAuditEvent);
    }

    if (securityFactory.verifyPOPO(p10cr) == false) {
        LOG.warn("could not validate POP for the pkcs#10 requst");
        PKIStatusInfo status = generateCmpRejectionStatus(PKIFailureInfo.badPOP, null);
        certResp = new CertResponse(certReqId, status);
        if (childAuditEvent != null) {
            childAuditEvent.setStatus(AuditStatus.FAILED);
            childAuditEvent.addEventData(new AuditEventData("message", "invalid POP"));
        }
    } else {
        CertificationRequestInfo certTemp = p10cr.getCertificationRequestInfo();
        Extensions extensions = null;
        ASN1Set attrs = certTemp.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())) {
                extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
            }
        }

        X500Name subject = certTemp.getSubject();
        if (childAuditEvent != null) {
            childAuditEvent.addEventData(new AuditEventData("subject", X509Util.getRFC4519Name(subject)));
        }

        SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();

        try {
            CmpUtf8Pairs keyvalues = CmpUtil.extract(reqHeader.getGeneralInfo());
            String certprofileName = keyvalues == null ? null
                    : keyvalues.getValue(CmpUtf8Pairs.KEY_CERT_PROFILE);
            if (certprofileName == null) {
                throw new CMPException("no certificate profile is specified");
            }

            if (childAuditEvent != null) {
                childAuditEvent.addEventData(new AuditEventData("certprofile", certprofileName));
            }

            checkPermission(requestor, certprofileName);

            certResp = generateCertificate(requestor, user, tid, certReqId, subject, publicKeyInfo, null,
                    extensions, certprofileName, false, confirmWaitTime, childAuditEvent);
        } catch (CMPException e) {
            certResp = new CertResponse(certReqId,
                    generateCmpRejectionStatus(PKIFailureInfo.badCertTemplate, e.getMessage()));
            if (childAuditEvent != null) {
                childAuditEvent.setStatus(AuditStatus.FAILED);
                childAuditEvent.addEventData(new AuditEventData("message", "badCertTemplate"));
            }
        } // end try
    }

    CMPCertificate[] caPubs = sendCaCert ? new CMPCertificate[] { getCA().getCAInfo().getCertInCMPFormat() }
            : null;
    CertRepMessage repMessage = new CertRepMessage(caPubs, new CertResponse[] { certResp });

    return new PKIBody(PKIBody.TYPE_CERT_REP, repMessage);
}

From source file:org.xipki.common.util.AlgorithmUtil.java

License:Open Source License

static public RSASSAPSSparams createPSSRSAParams(final ASN1ObjectIdentifier digestAlgOID)
        throws NoSuchAlgorithmException {
    int saltSize;
    if (X509ObjectIdentifiers.id_SHA1.equals(digestAlgOID)) {
        saltSize = 20;/*  w w w  . ja  va2  s  .com*/
    } else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOID)) {
        saltSize = 28;
    } else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOID)) {
        saltSize = 32;
    } else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOID)) {
        saltSize = 48;
    } else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOID)) {
        saltSize = 64;
    } else {
        throw new NoSuchAlgorithmException("unknown digest algorithm " + digestAlgOID);
    }

    AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(digestAlgOID, DERNull.INSTANCE);
    return new RSASSAPSSparams(digAlgId, new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, digAlgId),
            new ASN1Integer(saltSize), RSASSAPSSparams.DEFAULT_TRAILER_FIELD);
}

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 {/*from  www.j  ava 2s.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.proxy.Asn1GenDSAKeypairParams.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vector = new ASN1EncodableVector();
    vector.add(slotId);// w  w  w.  j  av a2  s.co  m
    vector.add(new DERUTF8String(label));
    vector.add(new ASN1Integer(p));
    vector.add(new ASN1Integer(q));
    vector.add(new ASN1Integer(g));
    return new DERSequence(vector);
}

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

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vector = new ASN1EncodableVector();
    vector.add(slotId);//from  w w  w.  ja v a 2s.co m
    vector.add(new DERUTF8String(label));
    vector.add(new ASN1Integer(keysize));
    if (publicExponent != null) {
        vector.add(new ASN1Integer(publicExponent));
    }
    return new DERSequence(vector);
}