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.sipfoundry.sipxconfig.cert.CertificateRequestGenerator.java

License:Contributor Agreement License

void copyExtensions(X509Certificate cert, Set<String> in, boolean critical, Vector<ASN1ObjectIdentifier> out,
        Vector<X509Extension> values) {
    for (String oid : in) {
        out.add(new ASN1ObjectIdentifier(oid));
        values.add(new X509Extension(critical, new DEROctetString(cert.getExtensionValue(oid))));
    }/*from   w  w w  .  j av a2s.c  o m*/
}

From source file:org.tramaci.onionmail.LibSTLS.java

License:Open Source License

public static X509Certificate CreateCert(KeyPair KP, String onion, long Dfrom, long Dto, String info,
        String[] AltName) throws Exception { //OK

    byte[] bi = Stdio.md5(onion.getBytes());
    byte[] bx = new byte[bi.length + 9];
    System.arraycopy(bi, 0, bx, 1, bi.length);
    bx[0] = 0x7C;//from  w  w  w. jav a2  s.  c  o  m
    byte[] tmp = Stdio.Stosx(new long[] { Dfrom / 1000L, Dto / 1000L }, 4);
    int bp = 17;
    for (int ax = 0; ax < 8; ax++)
        bx[bp++] = tmp[ax];

    Date startDate = new Date(Dfrom); // time from which certificate is valid
    Date expiryDate = new Date(Dto); // time after which certificate is not valid
    BigInteger serialNumber = new BigInteger(bx); // serial number for certificate
    KeyPair keyPair = KP; // EC public/private key pair

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    if (info != null && info.length() > 0)
        info = ", " + info;
    else
        info = "";
    X500Principal dnName = new X500Principal("CN=" + onion + info);
    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(startDate);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(dnName); // note: same as issuer
    certGen.setPublicKey(KP.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    if (AltName != null) {
        int cx = AltName.length;
        for (int ax = 0; ax < cx; ax++)
            try {
                GeneralName generalName = new GeneralName(GeneralName.dNSName,
                        new DERIA5String(AltName[ax].toLowerCase().trim()));
                GeneralNames subjectAltNames = new GeneralNames(generalName);
                certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
                        new DEROctetString(subjectAltNames));
            } catch (Exception EI) {
                Main.echo("CreateCert Error: " + EI.getMessage() + " (altName=`" + AltName[ax] + "`)\n");
            }
    }

    X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");

    return cert;
}

From source file:org.viafirma.nucleo.validacion.OcspValidatorHandler.java

License:Apache License

/**
 * Genera una nueva peticin OCSP para el certificado indicado.
 * /*from  w  w  w  .  j  a  v a  2s.c om*/
 * @param certificadoX509
 *            Certificado que deseamos validar.
 * @param certificadoX509Emisor
 *            Certificado emisor del certificado a validar.
 * @return Peticin OCSP
 * @throws OCSPException
 */
private OCSPReq generateRequest(X509Certificate certificadoX509, X509Certificate certificadoX509Emisor)
        throws OCSPException {
    // 1 -Generamos el identificador
    CertificateID id = new CertificateID(CertificateID.HASH_SHA1, certificadoX509Emisor,
            certificadoX509.getSerialNumber());

    // 2- Generador de peticiones ocsp
    OCSPReqGenerator requestGenerator = new OCSPReqGenerator();
    requestGenerator.addRequest(id);

    // 3- extensiones necesarias. RFC 2560
    BigInteger time = BigInteger.valueOf(System.currentTimeMillis());
    Vector<DERObjectIdentifier> oids = new Vector<DERObjectIdentifier>();
    oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
    Vector<X509Extension> values = new Vector<X509Extension>();
    values.add(new X509Extension(false, new DEROctetString(time.toByteArray())));

    // 4. Aadimos las extensiones necesarias al generador
    requestGenerator.setRequestExtensions(new X509Extensions(oids, values));

    // Generamos la peticin OCSP
    return requestGenerator.generate();
}

From source file:org.wso2.carbon.identity.authenticator.pki.cert.validation.ocsp.OCSPVerifier.java

License:Apache License

/**
 * This method generates an OCSP Request to be sent to an OCSP endpoint.
 * // w  w w  .jav a2  s  . co  m
 * @param issuerCert
 *            is the Certificate of the Issuer of the peer certificate we
 *            are interested in.
 * @param serialNumber
 *            of the peer certificate.
 * @return generated OCSP request.
 * @throws CertificateVerificationException
 * 
 */
private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws CertificateVerificationException {

    // TODO: Have to check if this is OK with synapse implementation.
    // Add provider BC
    // Security.addProvider(new
    // org.bouncycastle.jce.provider.BouncyCastleProvider());
    try {
        // CertID structure is used to uniquely identify certificates that
        // are the subject of
        // an OCSP request or response and has an ASN.1 definition. CertID
        // structure is defined in RFC 2560
        CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber);

        // basic request generation with nonce
        OCSPReqGenerator generator = new OCSPReqGenerator();
        generator.addRequest(id);

        // create details for nonce extension. The nonce extension is used
        // to bind
        // a request to a response to prevent replay attacks. As the name
        // implies,
        // the nonce value is something that the client should only use once
        // within a reasonably small period.
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        // Vector<DERObjectIdentifier> objectIdentifiers = new
        // Vector<DERObjectIdentifier>();
        // Vector<X509Extension> values = new Vector<X509Extension>();

        X509Extension ext = new X509Extension(false, new DEROctetString(nonce.toByteArray()));
        Hashtable exts = new Hashtable();
        exts.put(new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1.2"), ext);

        // to create the request Extension
        // objectIdentifiers.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);

        // values.add(ext);
        generator.setRequestExtensions(new X509Extensions(exts));

        return generator.generate();
    } catch (OCSPException e) {
        throw new CertificateVerificationException("Cannot generate OSCP Request with the given certificate",
                e);
    }
}

From source file:org.xipki.ca.certprofile.XmlX509Certprofile.java

License:Open Source License

private ExtensionValue createAdmission(final boolean critical, final List<ASN1ObjectIdentifier> professionOIDs,
        final List<String> professionItems, final String registrationNumber, final byte[] addProfessionInfo)
        throws CertprofileException {
    if (CollectionUtil.isEmpty(professionItems) && CollectionUtil.isEmpty(professionOIDs)
            && StringUtil.isBlank(registrationNumber)
            && (addProfessionInfo == null || addProfessionInfo.length == 0)) {
        return null;
    }/*from   w  w w . j a va2s  .  com*/

    DirectoryString[] _professionItems = null;
    if (professionItems != null && professionItems.size() > 0) {
        int n = professionItems.size();
        _professionItems = new DirectoryString[n];
        for (int i = 0; i < n; i++) {
            _professionItems[i] = new DirectoryString(professionItems.get(i));
        }
    }

    ASN1ObjectIdentifier[] _professionOIDs = null;
    if (professionOIDs != null && professionOIDs.size() > 0) {
        _professionOIDs = professionOIDs.toArray(new ASN1ObjectIdentifier[0]);
    }

    ASN1OctetString _addProfessionInfo = null;
    if (addProfessionInfo != null && addProfessionInfo.length > 0) {
        _addProfessionInfo = new DEROctetString(addProfessionInfo);
    }

    ProfessionInfo professionInfo = new ProfessionInfo(null, _professionItems, _professionOIDs,
            registrationNumber, _addProfessionInfo);

    Admissions admissions = new Admissions(null, null, new ProfessionInfo[] { professionInfo });

    ASN1EncodableVector vector = new ASN1EncodableVector();
    vector.add(admissions);

    AdmissionSyntax value = new AdmissionSyntax(null, new DERSequence(vector));
    return new ExtensionValue(critical, value);
}

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

License:Open Source License

protected PKIHeader buildPKIHeader(final boolean addImplictConfirm, final ASN1OctetString tid,
        final CmpUtf8Pairs utf8Pairs, final InfoTypeAndValue... additionalGeneralInfos) {
    if (additionalGeneralInfos != null) {
        for (InfoTypeAndValue itv : additionalGeneralInfos) {
            ASN1ObjectIdentifier type = itv.getInfoType();
            if (CMPObjectIdentifiers.it_implicitConfirm.equals(type)) {
                throw new IllegalArgumentException(
                        "" + "additionGeneralInfos contains unpermitted ITV implicitConfirm");
            }//from  www  .  j a va2  s.  c o m

            if (CMPObjectIdentifiers.regInfo_utf8Pairs.equals(type)) {
                throw new IllegalArgumentException(
                        "" + "additionGeneralInfos contains unpermitted ITV utf8Pairs");
            }
        }
    }

    PKIHeaderBuilder hBuilder = new PKIHeaderBuilder(PKIHeader.CMP_2000, sender,
            recipient != null ? recipient : DUMMY_RECIPIENT);
    hBuilder.setMessageTime(new ASN1GeneralizedTime(new Date()));

    ASN1OctetString _tid;
    if (tid == null) {
        _tid = new DEROctetString(randomTransactionId());
    } else {
        _tid = tid;
    }

    hBuilder.setTransactionID(_tid);

    List<InfoTypeAndValue> itvs = new ArrayList<>(2);
    if (addImplictConfirm) {
        itvs.add(CmpUtil.getImplictConfirmGeneralInfo());
    }

    if (utf8Pairs != null) {
        itvs.add(CmpUtil.buildInfoTypeAndValue(utf8Pairs));
    }

    if (additionalGeneralInfos != null) {
        for (InfoTypeAndValue itv : additionalGeneralInfos) {
            if (itv != null) {
                itvs.add(itv);
            }
        }
    }

    if (CollectionUtil.isNotEmpty(itvs)) {
        hBuilder.setGeneralInfo(itvs.toArray(new InfoTypeAndValue[0]));
    }

    return hBuilder.build();
}

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 {//from   ww w  . java2 s  .co  m
            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 {/*  w  w  w.j a v  a 2 s  .  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.server.impl.CmpResponder.java

License:Open Source License

public PKIMessage processPKIMessage(final PKIMessage pkiMessage, final X509Certificate tlsClientCert,
        final AuditEvent auditEvent) throws ConfigurationException {
    GeneralPKIMessage message = new GeneralPKIMessage(pkiMessage);

    PKIHeader reqHeader = message.getHeader();
    ASN1OctetString tid = reqHeader.getTransactionID();

    if (tid == null) {
        byte[] randomBytes = randomTransactionId();
        tid = new DEROctetString(randomBytes);
    }// w ww  .  j a  v  a 2 s .  c  o m
    String tidStr = Hex.toHexString(tid.getOctets());
    if (auditEvent != null) {
        auditEvent.addEventData(new AuditEventData("tid", tidStr));
    }

    CmpControl cmpControl = getCmpControl();

    Integer failureCode = null;
    String statusText = null;

    Date messageTime = null;
    if (reqHeader.getMessageTime() != null) {
        try {
            messageTime = reqHeader.getMessageTime().getDate();
        } catch (ParseException e) {
            final String msg = "tid=" + tidStr + ": could not parse messageDate";
            if (LOG.isErrorEnabled()) {
                LOG.error(LogUtil.buildExceptionLogFormat(msg), e.getClass().getName(), e.getMessage());
            }
            LOG.debug(msg, e);
            messageTime = null;
        }
    }

    GeneralName recipient = reqHeader.getRecipient();
    boolean intentMe = (recipient == null) ? null : intendsMe(recipient);
    if (intentMe == false) {
        LOG.warn("tid={}: I am not the intented recipient, but '{}'", tid, reqHeader.getRecipient());
        failureCode = PKIFailureInfo.badRequest;
        statusText = "I am not the intended recipient";
    } else if (messageTime == null) {
        if (cmpControl.isMessageTimeRequired()) {
            failureCode = PKIFailureInfo.missingTimeStamp;
            statusText = "missing timestamp";
        }
    } else {
        long messageTimeBias = cmpControl.getMessageTimeBias();
        if (messageTimeBias < 0) {
            messageTimeBias *= -1;
        }

        long msgTimeMs = messageTime.getTime();
        long currentTimeMs = System.currentTimeMillis();
        long bias = (msgTimeMs - currentTimeMs) / 1000L;
        if (bias > messageTimeBias) {
            failureCode = PKIFailureInfo.badTime;
            statusText = "message time is in the future";
        } else if (bias * -1 > messageTimeBias) {
            failureCode = PKIFailureInfo.badTime;
            statusText = "message too old";
        }
    }

    if (failureCode != null) {
        if (auditEvent != null) {
            auditEvent.setLevel(AuditLevel.INFO);
            auditEvent.setStatus(AuditStatus.FAILED);
            auditEvent.addEventData(new AuditEventData("message", statusText));
        }
        return buildErrorPkiMessage(tid, reqHeader, failureCode, statusText);
    }

    boolean isProtected = message.hasProtection();
    CmpRequestorInfo requestor = null;

    String errorStatus;

    if (isProtected) {
        try {
            ProtectionVerificationResult verificationResult = verifyProtection(tidStr, message, cmpControl);
            ProtectionResult pr = verificationResult.getProtectionResult();
            switch (pr) {
            case VALID:
                errorStatus = null;
                break;
            case INVALID:
                errorStatus = "request is protected by signature but invalid";
                break;
            case NOT_SIGNATURE_BASED:
                errorStatus = "request is not protected by signature";
                break;
            case SENDER_NOT_AUTHORIZED:
                errorStatus = "request is protected by signature but the requestor is not authorized";
                break;
            case SIGALGO_FORBIDDEN:
                errorStatus = "request is protected by signature but the protection algorithm is forbidden";
                break;
            default:
                throw new RuntimeException("should not reach here, unknown ProtectionResult " + pr);
            } // end switch
            requestor = (CmpRequestorInfo) verificationResult.getRequestor();
        } catch (Exception e) {
            final String msg = "tid=" + tidStr + ": error while verifying the signature";
            if (LOG.isErrorEnabled()) {
                LOG.error(LogUtil.buildExceptionLogFormat(msg), e.getClass().getName(), e.getMessage());
            }
            LOG.debug(msg, e);
            errorStatus = "request has invalid signature based protection";
        }
    } else if (tlsClientCert != null) {
        boolean authorized = false;

        requestor = getRequestor(reqHeader);
        if (requestor != null) {
            if (tlsClientCert.equals(requestor.getCert().getCert())) {
                authorized = true;
            }
        }

        if (authorized) {
            errorStatus = null;
        } else {
            LOG.warn("tid={}: not authorized requestor (TLS client '{}')", tid,
                    X509Util.getRFC4519Name(tlsClientCert.getSubjectX500Principal()));
            errorStatus = "requestor (TLS client certificate) is not authorized";
        }
    } else {
        errorStatus = "request has no protection";
        requestor = null;
    }

    CmpUtf8Pairs keyvalues = CmpUtil.extract(reqHeader.getGeneralInfo());
    String username = keyvalues == null ? null : keyvalues.getValue(CmpUtf8Pairs.KEY_USER);
    if (username != null) {
        if (username.indexOf('*') != -1 || username.indexOf('%') != -1) {
            errorStatus = "user could not contains characters '*' and '%'";
        }
    }

    if (errorStatus != null) {
        if (auditEvent != null) {
            auditEvent.setLevel(AuditLevel.INFO);
            auditEvent.setStatus(AuditStatus.FAILED);
            auditEvent.addEventData(new AuditEventData("message", errorStatus));
        }
        return buildErrorPkiMessage(tid, reqHeader, PKIFailureInfo.badMessageCheck, errorStatus);
    }

    PKIMessage resp = intern_processPKIMessage(requestor, username, tid, message, auditEvent);

    if (isProtected) {
        resp = addProtection(resp, auditEvent);
    } else {
        // protected by TLS connection
    }

    return resp;
}

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

License:Open Source License

PKIMessage processPkiMessage(final LocalP11CryptServicePool p11CryptServicePool, final String moduleName,
        final PKIMessage pkiMessage) {
    ParamUtil.requireNonNull("p11CryptServicePool", p11CryptServicePool);
    ParamUtil.requireNonNull("pkiMessage", pkiMessage);
    GeneralPKIMessage message = new GeneralPKIMessage(pkiMessage);

    PKIHeader reqHeader = message.getHeader();
    ASN1OctetString tid = reqHeader.getTransactionID();

    if (tid == null) {
        byte[] randomBytes = randomTransactionId();
        tid = new DEROctetString(randomBytes);
    }/*from  www .j a v a  2  s.co  m*/
    String tidStr = Hex.toHexString(tid.getOctets());

    PKIHeaderBuilder respHeaderBuilder = new PKIHeaderBuilder(reqHeader.getPvno().getValue().intValue(), sender,
            reqHeader.getSender());
    respHeaderBuilder.setTransactionID(tid);

    PKIBody reqBody = message.getBody();
    final int type = reqBody.getType();

    PKIHeader respHeader = respHeaderBuilder.build();

    if (type != PKIBody.TYPE_GEN_MSG) {
        ErrorMsgContent emc = new ErrorMsgContent(new PKIStatusInfo(PKIStatus.rejection,
                new PKIFreeText("unsupported type " + type), new PKIFailureInfo(PKIFailureInfo.badRequest)));

        PKIBody respBody = new PKIBody(PKIBody.TYPE_ERROR, emc);
        return new PKIMessage(respHeader, respBody);
    }

    GenMsgContent genMsgBody = GenMsgContent.getInstance(reqBody.getContent());
    InfoTypeAndValue[] itvs = genMsgBody.toInfoTypeAndValueArray();

    InfoTypeAndValue itv = null;
    if (itvs != null && itvs.length > 0) {
        for (InfoTypeAndValue m : itvs) {
            ASN1ObjectIdentifier itvType = m.getInfoType();
            if (ObjectIdentifiers.id_xipki_cmp_cmpGenmsg.equals(itvType)) {
                itv = m;
                break;
            }
        }
    }

    if (itv == null) {
        final String statusMessage = String.format("PKIBody type %s is only supported with the sub-knownTypes",
                ObjectIdentifiers.id_xipki_cmp_cmpGenmsg.getId());
        return createRejectionPkiMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
    }

    try {
        return doProcessPkiMessage(p11CryptServicePool, moduleName, itv, respHeader);
    } catch (BadAsn1ObjectException ex) {
        LogUtil.error(LOG, ex, "could not process CMP message " + tidStr);
        return createRejectionPkiMessage(respHeader, PKIFailureInfo.badRequest, ex.getMessage());
    } catch (P11TokenException ex) {
        LogUtil.error(LOG, ex, "could not process CMP message " + tidStr);

        String p11ErrorType;
        if (ex instanceof P11UnknownEntityException) {
            p11ErrorType = P11ProxyConstants.ERROR_UNKNOWN_ENTITY;
        } else if (ex instanceof P11DuplicateEntityException) {
            p11ErrorType = P11ProxyConstants.ERROR_DUPLICATE_ENTITY;
        } else if (ex instanceof P11UnsupportedMechanismException) {
            p11ErrorType = P11ProxyConstants.ERROR_UNSUPPORTED_MECHANISM;
        } else {
            p11ErrorType = P11ProxyConstants.ERROR_P11_TOKENERROR;
        }

        String errorMessage = ex.getMessage();

        if (errorMessage == null) {
            errorMessage = "NULL";
        } else if (StringUtil.isBlank(errorMessage.trim())) {
            errorMessage = "NULL";
        }

        ConfPairs confPairs = new ConfPairs(p11ErrorType, errorMessage);
        return createRejectionPkiMessage(respHeader, PKIFailureInfo.badRequest, confPairs.getEncoded());
    } catch (Throwable th) {
        LogUtil.error(LOG, th, "could not process CMP message " + tidStr);
        return createRejectionPkiMessage(respHeader, PKIFailureInfo.systemFailure, "SYSTEM_FAILURE");
    }
}