Search in sources :

Example 31 with CMSException

use of org.bouncycastle.cms.CMSException in project xipki by xipki.

the class ScepResponder method createSignedData.

// method servicePkiOperation0
private ContentInfo createSignedData(CertificateList crl) throws CaException {
    CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
    cmsSignedDataGen.addCRL(new X509CRLHolder(crl));
    CMSSignedData cmsSigneddata;
    try {
        cmsSigneddata = cmsSignedDataGen.generate(new CMSAbsentContent());
    } catch (CMSException ex) {
        throw new CaException(ex.getMessage(), ex);
    }
    return cmsSigneddata.toASN1Structure();
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSAbsentContent(org.bouncycastle.cms.CMSAbsentContent) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSException(org.bouncycastle.cms.CMSException)

Example 32 with CMSException

use of org.bouncycastle.cms.CMSException in project xipki by xipki.

the class PkiMessage method encrypt.

// method encode
private CMSEnvelopedData encrypt(X509Certificate recipient, ASN1ObjectIdentifier encAlgId) throws MessageEncodingException {
    ScepUtil.requireNonNull("recipient", recipient);
    ScepUtil.requireNonNull("encAlgId", encAlgId);
    byte[] messageDataBytes;
    try {
        messageDataBytes = messageData.toASN1Primitive().getEncoded();
    } catch (IOException ex) {
        throw new MessageEncodingException(ex);
    }
    CMSEnvelopedDataGenerator edGenerator = new CMSEnvelopedDataGenerator();
    CMSTypedData envelopable = new CMSProcessableByteArray(messageDataBytes);
    RecipientInfoGenerator recipientGenerator;
    try {
        recipientGenerator = new JceKeyTransRecipientInfoGenerator(recipient);
    } catch (CertificateEncodingException ex) {
        throw new MessageEncodingException(ex);
    }
    edGenerator.addRecipientInfoGenerator(recipientGenerator);
    try {
        OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(encAlgId).build();
        CMSEnvelopedData pkcsPkiEnvelope = edGenerator.generate(envelopable, encryptor);
        return pkcsPkiEnvelope;
    } catch (CMSException ex) {
        throw new MessageEncodingException(ex);
    }
}
Also used : CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) CMSEnvelopedDataGenerator(org.bouncycastle.cms.CMSEnvelopedDataGenerator) JceKeyTransRecipientInfoGenerator(org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator) RecipientInfoGenerator(org.bouncycastle.cms.RecipientInfoGenerator) CMSTypedData(org.bouncycastle.cms.CMSTypedData) JceCMSContentEncryptorBuilder(org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) MessageEncodingException(org.xipki.scep.exception.MessageEncodingException) JceKeyTransRecipientInfoGenerator(org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator) OutputEncryptor(org.bouncycastle.operator.OutputEncryptor) CMSException(org.bouncycastle.cms.CMSException)

Example 33 with CMSException

use of org.bouncycastle.cms.CMSException in project signer by demoiselle.

the class CAdESSigner method doSign.

private byte[] doSign(byte[] content, byte[] previewSignature) {
    try {
        Security.addProvider(new BouncyCastleProvider());
        // Completa os certificados ausentes da cadeia, se houver
        if (this.certificate == null && this.certificateChain != null && this.certificateChain.length > 0) {
            this.certificate = (X509Certificate) this.certificateChain[0];
        }
        this.certificateChain = CAManager.getInstance().getCertificateChainArray(this.certificate);
        if (this.certificateChain.length < 3) {
            throw new SignerException(cadesMessagesBundle.getString("error.no.ca", this.certificate.getIssuerDN()));
        }
        Certificate[] certStore = new Certificate[] {};
        CMSSignedData cmsPreviewSignedData = null;
        // Importar todos os certificados da assinatura anterior
        if (previewSignature != null && previewSignature.length > 0) {
            cmsPreviewSignedData = new CMSSignedData(new CMSAbsentContent(), previewSignature);
            Collection<X509Certificate> previewCerts = this.getSignersCertificates(cmsPreviewSignedData);
            // previewCerts.add(this.certificate);
            certStore = previewCerts.toArray(new Certificate[] {});
        }
        setCertificateManager(new CertificateManager(this.certificate));
        // Recupera a lista de algoritmos da politica e o tamanho minimo da
        // chave
        List<AlgAndLength> listOfAlgAndLength = new ArrayList<AlgAndLength>();
        for (AlgAndLength algLength : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getAlgorithmConstraintSet().getSignerAlgorithmConstraints().getAlgAndLengths()) {
            listOfAlgAndLength.add(algLength);
        }
        AlgAndLength algAndLength = null;
        // verificar se o mesmo é permitido pela politica
        if (this.pkcs1.getAlgorithm() != null) {
            String varSetedAlgorithmOID = AlgorithmNames.getOIDByAlgorithmName(this.pkcs1.getAlgorithm());
            for (AlgAndLength algLength : listOfAlgAndLength) {
                if (algLength.getAlgID().getValue().equalsIgnoreCase(varSetedAlgorithmOID)) {
                    algAndLength = algLength;
                    SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum.valueOf(this.pkcs1.getAlgorithm());
                    String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash();
                    ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg().getAlgorithm();
                    varObjectIdentifier.setValue(varOIDAlgorithmHash);
                    AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg();
                    varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier);
                    signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier);
                }
            }
        } else {
            algAndLength = listOfAlgAndLength.get(0);
        }
        if (algAndLength == null) {
            throw new SignerException(cadesMessagesBundle.getString("error.no.algorithm.policy"));
        }
        logger.info(cadesMessagesBundle.getString("info.algorithm.id", algAndLength.getAlgID().getValue()));
        logger.info(cadesMessagesBundle.getString("info.algorithm.name", AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue())));
        logger.info(cadesMessagesBundle.getString("info.algorithm.policy.default", AlgorithmNames.getOIDByAlgorithmName(getAlgorithm())));
        logger.info(cadesMessagesBundle.getString("info.min.key.length", algAndLength.getMinKeyLength()));
        // Recupera o tamanho minimo da chave para validacao
        logger.info(cadesMessagesBundle.getString("info.validating.key.length"));
        int keyLegth = ((RSAKey) certificate.getPublicKey()).getModulus().bitLength();
        if (keyLegth < algAndLength.getMinKeyLength()) {
            throw new SignerException(cadesMessagesBundle.getString("error.min.key.length", algAndLength.getMinKeyLength().toString(), keyLegth));
        }
        AttributeFactory attributeFactory = AttributeFactory.getInstance();
        // Consulta e adiciona os atributos assinados
        ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
        logger.info(cadesMessagesBundle.getString("info.signed.attribute"));
        if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr().getObjectIdentifiers() != null) {
            for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr().getObjectIdentifiers()) {
                SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory.factory(objectIdentifier.getValue());
                signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, content, signaturePolicy, this.hash);
                signedAttributes.add(signedOrUnsignedAttribute.getValue());
            }
        }
        // Monta a tabela de atributos assinados
        AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
        // Create the table table generator that will added to the Signer
        // builder
        CMSAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(signedAttributesTable);
        // Recupera o(s) certificado(s) de confianca para validacao
        Collection<X509Certificate> trustedCAs = new HashSet<X509Certificate>();
        Collection<CertificateTrustPoint> ctp = signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSigningCertTrustCondition().getSignerTrustTrees().getCertificateTrustPoints();
        for (CertificateTrustPoint certificateTrustPoint : ctp) {
            logger.info(cadesMessagesBundle.getString("info.trust.point", certificateTrustPoint.getTrustpoint().getSubjectDN().toString()));
            trustedCAs.add(certificateTrustPoint.getTrustpoint());
        }
        // Efetua a validacao das cadeias do certificado baseado na politica
        Collection<X509Certificate> certificateChainTrusted = new HashSet<X509Certificate>();
        for (Certificate certCA : certificateChain) {
            certificateChainTrusted.add((X509Certificate) certCA);
        }
        X509Certificate rootOfCertificate = null;
        for (X509Certificate tcac : certificateChainTrusted) {
            logger.info(tcac.getIssuerDN().toString());
            if (CAManager.getInstance().isRootCA(tcac)) {
                rootOfCertificate = tcac;
            }
        }
        if (trustedCAs.contains(rootOfCertificate)) {
            logger.info(cadesMessagesBundle.getString("info.trust.in.point", rootOfCertificate.getSubjectDN()));
        } else {
            // Não encontrou na política, verificará nas cadeias do
            // componente chain-icp-brasil provavelmente certificado de
            // homologação.
            logger.warn(cadesMessagesBundle.getString("info.trust.poin.homolog"));
            CAManager.getInstance().validateRootCAs(certificateChainTrusted, certificate);
        }
        // validade da politica
        logger.info(cadesMessagesBundle.getString("info.policy.valid.period"));
        PolicyValidator pv = new PolicyValidator(this.signaturePolicy, this.policyName);
        pv.validate();
        // Realiza a assinatura do conteudo
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        gen.addCertificates(this.generatedCertStore(certStore));
        String algorithmOID = algAndLength.getAlgID().getValue();
        logger.info(cadesMessagesBundle.getString("info.algorithm.id", algorithmOID));
        SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder().setSignedAttributeGenerator(signedAttributeGenerator).setUnsignedAttributeGenerator(null).build(AlgorithmNames.getAlgorithmNameByOID(algorithmOID), this.pkcs1.getPrivateKey(), this.certificate);
        gen.addSignerInfoGenerator(signerInfoGenerator);
        CMSTypedData cmsTypedData;
        // para assinatura do hash, content nulo
        if (content == null) {
            cmsTypedData = new CMSAbsentContent();
        } else {
            cmsTypedData = new CMSProcessableByteArray(content);
        }
        // Efetua a assinatura digital do conteúdo
        CMSSignedData cmsSignedData = gen.generate(cmsTypedData, this.attached);
        setAttached(false);
        // Consulta e adiciona os atributos não assinados//
        ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector();
        logger.info(cadesMessagesBundle.getString("info.unsigned.attribute"));
        Collection<SignerInformation> vNewSigners = cmsSignedData.getSignerInfos().getSigners();
        Iterator<SignerInformation> it = vNewSigners.iterator();
        SignerInformation oSi = it.next();
        if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers() != null) {
            for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers()) {
                SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory.factory(objectIdentifier.getValue());
                if (signedOrUnsignedAttribute.getOID().equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) {
                    signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.certificateChainTimeStamp, oSi.getSignature(), signaturePolicy, this.hash);
                }
                if (// EscTimeStamp
                signedOrUnsignedAttribute.getOID().equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    outputStream.write(oSi.getSignature());
                    AttributeTable varUnsignedAttributes = oSi.getUnsignedAttributes();
                    Attribute varAttribute = varUnsignedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()));
                    outputStream.write(varAttribute.getAttrType().getEncoded());
                    outputStream.write(varAttribute.getAttrValues().getEncoded());
                    varAttribute = varUnsignedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_certificateRefs.getId()));
                    outputStream.write(varAttribute.getAttrType().getEncoded());
                    outputStream.write(varAttribute.getAttrValues().getEncoded());
                    varAttribute = varUnsignedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_revocationRefs.getId()));
                    outputStream.write(varAttribute.getAttrType().getEncoded());
                    outputStream.write(varAttribute.getAttrValues().getEncoded());
                    escTimeStampContent = outputStream.toByteArray();
                    signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.certificateChainTimeStamp, escTimeStampContent, signaturePolicy, this.hash);
                } else {
                    signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, oSi.getSignature(), signaturePolicy, this.hash);
                }
                unsignedAttributes.add(signedOrUnsignedAttribute.getValue());
                AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes);
                vNewSigners.remove(oSi);
                oSi = SignerInformation.replaceUnsignedAttributes(oSi, unsignedAttributesTable);
                vNewSigners.add(oSi);
            }
        }
        // TODO Estudar este método de contra-assinatura posteriormente
        if (previewSignature != null && previewSignature.length > 0) {
            vNewSigners.addAll(cmsPreviewSignedData.getSignerInfos().getSigners());
        }
        SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners);
        CMSSignedData oSignedData = cmsSignedData;
        cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore);
        byte[] result = cmsSignedData.getEncoded();
        logger.info(cadesMessagesBundle.getString("info.signature.ok"));
        return result;
    } catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) {
        throw new SignerException(ex);
    }
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) DefaultSignedAttributeTableGenerator(org.bouncycastle.cms.DefaultSignedAttributeTableGenerator) Attribute(org.bouncycastle.asn1.cms.Attribute) SignedOrUnsignedAttribute(org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.SignedOrUnsignedAttribute) ArrayList(java.util.ArrayList) SignedOrUnsignedAttribute(org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.SignedOrUnsignedAttribute) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) CertificateManager(org.demoiselle.signer.core.CertificateManager) SignerInformation(org.bouncycastle.cms.SignerInformation) AlgorithmIdentifier(org.demoiselle.signer.policy.engine.asn1.etsi.AlgorithmIdentifier) CertificateTrustPoint(org.demoiselle.signer.policy.engine.asn1.etsi.CertificateTrustPoint) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) CMSAttributeTableGenerator(org.bouncycastle.cms.CMSAttributeTableGenerator) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) JcaSimpleSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoGeneratorBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) ObjectIdentifier(org.demoiselle.signer.policy.engine.asn1.etsi.ObjectIdentifier) HashSet(java.util.HashSet) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) CMSTypedData(org.bouncycastle.cms.CMSTypedData) SignerAlgorithmEnum(org.demoiselle.signer.policy.impl.cades.SignerAlgorithmEnum) CMSAbsentContent(org.bouncycastle.cms.CMSAbsentContent) AlgAndLength(org.demoiselle.signer.policy.engine.asn1.etsi.AlgAndLength) AttributeFactory(org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.factory.AttributeFactory) CertificateEncodingException(java.security.cert.CertificateEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CertificateTrustPoint(org.demoiselle.signer.policy.engine.asn1.etsi.CertificateTrustPoint) PolicyValidator(org.demoiselle.signer.policy.engine.asn1.icpb.v2.PolicyValidator) SignerInfoGenerator(org.bouncycastle.cms.SignerInfoGenerator) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) CMSException(org.bouncycastle.cms.CMSException)

Example 34 with CMSException

use of org.bouncycastle.cms.CMSException in project signer by demoiselle.

the class RequestSigner method signRequest.

/**
 * Signs a time stamp request
 *
 * @param privateKey private key to sign with
 * @param certificates certificate chain
 * @param request request to be signed
 * @return The signed request
 */
public byte[] signRequest(PrivateKey privateKey, Certificate[] certificates, byte[] request, String algorithm) {
    try {
        logger.info(timeStampMessagesBundle.getString("info.timestamp.sign.request"));
        Security.addProvider(new BouncyCastleProvider());
        X509Certificate signCert = (X509Certificate) certificates[0];
        List<X509Certificate> certList = new ArrayList<>();
        certList.add(signCert);
        // setup the generator
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        String varAlgorithm = null;
        if (algorithm != null && !algorithm.isEmpty()) {
            varAlgorithm = algorithm;
        } else {
            varAlgorithm = "SHA256withRSA";
        }
        SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder().build(varAlgorithm, privateKey, signCert);
        generator.addSignerInfoGenerator(signerInfoGenerator);
        Store<?> certStore = new JcaCertStore(certList);
        generator.addCertificates(certStore);
        // Store crlStore = new JcaCRLStore(crlList);
        // generator.addCRLs(crlStore);
        // Create the signed data object
        CMSTypedData data = new CMSProcessableByteArray(request);
        CMSSignedData signed = generator.generate(data, true);
        return signed.getEncoded();
    } catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) {
        logger.info(ex.getMessage());
    }
    return null;
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) CMSTypedData(org.bouncycastle.cms.CMSTypedData) ArrayList(java.util.ArrayList) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) SignerInfoGenerator(org.bouncycastle.cms.SignerInfoGenerator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) JcaSimpleSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoGeneratorBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) CMSException(org.bouncycastle.cms.CMSException)

Example 35 with CMSException

use of org.bouncycastle.cms.CMSException in project pdfbox by apache.

the class PublicKeySecurityHandler method prepareForDecryption.

/**
 * Prepares everything to decrypt the document.
 *
 * @param encryption encryption dictionary, can be retrieved via
 * {@link PDDocument#getEncryption()}
 * @param documentIDArray document id which is returned via
 * {@link org.apache.pdfbox.cos.COSDocument#getDocumentID()} (not used by
 * this handler)
 * @param decryptionMaterial Information used to decrypt the document.
 *
 * @throws IOException If there is an error accessing data. If verbose mode
 * is enabled, the exception message will provide more details why the
 * match wasn't successful.
 */
@Override
public void prepareForDecryption(PDEncryption encryption, COSArray documentIDArray, DecryptionMaterial decryptionMaterial) throws IOException {
    if (!(decryptionMaterial instanceof PublicKeyDecryptionMaterial)) {
        throw new IOException("Provided decryption material is not compatible with the document");
    }
    setDecryptMetadata(encryption.isEncryptMetaData());
    if (encryption.getLength() != 0) {
        this.keyLength = encryption.getLength();
    }
    PublicKeyDecryptionMaterial material = (PublicKeyDecryptionMaterial) decryptionMaterial;
    try {
        boolean foundRecipient = false;
        X509Certificate certificate = material.getCertificate();
        X509CertificateHolder materialCert = null;
        if (certificate != null) {
            materialCert = new X509CertificateHolder(certificate.getEncoded());
        }
        // the decrypted content of the enveloped data that match
        // the certificate in the decryption material provided
        byte[] envelopedData = null;
        // the bytes of each recipient in the recipients array
        byte[][] recipientFieldsBytes = new byte[encryption.getRecipientsLength()][];
        int recipientFieldsLength = 0;
        int i = 0;
        StringBuilder extraInfo = new StringBuilder();
        for (; i < encryption.getRecipientsLength(); i++) {
            COSString recipientFieldString = encryption.getRecipientStringAt(i);
            byte[] recipientBytes = recipientFieldString.getBytes();
            CMSEnvelopedData data = new CMSEnvelopedData(recipientBytes);
            Collection<RecipientInformation> recipCertificatesIt = data.getRecipientInfos().getRecipients();
            int j = 0;
            for (RecipientInformation ri : recipCertificatesIt) {
                // Impl: if a matching certificate was previously found it is an error,
                // here we just don't care about it
                RecipientId rid = ri.getRID();
                if (!foundRecipient && rid.match(materialCert)) {
                    foundRecipient = true;
                    PrivateKey privateKey = (PrivateKey) material.getPrivateKey();
                    envelopedData = ri.getContent(new JceKeyTransEnvelopedRecipient(privateKey));
                    break;
                }
                j++;
                if (certificate != null) {
                    extraInfo.append('\n');
                    extraInfo.append(j);
                    extraInfo.append(": ");
                    if (rid instanceof KeyTransRecipientId) {
                        appendCertInfo(extraInfo, (KeyTransRecipientId) rid, certificate, materialCert);
                    }
                }
            }
            recipientFieldsBytes[i] = recipientBytes;
            recipientFieldsLength += recipientBytes.length;
        }
        if (!foundRecipient || envelopedData == null) {
            throw new IOException("The certificate matches none of " + i + " recipient entries" + extraInfo.toString());
        }
        if (envelopedData.length != 24) {
            throw new IOException("The enveloped data does not contain 24 bytes");
        }
        // now envelopedData contains:
        // - the 20 bytes seed
        // - the 4 bytes of permission for the current user
        byte[] accessBytes = new byte[4];
        System.arraycopy(envelopedData, 20, accessBytes, 0, 4);
        AccessPermission currentAccessPermission = new AccessPermission(accessBytes);
        currentAccessPermission.setReadOnly();
        setCurrentAccessPermission(currentAccessPermission);
        // what we will put in the SHA1 = the seed + each byte contained in the recipients array
        byte[] sha1Input = new byte[recipientFieldsLength + 20];
        // put the seed in the sha1 input
        System.arraycopy(envelopedData, 0, sha1Input, 0, 20);
        // put each bytes of the recipients array in the sha1 input
        int sha1InputOffset = 20;
        for (byte[] recipientFieldsByte : recipientFieldsBytes) {
            System.arraycopy(recipientFieldsByte, 0, sha1Input, sha1InputOffset, recipientFieldsByte.length);
            sha1InputOffset += recipientFieldsByte.length;
        }
        MessageDigest md = MessageDigests.getSHA1();
        byte[] mdResult = md.digest(sha1Input);
        // we have the encryption key ...
        encryptionKey = new byte[this.keyLength / 8];
        System.arraycopy(mdResult, 0, encryptionKey, 0, this.keyLength / 8);
    } catch (CMSException | KeyStoreException | CertificateEncodingException e) {
        throw new IOException(e);
    }
}
Also used : CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) KeyTransRecipientId(org.bouncycastle.cms.KeyTransRecipientId) RecipientId(org.bouncycastle.cms.RecipientId) PrivateKey(java.security.PrivateKey) KeyTransRecipientId(org.bouncycastle.cms.KeyTransRecipientId) JceKeyTransEnvelopedRecipient(org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) RecipientInformation(org.bouncycastle.cms.RecipientInformation) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) MessageDigest(java.security.MessageDigest) COSString(org.apache.pdfbox.cos.COSString) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

CMSException (org.bouncycastle.cms.CMSException)41 CMSSignedData (org.bouncycastle.cms.CMSSignedData)30 IOException (java.io.IOException)28 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)19 X509Certificate (java.security.cert.X509Certificate)18 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)14 CMSSignedDataGenerator (org.bouncycastle.cms.CMSSignedDataGenerator)14 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)13 CertificateEncodingException (java.security.cert.CertificateEncodingException)11 CertificateException (java.security.cert.CertificateException)10 SignerInformation (org.bouncycastle.cms.SignerInformation)9 CMSAbsentContent (org.bouncycastle.cms.CMSAbsentContent)8 SignerInformationStore (org.bouncycastle.cms.SignerInformationStore)8 InputStream (java.io.InputStream)7 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)7 TSPException (org.bouncycastle.tsp.TSPException)7 CertificateCoreException (org.demoiselle.signer.core.exception.CertificateCoreException)7 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)6 Attribute (org.bouncycastle.asn1.cms.Attribute)6 CMSTypedData (org.bouncycastle.cms.CMSTypedData)6