Search in sources :

Example 11 with CertificateCoreException

use of org.demoiselle.signer.core.exception.CertificateCoreException in project signer by demoiselle.

the class TimeStampOperator method validate.

/**
 * Validate a time stamp
 *
 * @param content if it is assigned, the parameter hash must to be null
 * @param timeStamp timestamp to be validated
 * @param hash if it is assigned, the parameter content must to be null
 * @throws CertificateCoreException validate exception
 */
@SuppressWarnings("unchecked")
public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException {
    try {
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp));
        CMSSignedData s = timeStampToken.toCMSSignedData();
        int verified = 0;
        Store<?> certStore = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection<SignerInformation> c = signers.getSigners();
        Iterator<SignerInformation> it = c.iterator();
        while (it.hasNext()) {
            SignerInformation signer = it.next();
            Collection<?> certCollection = certStore.getMatches(signer.getSID());
            Iterator<?> certIt = certCollection.iterator();
            X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
            if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
                verified++;
            }
            cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue();
        }
        logger.info(timeStampMessagesBundle.getString("info.signature.verified", verified));
        // Valida o hash  incluso no carimbo de tempo com hash do arquivo carimbado
        byte[] calculatedHash = null;
        if (content != null) {
            Digest digest = DigestFactory.getInstance().factoryDefault();
            digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
            calculatedHash = digest.digest(content);
        } else {
            calculatedHash = hash;
        }
        if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
            logger.info(timeStampMessagesBundle.getString("info.timestamp.hash.ok"));
        } else {
            throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
        }
    } catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) {
        throw new CertificateCoreException(ex.getMessage());
    }
}
Also used : Digest(org.demoiselle.signer.cryptography.Digest) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CMSException(org.bouncycastle.cms.CMSException)

Example 12 with CertificateCoreException

use of org.demoiselle.signer.core.exception.CertificateCoreException in project signer by demoiselle.

the class DefaultExtensionLoader method load.

@Override
public void load(Object object, Field field, X509Certificate x509) {
    if (field.isAnnotationPresent(DefaultExtension.class)) {
        DefaultExtension annotation = field.getAnnotation(DefaultExtension.class);
        Object keyValue;
        BasicCertificate basicCertificate = new BasicCertificate(x509);
        switch(annotation.type()) {
            case CRL_URL:
                try {
                    keyValue = basicCertificate.getCRLDistributionPoint();
                } catch (IOException e1) {
                    throw new CertificateCoreException(coreMessagesBundle.getString("error.get.value.field", field.getName()), e1);
                }
                break;
            case SERIAL_NUMBER:
                keyValue = basicCertificate.getSerialNumber();
                break;
            case ISSUER_DN:
                try {
                    keyValue = basicCertificate.getCertificateIssuerDN().toString();
                } catch (IOException e1) {
                    throw new CertificateCoreException(coreMessagesBundle.getString("error.get.value.field", field.getName()), e1);
                }
                break;
            case SUBJECT_DN:
                try {
                    keyValue = basicCertificate.getCertificateSubjectDN().toString();
                } catch (IOException e1) {
                    throw new CertificateCoreException(coreMessagesBundle.getString("error.get.value.field", field.getName()), e1);
                }
                break;
            case KEY_USAGE:
                keyValue = basicCertificate.getICPBRKeyUsage().toString();
                break;
            case PATH_LENGTH:
                keyValue = basicCertificate.getPathLength();
                break;
            case AUTHORITY_KEY_IDENTIFIER:
                try {
                    keyValue = basicCertificate.getAuthorityKeyIdentifier();
                } catch (IOException e1) {
                    throw new CertificateCoreException(coreMessagesBundle.getString("error.get.value.field", field.getName()), e1);
                }
                break;
            case SUBJECT_KEY_IDENTIFIER:
                try {
                    keyValue = basicCertificate.getSubjectKeyIdentifier();
                } catch (IOException e1) {
                    throw new CertificateCoreException(coreMessagesBundle.getString("error.get.value.field", field.getName()), e1);
                }
                break;
            case BEFORE_DATE:
                keyValue = basicCertificate.getBeforeDate();
                break;
            case AFTER_DATE:
                keyValue = basicCertificate.getAfterDate();
                break;
            case CERTIFICATION_AUTHORITY:
                keyValue = basicCertificate.isCACertificate();
                break;
            default:
                throw new CertificateCoreException(coreMessagesBundle.getString("error.field.not.implemented", annotation.type()));
        }
        try {
            field.setAccessible(true);
            field.set(object, keyValue);
        } catch (IllegalAccessException | IllegalArgumentException | SecurityException e) {
            throw new CertificateCoreException(coreMessagesBundle.getString("error.load.value.field", field.getName()), e);
        }
    }
}
Also used : IOException(java.io.IOException) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException)

Example 13 with CertificateCoreException

use of org.demoiselle.signer.core.exception.CertificateCoreException in project signer by demoiselle.

the class CAdESTimeStampSigner method checkTimeStampOnSignature.

@Override
public List<Timestamp> checkTimeStampOnSignature(byte[] signature) {
    try {
        Security.addProvider(new BouncyCastleProvider());
        List<Timestamp> listOfTimeStamp = new ArrayList<Timestamp>();
        CMSSignedData cmsSignedData = new CMSSignedData(signature);
        SignerInformationStore signers = cmsSignedData.getSignerInfos();
        Iterator<?> it = signers.getSigners().iterator();
        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
            Attribute attributeTimeStamp = unsignedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()));
            if (attributeTimeStamp != null) {
                TimeStampOperator timeStampOperator = new TimeStampOperator();
                byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
                TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
                Timestamp timeStampSigner = new Timestamp(timeStampToken);
                timeStampOperator.validate(signer.getSignature(), varTimeStamp, null);
                listOfTimeStamp.add(timeStampSigner);
            }
        }
        return listOfTimeStamp;
    } catch (CertificateCoreException | IOException | TSPException | CMSException e) {
        throw new SignerException(e);
    }
}
Also used : TimeStampOperator(org.demoiselle.signer.timestamp.connector.TimeStampOperator) SignedOrUnsignedAttribute(org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.SignedOrUnsignedAttribute) Timestamp(org.demoiselle.signer.timestamp.Timestamp) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 14 with CertificateCoreException

use of org.demoiselle.signer.core.exception.CertificateCoreException in project signer by demoiselle.

the class CAdESTimeStampSigner method checkTimeStamp.

private Timestamp checkTimeStamp(byte[] timeStamp, byte[] content, byte[] hash) {
    try {
        Security.addProvider(new BouncyCastleProvider());
        ais = new ASN1InputStream(new ByteArrayInputStream(timeStamp));
        ASN1Sequence seq = (ASN1Sequence) ais.readObject();
        Attribute attributeTimeStamp = new Attribute((ASN1ObjectIdentifier) seq.getObjectAt(0), (ASN1Set) seq.getObjectAt(1));
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        if (content != null) {
            timeStampOperator.validate(content, varTimeStamp, null);
        } else {
            timeStampOperator.validate(null, varTimeStamp, hash);
        }
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
        Timestamp timeStampSigner = new Timestamp(timeStampToken);
        return timeStampSigner;
    } catch (CertificateCoreException | IOException | TSPException | CMSException e) {
        throw new SignerException(e);
    }
}
Also used : TimeStampOperator(org.demoiselle.signer.timestamp.connector.TimeStampOperator) SignedOrUnsignedAttribute(org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.SignedOrUnsignedAttribute) Timestamp(org.demoiselle.signer.timestamp.Timestamp) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 15 with CertificateCoreException

use of org.demoiselle.signer.core.exception.CertificateCoreException in project signer by demoiselle.

the class TimeStampOperator method createRequest.

/**
 * Creates a time stamp request, signed with the users's certificate.
 *
 * @param privateKey private key to sign with
 * @param certificates certificate chain
 * @param content  set null if signing only hash
 * @param hash  set null if signing content
 * @return A time stamp request
 * @throws CertificateCoreException exception
 */
public byte[] createRequest(PrivateKey privateKey, Certificate[] certificates, byte[] content, byte[] hash) throws CertificateCoreException {
    try {
        logger.info(timeStampMessagesBundle.getString("info.timestamp.digest"));
        Digest digest = DigestFactory.getInstance().factoryDefault();
        digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
        byte[] hashedMessage = null;
        if (content != null) {
            hashedMessage = digest.digest(content);
        // logger.info(Base64.toBase64String(hashedMessage));
        } else {
            hashedMessage = hash;
        }
        logger.info(timeStampMessagesBundle.getString("info.timestamp.prepare.request"));
        TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
        timeStampRequestGenerator.setReqPolicy(new ASN1ObjectIdentifier(TimeStampConfig.getInstance().getTSPOid()));
        timeStampRequestGenerator.setCertReq(true);
        BigInteger nonce = BigInteger.valueOf(100);
        timeStampRequest = timeStampRequestGenerator.generate(new ASN1ObjectIdentifier(TSPAlgorithms.SHA256.getId()), hashedMessage, nonce);
        byte[] request = timeStampRequest.getEncoded();
        logger.info(timeStampMessagesBundle.getString("info.timestamp.sign.request"));
        RequestSigner requestSigner = new RequestSigner();
        byte[] signedRequest = requestSigner.signRequest(privateKey, certificates, request, "SHA256withRSA");
        return signedRequest;
    } catch (IOException ex) {
        throw new CertificateCoreException(ex.getMessage());
    }
}
Also used : Digest(org.demoiselle.signer.cryptography.Digest) BigInteger(java.math.BigInteger) TimeStampRequestGenerator(org.bouncycastle.tsp.TimeStampRequestGenerator) IOException(java.io.IOException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) RequestSigner(org.demoiselle.signer.timestamp.signer.RequestSigner)

Aggregations

CertificateCoreException (org.demoiselle.signer.core.exception.CertificateCoreException)16 IOException (java.io.IOException)9 Timestamp (org.demoiselle.signer.timestamp.Timestamp)5 TSPException (org.bouncycastle.tsp.TSPException)4 TimeStampToken (org.bouncycastle.tsp.TimeStampToken)4 SignerException (org.demoiselle.signer.policy.impl.cades.SignerException)4 TimeStampOperator (org.demoiselle.signer.timestamp.connector.TimeStampOperator)4 CMSException (org.bouncycastle.cms.CMSException)3 CMSSignedData (org.bouncycastle.cms.CMSSignedData)3 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 BigInteger (java.math.BigInteger)2 KeyStoreException (java.security.KeyStoreException)2 CertificateException (java.security.cert.CertificateException)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2 BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)2 Digest (org.demoiselle.signer.cryptography.Digest)2 SignedOrUnsignedAttribute (org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.SignedOrUnsignedAttribute)2 FileNotFoundException (java.io.FileNotFoundException)1 FileOutputStream (java.io.FileOutputStream)1