Example usage for org.bouncycastle.asn1.cms RecipientIdentifier getId

List of usage examples for org.bouncycastle.asn1.cms RecipientIdentifier getId

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cms RecipientIdentifier getId.

Prototype

public ASN1Encodable getId() 

Source Link

Usage

From source file:org.ejbca.core.protocol.scep.ScepRequestMessage.java

License:Open Source License

private void init() throws IOException {
    if (log.isTraceEnabled()) {
        log.trace(">init");
    }//  www  .j ava2 s . co  m
    try {
        CMSSignedData csd = new CMSSignedData(scepmsg);
        SignerInformationStore infoStore = csd.getSignerInfos();
        @SuppressWarnings("unchecked")
        Collection<SignerInformation> signers = infoStore.getSigners();
        Iterator<SignerInformation> iter = signers.iterator();
        if (iter.hasNext()) {
            SignerInformation si = (SignerInformation) iter.next();
            preferredDigestAlg = si.getDigestAlgOID();
            log.debug("Set " + preferredDigestAlg + " as preferred digest algorithm for SCEP");
        }
    } catch (CMSException e) {
        // ignore, use default digest algo
        log.error("CMSException trying to get preferred digest algorithm: ", e);
    }
    // Parse and verify the integrity of the PKIOperation message PKCS#7
    /* If this would have been done using the newer CMS it would have made me so much happier... */
    ASN1InputStream seqAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(scepmsg));
    ASN1Sequence seq = null;
    try {
        seq = (ASN1Sequence) seqAsn1InputStream.readObject();
    } finally {
        seqAsn1InputStream.close();
    }
    ContentInfo ci = ContentInfo.getInstance(seq);
    String ctoid = ci.getContentType().getId();

    if (ctoid.equals(CMSObjectIdentifiers.signedData.getId())) {
        // This is SignedData so it is a pkcsCertReqSigned, pkcsGetCertInitialSigned, pkcsGetCertSigned, pkcsGetCRLSigned
        // (could also be pkcsRepSigned or certOnly, but we don't receive them on the server side
        // Try to find out what kind of message this is
        sd = SignedData.getInstance((ASN1Sequence) ci.getContent());
        // Get self signed cert to identify the senders public key
        ASN1Set certs = sd.getCertificates();
        if (certs.size() > 0) {
            // There should be only one...
            ASN1Encodable dercert = certs.getObjectAt(0);
            if (dercert != null) {
                // Requester's self-signed certificate is requestKeyInfo
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                DEROutputStream dOut = new DEROutputStream(bOut);
                dOut.writeObject(dercert);
                if (bOut.size() > 0) {
                    requestKeyInfo = bOut.toByteArray();
                    //Create Certificate used for debugging
                    try {
                        signercert = CertTools.getCertfromByteArray(requestKeyInfo);
                        if (log.isDebugEnabled()) {
                            log.debug("requestKeyInfo is SubjectDN: " + CertTools.getSubjectDN(signercert)
                                    + ", Serial=" + CertTools.getSerialNumberAsString(signercert)
                                    + "; IssuerDN: " + CertTools.getIssuerDN(signercert).toString());
                        }
                    } catch (CertificateException e) {
                        log.error("Error parsing requestKeyInfo : ", e);
                    }

                }
            }
        }

        Enumeration<?> sis = sd.getSignerInfos().getObjects();

        if (sis.hasMoreElements()) {
            SignerInfo si = SignerInfo.getInstance((ASN1Sequence) sis.nextElement());
            Enumeration<?> attr = si.getAuthenticatedAttributes().getObjects();

            while (attr.hasMoreElements()) {
                Attribute a = Attribute.getInstance((ASN1Sequence) attr.nextElement());
                if (log.isDebugEnabled()) {
                    log.debug("Found attribute: " + a.getAttrType().getId());
                }
                if (a.getAttrType().getId().equals(id_senderNonce)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    ASN1OctetString str = ASN1OctetString.getInstance(values.nextElement());
                    senderNonce = new String(Base64.encode(str.getOctets(), false));
                    if (log.isDebugEnabled()) {
                        log.debug("senderNonce = " + senderNonce);
                    }
                }
                if (a.getAttrType().getId().equals(id_transId)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    DERPrintableString str = DERPrintableString.getInstance(values.nextElement());
                    transactionId = str.getString();
                    if (log.isDebugEnabled()) {
                        log.debug("transactionId = " + transactionId);
                    }
                }
                if (a.getAttrType().getId().equals(id_messageType)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    DERPrintableString str = DERPrintableString.getInstance(values.nextElement());
                    messageType = Integer.parseInt(str.getString());
                    if (log.isDebugEnabled()) {
                        log.debug("messagetype = " + messageType);
                    }
                }
            }
        }

        // If this is a PKCSReq
        if ((messageType == ScepRequestMessage.SCEP_TYPE_PKCSREQ)
                || (messageType == ScepRequestMessage.SCEP_TYPE_GETCRL)
                || (messageType == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL)) {
            // Extract the contents, which is an encrypted PKCS10 if messageType == 19
            // , and an encrypted issuer and subject if messageType == 20 (not extracted)
            // and an encrypted IssuerAndSerialNumber if messageType == 22
            ci = sd.getEncapContentInfo();
            ctoid = ci.getContentType().getId();

            if (ctoid.equals(CMSObjectIdentifiers.data.getId())) {
                ASN1OctetString content = (ASN1OctetString) ci.getContent();
                if (log.isDebugEnabled()) {
                    log.debug("envelopedData is " + content.getOctets().length + " bytes.");
                }
                ASN1InputStream seq1Asn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(content.getOctets()));
                ASN1Sequence seq1 = null;
                try {
                    seq1 = (ASN1Sequence) seq1Asn1InputStream.readObject();
                } finally {
                    seq1Asn1InputStream.close();
                }
                envEncData = ContentInfo.getInstance(seq1);
                ctoid = envEncData.getContentType().getId();

                if (ctoid.equals(CMSObjectIdentifiers.envelopedData.getId())) {
                    envData = EnvelopedData.getInstance((ASN1Sequence) envEncData.getContent());
                    ASN1Set recipientInfos = envData.getRecipientInfos();
                    Enumeration<?> e = recipientInfos.getObjects();
                    while (e.hasMoreElements()) {
                        RecipientInfo ri = RecipientInfo.getInstance(e.nextElement());
                        KeyTransRecipientInfo recipientInfo = KeyTransRecipientInfo.getInstance(ri.getInfo());
                        RecipientIdentifier rid = recipientInfo.getRecipientIdentifier();
                        IssuerAndSerialNumber iasn = IssuerAndSerialNumber.getInstance(rid.getId());
                        issuerDN = iasn.getName().toString();
                        serialNo = iasn.getSerialNumber().getValue();
                        if (log.isDebugEnabled()) {
                            log.debug("IssuerDN: " + issuerDN);
                            log.debug("SerialNumber: " + iasn.getSerialNumber().getValue().toString(16));
                        }
                    }
                } else {
                    errorText = "EncapsulatedContentInfo does not contain PKCS7 envelopedData: ";
                    log.error(errorText + ctoid);
                    error = 2;
                }
            } else {
                errorText = "EncapsulatedContentInfo is not of type 'data': ";
                log.error(errorText + ctoid);
                error = 3;
            }
        } else {
            errorText = "This is not a certification request!";
            log.error(errorText);
            error = 4;
        }
    } else {
        errorText = "PKCSReq does not contain 'signedData': ";
        log.error(errorText + ctoid);
        error = 1;
    }

    log.trace("<init");
}