Search in sources :

Example 41 with ASN1OctetString

use of org.bouncycastle.asn1.ASN1OctetString in project jruby-openssl by jruby.

the class EncContent method fromASN1.

/**
 * EncryptedContentInfo ::= SEQUENCE {
 *   contentType ContentType,
 *   contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
 *   encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL }
 *
 * EncryptedContent ::= OCTET STRING
 */
public static EncContent fromASN1(final ASN1Encodable content) {
    final ASN1Sequence sequence = (ASN1Sequence) content;
    ASN1ObjectIdentifier contentType = (ASN1ObjectIdentifier) (sequence.getObjectAt(0));
    final EncContent ec = new EncContent();
    ec.setContentType(ASN1Registry.oid2nid(contentType));
    ec.setAlgorithm(AlgorithmIdentifier.getInstance(sequence.getObjectAt(1)));
    if (sequence.size() > 2 && sequence.getObjectAt(2) instanceof ASN1TaggedObject && ((ASN1TaggedObject) (sequence.getObjectAt(2))).getTagNo() == 0) {
        ASN1Encodable ee = ((ASN1TaggedObject) (sequence.getObjectAt(2))).getObject();
        if (ee instanceof ASN1Sequence && ((ASN1Sequence) ee).size() > 0) {
            ByteList combinedOctets = new ByteList();
            Enumeration enm = ((ASN1Sequence) ee).getObjects();
            while (enm.hasMoreElements()) {
                byte[] octets = ((ASN1OctetString) enm.nextElement()).getOctets();
                combinedOctets.append(octets);
            }
            ec.setEncData(new DEROctetString(combinedOctets.bytes()));
        } else {
            ec.setEncData((ASN1OctetString) ee);
        }
    }
    return ec;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ByteList(org.jruby.util.ByteList) Enumeration(java.util.Enumeration) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) DEROctetString(org.bouncycastle.asn1.DEROctetString)

Example 42 with ASN1OctetString

use of org.bouncycastle.asn1.ASN1OctetString in project jruby-openssl by jruby.

the class RecipInfo method fromASN1.

/**
 * RecipientInfo ::= SEQUENCE {
 *   version Version,
 *   issuerAndSerialNumber IssuerAndSerialNumber,
 *   keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
 *   encryptedKey EncryptedKey }
 *
 * EncryptedKey ::= OCTET STRING
 */
public static RecipInfo fromASN1(ASN1Encodable content) {
    ASN1Sequence sequence = (ASN1Sequence) content;
    RecipInfo ri = new RecipInfo();
    ri.setVersion(((ASN1Integer) sequence.getObjectAt(0)).getValue().intValue());
    ri.setIssuerAndSerial(IssuerAndSerialNumber.getInstance(sequence.getObjectAt(1)));
    ri.setKeyEncAlgor(AlgorithmIdentifier.getInstance(sequence.getObjectAt(2)));
    ri.setEncKey((ASN1OctetString) sequence.getObjectAt(3));
    return ri;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Integer(org.bouncycastle.asn1.ASN1Integer)

Example 43 with ASN1OctetString

use of org.bouncycastle.asn1.ASN1OctetString in project jruby-openssl by jruby.

the class X509Utils method checkIfIssuedBy.

/**
 * c: X509_check_issued
 */
public static int checkIfIssuedBy(final X509AuxCertificate issuer, final X509AuxCertificate subject) throws IOException {
    if (!issuer.getSubjectX500Principal().equals(subject.getIssuerX500Principal())) {
        return V_ERR_SUBJECT_ISSUER_MISMATCH;
    }
    if (subject.getExtensionValue("2.5.29.35") != null) {
        // authorityKeyID
        // I hate ASN1 and DER
        Object key = get(subject.getExtensionValue("2.5.29.35"));
        if (!(key instanceof ASN1Sequence))
            key = get((DEROctetString) key);
        final ASN1Sequence seq = (ASN1Sequence) key;
        final AuthorityKeyIdentifier sakid;
        if (seq.size() == 1 && (seq.getObjectAt(0) instanceof ASN1OctetString)) {
            sakid = AuthorityKeyIdentifier.getInstance(new DLSequence(new DERTaggedObject(0, seq.getObjectAt(0))));
        } else {
            sakid = AuthorityKeyIdentifier.getInstance(seq);
        }
        if (sakid.getKeyIdentifier() != null) {
            if (issuer.getExtensionValue("2.5.29.14") != null) {
                DEROctetString der = (DEROctetString) get(issuer.getExtensionValue("2.5.29.14"));
                SubjectKeyIdentifier iskid = SubjectKeyIdentifier.getInstance(get(der.getOctets()));
                if (iskid.getKeyIdentifier() != null) {
                    if (!Arrays.equals(sakid.getKeyIdentifier(), iskid.getKeyIdentifier())) {
                        return V_ERR_AKID_SKID_MISMATCH;
                    }
                }
            }
        }
        final BigInteger serialNumber = sakid.getAuthorityCertSerialNumber();
        if (serialNumber != null && !serialNumber.equals(issuer.getSerialNumber())) {
            return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
        }
        if (sakid.getAuthorityCertIssuer() != null) {
            GeneralName[] gens = sakid.getAuthorityCertIssuer().getNames();
            X500Name x500Name = null;
            for (int i = 0; i < gens.length; i++) {
                if (gens[i].getTagNo() == GeneralName.directoryName) {
                    ASN1Encodable name = gens[i].getName();
                    if (name instanceof X500Name) {
                        x500Name = (X500Name) name;
                    } else if (name instanceof ASN1Sequence) {
                        x500Name = X500Name.getInstance((ASN1Sequence) name);
                    } else {
                        throw new RuntimeException("unknown name type: " + name);
                    }
                    break;
                }
            }
            if (x500Name != null) {
                if (!new Name(x500Name).equalTo(issuer.getIssuerX500Principal())) {
                    return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
                }
            }
        }
    }
    final boolean[] keyUsage = issuer.getKeyUsage();
    if (subject.getExtensionValue("1.3.6.1.5.5.7.1.14") != null) {
        if (keyUsage != null && !keyUsage[0]) {
            // KU_DIGITAL_SIGNATURE
            return V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
        }
    } else if (keyUsage != null && !keyUsage[5]) {
        // KU_KEY_CERT_SIGN
        return V_ERR_KEYUSAGE_NO_CERTSIGN;
    }
    return V_OK;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) DEROctetString(org.bouncycastle.asn1.DEROctetString) GeneralName(org.bouncycastle.asn1.x509.GeneralName) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DLSequence(org.bouncycastle.asn1.DLSequence) BigInteger(java.math.BigInteger) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable)

Example 44 with ASN1OctetString

use of org.bouncycastle.asn1.ASN1OctetString in project xipki by xipki.

the class AdmissionSyntaxOption method getExtensionValue.

public ExtensionValue getExtensionValue(List<List<String>> registrationNumbersList) throws BadCertTemplateException {
    if (!this.inputFromRequestRequired) {
        return this.extensionValue;
    }
    if (CollectionUtil.isEmpty(registrationNumbersList)) {
        throw new BadCertTemplateException("registrationNumbersList must not be empty");
    }
    final int n = registrationNumbersList.size();
    if (n != this.admissionsList.size()) {
        throw new BadCertTemplateException("invalid size of Admissions in AdmissionSyntax: " + "is=" + n + ", expected=" + this.admissionsList.size());
    }
    // check registrationNumbers
    List<List<String>> newRegNumbersList = new ArrayList<>(this.admissionsList.size());
    for (int i = 0; i < n; i++) {
        AdmissionsOption ao = this.admissionsList.get(i);
        List<ProfessionInfoOption> pi = ao.getProfessionInfos();
        List<String> registrationNumbers = registrationNumbersList.get(i);
        final int k = registrationNumbers.size();
        if (k != pi.size()) {
            throw new BadCertTemplateException("invalid size of ProfessionInfo in Admissions[" + i + "], is=" + k + ", expected=" + pi.size());
        }
        List<String> newRegNumbers = new ArrayList<>(k);
        newRegNumbersList.add(newRegNumbers);
        for (int j = 0; j < k; j++) {
            RegistrationNumberOption option = pi.get(j).getRegistrationNumberOption();
            if (option == null || option.getConstant() != null) {
                continue;
            }
            Pattern regex = option.getRegex();
            String regNum = registrationNumbers.get(j);
            if (regNum == null || !regex.matcher(regNum).matches()) {
                throw new BadCertTemplateException("invalid registrationNumber[" + i + "][" + j + "]: '" + regNum + "'");
            }
            newRegNumbers.add(regNum);
        }
    }
    ASN1EncodableVector vec = new ASN1EncodableVector();
    for (int i = 0; i < this.admissionsList.size(); i++) {
        AdmissionsOption ao = this.admissionsList.get(i);
        List<ProfessionInfoOption> piList = ao.getProfessionInfos();
        ProfessionInfo[] pis = new ProfessionInfo[piList.size()];
        for (int j = 0; j < pis.length; j++) {
            ProfessionInfoOption pio = piList.get(j);
            DirectoryString[] professionItems = null;
            int size = pio.getProfessionItems().size();
            professionItems = new DirectoryString[size];
            for (int k = 0; k < size; k++) {
                professionItems[k] = new DirectoryString(pio.getProfessionItems().get(k));
            }
            ASN1OctetString addProfessionInfo = null;
            if (pio.getAddProfessionalInfo() != null) {
                addProfessionInfo = new DEROctetString(pio.getAddProfessionalInfo());
            }
            RegistrationNumberOption regNumOption = pio.getRegistrationNumberOption();
            String registrationNumber = null;
            if (regNumOption != null) {
                if (regNumOption.getConstant() != null) {
                    registrationNumber = regNumOption.getConstant();
                } else {
                    registrationNumber = newRegNumbersList.get(i).get(j);
                }
            }
            pis[i] = new ProfessionInfo(pio.getNamingAuthority(), professionItems, pio.getProfessionOids().toArray(new ASN1ObjectIdentifier[0]), registrationNumber, addProfessionInfo);
        }
        vec.add(new Admissions(ao.getAdmissionAuthority(), ao.getNamingAuthority(), pis));
    }
    return new ExtensionValue(critical, new AdmissionSyntax(admissionAuthority, new DERSequence(vec)));
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERSequence(org.bouncycastle.asn1.DERSequence) ExtensionValue(org.xipki.ca.api.profile.ExtensionValue) AdmissionSyntax(org.bouncycastle.asn1.isismtt.x509.AdmissionSyntax) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) Admissions(org.bouncycastle.asn1.isismtt.x509.Admissions) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ArrayList(java.util.ArrayList) List(java.util.List) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) ProfessionInfo(org.bouncycastle.asn1.isismtt.x509.ProfessionInfo)

Example 45 with ASN1OctetString

use of org.bouncycastle.asn1.ASN1OctetString in project xipki by xipki.

the class CmpRequestor method signAndSend.

protected PkiResponse signAndSend(PKIMessage request, RequestResponseDebug debug) throws CmpRequestorException {
    ParamUtil.requireNonNull("request", request);
    PKIMessage tmpRequest = (signRequest) ? sign(request) : request;
    byte[] encodedRequest;
    try {
        encodedRequest = tmpRequest.getEncoded();
    } catch (IOException ex) {
        LOG.error("could not encode the PKI request {}", tmpRequest);
        throw new CmpRequestorException(ex.getMessage(), ex);
    }
    RequestResponsePair reqResp = null;
    if (debug != null) {
        reqResp = new RequestResponsePair();
        debug.add(reqResp);
        if (debug.saveRequest()) {
            reqResp.setRequest(encodedRequest);
        }
    }
    byte[] encodedResponse;
    try {
        encodedResponse = send(encodedRequest);
    } catch (IOException ex) {
        LOG.error("could not send the PKI request {} to server", tmpRequest);
        throw new CmpRequestorException("TRANSPORT_ERROR", ex);
    }
    if (reqResp != null && debug.saveResponse()) {
        reqResp.setResponse(encodedResponse);
    }
    GeneralPKIMessage response;
    try {
        response = new GeneralPKIMessage(encodedResponse);
    } catch (IOException ex) {
        LOG.error("could not decode the received PKI message: {}", Hex.encode(encodedResponse));
        throw new CmpRequestorException(ex.getMessage(), ex);
    }
    PKIHeader reqHeader = request.getHeader();
    PKIHeader respHeader = response.getHeader();
    ASN1OctetString tid = reqHeader.getTransactionID();
    ASN1OctetString respTid = respHeader.getTransactionID();
    if (!tid.equals(respTid)) {
        LOG.warn("Response contains different tid ({}) than requested {}", respTid, tid);
        throw new CmpRequestorException("Response contains differnt tid than the request");
    }
    ASN1OctetString senderNonce = reqHeader.getSenderNonce();
    ASN1OctetString respRecipientNonce = respHeader.getRecipNonce();
    if (!senderNonce.equals(respRecipientNonce)) {
        LOG.warn("tid {}: response.recipientNonce ({}) != request.senderNonce ({})", tid, respRecipientNonce, senderNonce);
        throw new CmpRequestorException("Response contains differnt tid than the request");
    }
    GeneralName rec = respHeader.getRecipient();
    if (!sender.equals(rec)) {
        LOG.warn("tid={}: unknown CMP requestor '{}'", tid, rec);
    }
    PkiResponse ret = new PkiResponse(response);
    if (response.hasProtection()) {
        try {
            ProtectionVerificationResult verifyProtection = verifyProtection(Hex.encode(tid.getOctets()), response);
            ret.setProtectionVerificationResult(verifyProtection);
        } catch (InvalidKeyException | OperatorCreationException | CMPException ex) {
            throw new CmpRequestorException(ex.getMessage(), ex);
        }
    } else if (signRequest) {
        PKIBody respBody = response.getBody();
        int bodyType = respBody.getType();
        if (bodyType != PKIBody.TYPE_ERROR) {
            throw new CmpRequestorException("response is not signed");
        }
    }
    return ret;
}
Also used : ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage) RequestResponsePair(org.xipki.common.RequestResponsePair) PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PkiResponse(org.xipki.cmp.PkiResponse) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) ProtectionVerificationResult(org.xipki.cmp.ProtectionVerificationResult) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage) CMPException(org.bouncycastle.cert.cmp.CMPException) GeneralName(org.bouncycastle.asn1.x509.GeneralName) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Aggregations

ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)84 IOException (java.io.IOException)39 DEROctetString (org.bouncycastle.asn1.DEROctetString)26 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)24 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)22 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)20 ByteArrayInputStream (java.io.ByteArrayInputStream)16 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)16 X509Certificate (java.security.cert.X509Certificate)15 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)15 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)15 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)14 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)12 Enumeration (java.util.Enumeration)12 DERBitString (org.bouncycastle.asn1.DERBitString)12 CertificateException (java.security.cert.CertificateException)11 DERBMPString (org.bouncycastle.asn1.DERBMPString)11 DERIA5String (org.bouncycastle.asn1.DERIA5String)11 DERSequence (org.bouncycastle.asn1.DERSequence)11 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)11