Search in sources :

Example 1 with EnvelopedData

use of org.bouncycastle.asn1.cms.EnvelopedData in project xipki by xipki.

the class PkiMessage method encode.

public ContentInfo encode(ContentSigner signer, X509Certificate signerCert, X509Certificate[] cmsCertSet, X509Certificate recipientCert, ASN1ObjectIdentifier encAlgId) throws MessageEncodingException {
    ScepUtil.requireNonNull("signer", signer);
    ScepUtil.requireNonNull("signerCert", signerCert);
    if (messageData != null) {
        ScepUtil.requireNonNull("recipientCert", recipientCert);
        ScepUtil.requireNonNull("encAlgId", encAlgId);
    }
    CMSTypedData content;
    if (messageData == null) {
        content = new CMSAbsentContent();
    } else {
        CMSEnvelopedData envelopedData = encrypt(recipientCert, encAlgId);
        byte[] encoded;
        try {
            encoded = envelopedData.getEncoded();
        } catch (IOException ex) {
            throw new MessageEncodingException(ex);
        }
        content = new CMSProcessableByteArray(CMSObjectIdentifiers.envelopedData, encoded);
    }
    try {
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        // signerInfo
        JcaSignerInfoGeneratorBuilder signerInfoBuilder = new JcaSignerInfoGeneratorBuilder(new BcDigestCalculatorProvider());
        signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(getSignedAttributes()));
        AttributeTable attrTable = getUnsignedAttributes();
        if (attrTable != null) {
            signerInfoBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(attrTable));
        }
        // certificateSet
        ScepUtil.addCmsCertSet(generator, cmsCertSet);
        SignerInfoGenerator signerInfo;
        try {
            signerInfo = signerInfoBuilder.build(signer, signerCert);
        } catch (Exception ex) {
            throw new MessageEncodingException(ex);
        }
        generator.addSignerInfoGenerator(signerInfo);
        CMSSignedData signedData = generator.generate(content, true);
        return signedData.toASN1Structure();
    } catch (CMSException ex) {
        throw new MessageEncodingException(ex);
    } catch (Exception ex) {
        throw new MessageEncodingException(ex);
    }
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) DefaultSignedAttributeTableGenerator(org.bouncycastle.cms.DefaultSignedAttributeTableGenerator) CMSTypedData(org.bouncycastle.cms.CMSTypedData) CMSAbsentContent(org.bouncycastle.cms.CMSAbsentContent) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) IOException(java.io.IOException) MessageEncodingException(org.xipki.scep.exception.MessageEncodingException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSException(org.bouncycastle.cms.CMSException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) MessageEncodingException(org.xipki.scep.exception.MessageEncodingException) IOException(java.io.IOException) CertificateEncodingException(java.security.cert.CertificateEncodingException) SimpleAttributeTableGenerator(org.bouncycastle.cms.SimpleAttributeTableGenerator) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) SignerInfoGenerator(org.bouncycastle.cms.SignerInfoGenerator) CMSException(org.bouncycastle.cms.CMSException)

Example 2 with EnvelopedData

use of org.bouncycastle.asn1.cms.EnvelopedData in project xipki by xipki.

the class DecodedPkiMessage method decode.

@SuppressWarnings("unchecked")
public static DecodedPkiMessage decode(CMSSignedData pkiMessage, EnvelopedDataDecryptor recipient, CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException {
    ScepUtil.requireNonNull("pkiMessage", pkiMessage);
    ScepUtil.requireNonNull("recipient", recipient);
    SignerInformationStore signerStore = pkiMessage.getSignerInfos();
    Collection<SignerInformation> signerInfos = signerStore.getSigners();
    if (signerInfos.size() != 1) {
        throw new MessageDecodingException("number of signerInfos is not 1, but " + signerInfos.size());
    }
    SignerInformation signerInfo = signerInfos.iterator().next();
    SignerId sid = signerInfo.getSID();
    Collection<?> signedDataCerts = null;
    if (certStore != null) {
        signedDataCerts = certStore.getMatches(sid);
    }
    if (signedDataCerts == null || signedDataCerts.isEmpty()) {
        signedDataCerts = pkiMessage.getCertificates().getMatches(signerInfo.getSID());
    }
    if (signedDataCerts == null || signedDataCerts.size() != 1) {
        throw new MessageDecodingException("could not find embedded certificate to verify the signature");
    }
    AttributeTable signedAttrs = signerInfo.getSignedAttributes();
    if (signedAttrs == null) {
        throw new MessageDecodingException("missing SCEP attributes");
    }
    Date signingTime = null;
    // signingTime
    ASN1Encodable attrValue = ScepUtil.getFirstAttrValue(signedAttrs, CMSAttributes.signingTime);
    if (attrValue != null) {
        signingTime = Time.getInstance(attrValue).getDate();
    }
    // transactionId
    String str = getPrintableStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_TRANSACTION_ID);
    if (str == null || str.isEmpty()) {
        throw new MessageDecodingException("missing required SCEP attribute transactionId");
    }
    TransactionId transactionId = new TransactionId(str);
    // messageType
    Integer intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_MESSAGE_TYPE);
    if (intValue == null) {
        throw new MessageDecodingException("tid " + transactionId.getId() + ": missing required SCEP attribute messageType");
    }
    MessageType messageType;
    try {
        messageType = MessageType.forValue(intValue);
    } catch (IllegalArgumentException ex) {
        throw new MessageDecodingException("tid " + transactionId.getId() + ": invalid messageType '" + intValue + "'");
    }
    // senderNonce
    Nonce senderNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_SENDER_NONCE);
    if (senderNonce == null) {
        throw new MessageDecodingException("tid " + transactionId.getId() + ": missing required SCEP attribute senderNonce");
    }
    DecodedPkiMessage ret = new DecodedPkiMessage(transactionId, messageType, senderNonce);
    if (signingTime != null) {
        ret.setSigningTime(signingTime);
    }
    Nonce recipientNonce = null;
    try {
        recipientNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_RECIPIENT_NONCE);
    } catch (MessageDecodingException ex) {
        ret.setFailureMessage("could not parse recipientNonce: " + ex.getMessage());
    }
    if (recipientNonce != null) {
        ret.setRecipientNonce(recipientNonce);
    }
    PkiStatus pkiStatus = null;
    FailInfo failInfo = null;
    if (MessageType.CertRep == messageType) {
        // pkiStatus
        try {
            intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_PKI_STATUS);
        } catch (MessageDecodingException ex) {
            ret.setFailureMessage("could not parse pkiStatus: " + ex.getMessage());
            return ret;
        }
        if (intValue == null) {
            ret.setFailureMessage("missing required SCEP attribute pkiStatus");
            return ret;
        }
        try {
            pkiStatus = PkiStatus.forValue(intValue);
        } catch (IllegalArgumentException ex) {
            ret.setFailureMessage("invalid pkiStatus '" + intValue + "'");
            return ret;
        }
        ret.setPkiStatus(pkiStatus);
        // failureInfo
        if (pkiStatus == PkiStatus.FAILURE) {
            try {
                intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_FAILINFO);
            } catch (MessageDecodingException ex) {
                ret.setFailureMessage("could not parse failInfo: " + ex.getMessage());
                return ret;
            }
            if (intValue == null) {
                ret.setFailureMessage("missing required SCEP attribute failInfo");
                return ret;
            }
            try {
                failInfo = FailInfo.forValue(intValue);
            } catch (IllegalArgumentException ex) {
                ret.setFailureMessage("invalid failInfo '" + intValue + "'");
                return ret;
            }
            ret.setFailInfo(failInfo);
        }
    // end if(pkiStatus == PkiStatus.FAILURE)
    }
    // end if (MessageType.CertRep == messageType)
    // other signedAttributes
    Attribute[] attrs = signedAttrs.toASN1Structure().getAttributes();
    for (Attribute attr : attrs) {
        ASN1ObjectIdentifier type = attr.getAttrType();
        if (!SCEP_ATTR_TYPES.contains(type)) {
            ret.addSignendAttribute(type, attr.getAttrValues().getObjectAt(0));
        }
    }
    // unsignedAttributes
    AttributeTable unsignedAttrs = signerInfo.getUnsignedAttributes();
    attrs = (unsignedAttrs == null) ? null : unsignedAttrs.toASN1Structure().getAttributes();
    if (attrs != null) {
        for (Attribute attr : attrs) {
            ASN1ObjectIdentifier type = attr.getAttrType();
            ret.addUnsignendAttribute(type, attr.getAttrValues().getObjectAt(0));
        }
    }
    ASN1ObjectIdentifier digestAlgOid = signerInfo.getDigestAlgorithmID().getAlgorithm();
    ret.setDigestAlgorithm(digestAlgOid);
    String sigAlgOid = signerInfo.getEncryptionAlgOID();
    if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(sigAlgOid)) {
        ASN1ObjectIdentifier tmpDigestAlgOid;
        try {
            tmpDigestAlgOid = ScepUtil.extractDigesetAlgorithmIdentifier(signerInfo.getEncryptionAlgOID(), signerInfo.getEncryptionAlgParams());
        } catch (Exception ex) {
            final String msg = "could not extract digest algorithm from signerInfo.signatureAlgorithm: " + ex.getMessage();
            LOG.error(msg);
            LOG.debug(msg, ex);
            ret.setFailureMessage(msg);
            return ret;
        }
        if (!digestAlgOid.equals(tmpDigestAlgOid)) {
            ret.setFailureMessage("digestAlgorithm and encryptionAlgorithm do not use the same digestAlgorithm");
            return ret;
        }
    // end if
    }
    // end if
    X509CertificateHolder tmpSignerCert = (X509CertificateHolder) signedDataCerts.iterator().next();
    X509Certificate signerCert;
    try {
        signerCert = ScepUtil.toX509Cert(tmpSignerCert.toASN1Structure());
    } catch (CertificateException ex) {
        final String msg = "could not construct X509Certificate: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    ret.setSignatureCert(signerCert);
    // validate the signature
    SignerInformationVerifier verifier;
    try {
        verifier = new JcaSimpleSignerInfoVerifierBuilder().build(tmpSignerCert);
    } catch (OperatorCreationException | CertificateException ex) {
        final String msg = "could not build signature verifier: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    boolean signatureValid;
    try {
        signatureValid = signerInfo.verify(verifier);
    } catch (CMSException ex) {
        final String msg = "could not verify the signature: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    ret.setSignatureValid(signatureValid);
    if (!signatureValid) {
        return ret;
    }
    if (MessageType.CertRep == messageType && (pkiStatus == PkiStatus.FAILURE | pkiStatus == PkiStatus.PENDING)) {
        return ret;
    }
    // MessageData
    CMSTypedData signedContent = pkiMessage.getSignedContent();
    ASN1ObjectIdentifier signedContentType = signedContent.getContentType();
    if (!CMSObjectIdentifiers.envelopedData.equals(signedContentType)) {
        // fall back: some SCEP client, such as JSCEP use id-data
        if (!CMSObjectIdentifiers.data.equals(signedContentType)) {
            ret.setFailureMessage("either id-envelopedData or id-data is excepted, but not '" + signedContentType.getId());
            return ret;
        }
    }
    CMSEnvelopedData envData;
    try {
        envData = new CMSEnvelopedData((byte[]) signedContent.getContent());
    } catch (CMSException ex) {
        final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    ret.setContentEncryptionAlgorithm(envData.getContentEncryptionAlgorithm().getAlgorithm());
    byte[] encodedMessageData;
    try {
        encodedMessageData = recipient.decrypt(envData);
    } catch (MessageDecodingException ex) {
        final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        ret.setDecryptionSuccessful(false);
        return ret;
    }
    ret.setDecryptionSuccessful(true);
    try {
        if (MessageType.PKCSReq == messageType || MessageType.RenewalReq == messageType || MessageType.UpdateReq == messageType) {
            CertificationRequest messageData = CertificationRequest.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
        } else if (MessageType.CertPoll == messageType) {
            IssuerAndSubject messageData = IssuerAndSubject.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
        } else if (MessageType.GetCert == messageType || MessageType.GetCRL == messageType) {
            IssuerAndSerialNumber messageData = IssuerAndSerialNumber.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
            ret.setMessageData(messageData);
        } else if (MessageType.CertRep == messageType) {
            ContentInfo ci = ContentInfo.getInstance(encodedMessageData);
            ret.setMessageData(ci);
        } else {
            throw new RuntimeException("should not reach here, unknown messageType " + messageType);
        }
    } catch (Exception ex) {
        final String msg = "could not parse the messageData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    return ret;
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) Attribute(org.bouncycastle.asn1.cms.Attribute) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) SignerInformation(org.bouncycastle.cms.SignerInformation) CertificateException(java.security.cert.CertificateException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) FailInfo(org.xipki.scep.transaction.FailInfo) SignerInformationVerifier(org.bouncycastle.cms.SignerInformationVerifier) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) MessageType(org.xipki.scep.transaction.MessageType) PkiStatus(org.xipki.scep.transaction.PkiStatus) CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) CMSTypedData(org.bouncycastle.cms.CMSTypedData) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) Date(java.util.Date) CMSException(org.bouncycastle.cms.CMSException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) MessageDecodingException(org.xipki.scep.exception.MessageDecodingException) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) TransactionId(org.xipki.scep.transaction.TransactionId) Nonce(org.xipki.scep.transaction.Nonce) MessageDecodingException(org.xipki.scep.exception.MessageDecodingException) SignerId(org.bouncycastle.cms.SignerId) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) CMSException(org.bouncycastle.cms.CMSException)

Example 3 with EnvelopedData

use of org.bouncycastle.asn1.cms.EnvelopedData in project pdfbox by apache.

the class PublicKeySecurityHandler method createDERForRecipient.

private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert) throws IOException, GeneralSecurityException {
    String algorithm = "1.2.840.113549.3.2";
    AlgorithmParameterGenerator apg;
    KeyGenerator keygen;
    Cipher cipher;
    try {
        apg = AlgorithmParameterGenerator.getInstance(algorithm, SecurityProvider.getProvider());
        keygen = KeyGenerator.getInstance(algorithm, SecurityProvider.getProvider());
        cipher = Cipher.getInstance(algorithm, SecurityProvider.getProvider());
    } catch (NoSuchAlgorithmException e) {
        // happens when using the command line app .jar file
        throw new IOException("Could not find a suitable javax.crypto provider for algorithm " + algorithm + "; possible reason: using an unsigned .jar file", e);
    } catch (NoSuchPaddingException e) {
        // should never happen, if this happens throw IOException instead
        throw new RuntimeException("Could not find a suitable javax.crypto provider", e);
    }
    AlgorithmParameters parameters = apg.generateParameters();
    ASN1Primitive object;
    try (ASN1InputStream input = new ASN1InputStream(parameters.getEncoded("ASN.1"))) {
        object = input.readObject();
    }
    keygen.init(128);
    SecretKey secretkey = keygen.generateKey();
    cipher.init(1, secretkey, parameters);
    byte[] bytes = cipher.doFinal(in);
    KeyTransRecipientInfo recipientInfo = computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet set = new DERSet(new RecipientInfo(recipientInfo));
    AlgorithmIdentifier algorithmId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(algorithm), object);
    EncryptedContentInfo encryptedInfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmId, new DEROctetString(bytes));
    EnvelopedData enveloped = new EnvelopedData(null, set, encryptedInfo, (ASN1Set) null);
    ContentInfo contentInfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, enveloped);
    return contentInfo.toASN1Primitive();
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyTransRecipientInfo(org.bouncycastle.asn1.cms.KeyTransRecipientInfo) AlgorithmParameterGenerator(java.security.AlgorithmParameterGenerator) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) DEROctetString(org.bouncycastle.asn1.DEROctetString) COSString(org.apache.pdfbox.cos.COSString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) DERSet(org.bouncycastle.asn1.DERSet) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) SecretKey(javax.crypto.SecretKey) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) EncryptedContentInfo(org.bouncycastle.asn1.cms.EncryptedContentInfo) Cipher(javax.crypto.Cipher) KeyGenerator(javax.crypto.KeyGenerator) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) KeyTransRecipientInfo(org.bouncycastle.asn1.cms.KeyTransRecipientInfo) RecipientInfo(org.bouncycastle.asn1.cms.RecipientInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) EnvelopedData(org.bouncycastle.asn1.cms.EnvelopedData) CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) AlgorithmParameters(java.security.AlgorithmParameters) EncryptedContentInfo(org.bouncycastle.asn1.cms.EncryptedContentInfo)

Example 4 with EnvelopedData

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

the class Envelope method fromASN1.

/**
 * EnvelopedData ::= SEQUENCE {
 *   version Version,
 *   recipientInfos RecipientInfos,
 *   encryptedContentInfo EncryptedContentInfo }
 *
 * Version ::= INTEGER
 *
 * RecipientInfos ::= SET OF RecipientInfo
 */
public static Envelope fromASN1(ASN1Encodable content) {
    ASN1Sequence sequence = (ASN1Sequence) content;
    ASN1Integer version = (ASN1Integer) sequence.getObjectAt(0);
    ASN1Set recipients = (ASN1Set) sequence.getObjectAt(1);
    ASN1Encodable encContent = sequence.getObjectAt(2);
    Envelope envelope = new Envelope();
    envelope.setVersion(version.getValue().intValue());
    envelope.setRecipientInfo(recipientInfosFromASN1Set(recipients));
    envelope.setEncData(EncContent.fromASN1(encContent));
    return envelope;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable)

Aggregations

CMSEnvelopedData (org.bouncycastle.cms.CMSEnvelopedData)3 IOException (java.io.IOException)2 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)2 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)2 CMSException (org.bouncycastle.cms.CMSException)2 CMSTypedData (org.bouncycastle.cms.CMSTypedData)2 AlgorithmParameterGenerator (java.security.AlgorithmParameterGenerator)1 AlgorithmParameters (java.security.AlgorithmParameters)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 CertificateEncodingException (java.security.cert.CertificateEncodingException)1 CertificateException (java.security.cert.CertificateException)1 X509Certificate (java.security.cert.X509Certificate)1 Date (java.util.Date)1 Cipher (javax.crypto.Cipher)1 KeyGenerator (javax.crypto.KeyGenerator)1 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)1 SecretKey (javax.crypto.SecretKey)1 COSString (org.apache.pdfbox.cos.COSString)1