Search in sources :

Example 6 with Timestamp

use of org.demoiselle.signer.timestamp.Timestamp in project signer by demoiselle.

the class CAdESTimeStampSignerTest method testCheckTimeStampWithHash.

// @Test
public void testCheckTimeStampWithHash() {
    String fileTimeStampDirName = "local_e_nome_do_arquivo_da_assinatura";
    String fileContentDirName = "local_e_nome_do_arquivo_assinado";
    try {
        byte[] timeStampFile = readContent(fileTimeStampDirName);
        byte[] content = readContent(fileContentDirName);
        // gera o hash do conteudo
        java.security.MessageDigest md = java.security.MessageDigest.getInstance(DigestAlgorithmEnum.SHA_256.getAlgorithm());
        byte[] hash = md.digest(content);
        CAdESTimeStampSigner varCAdESTimeStampSigner = new CAdESTimeStampSigner();
        Timestamp varTimeStamp = varCAdESTimeStampSigner.checkTimeStampWithHash(timeStampFile, hash);
        if (varTimeStamp != null) {
            System.out.println(varTimeStamp.toString());
            assertTrue(true);
        } else {
            assertTrue(false);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}
Also used : Timestamp(org.demoiselle.signer.timestamp.Timestamp) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException)

Example 7 with Timestamp

use of org.demoiselle.signer.timestamp.Timestamp in project signer by demoiselle.

the class CAdESTimeStampSignerTest method testCheckTimeStampOnSignature.

// @Test
public void testCheckTimeStampOnSignature() {
    String fileSignatureDirName = "local_e_nome_do_arquivo_da_assinatura";
    try {
        byte[] signatureFile = readContent(fileSignatureDirName);
        CAdESTimeStampSigner varCAdESTimeStampSigner = new CAdESTimeStampSigner();
        List<Timestamp> listTimeStamp = varCAdESTimeStampSigner.checkTimeStampOnSignature(signatureFile);
        if (!listTimeStamp.isEmpty()) {
            for (Timestamp ts : listTimeStamp) {
                System.out.println(ts.toString());
                assertTrue(true);
            }
        } else {
            assertTrue(false);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}
Also used : Timestamp(org.demoiselle.signer.timestamp.Timestamp) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException)

Example 8 with Timestamp

use of org.demoiselle.signer.timestamp.Timestamp 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 9 with Timestamp

use of org.demoiselle.signer.timestamp.Timestamp 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 10 with Timestamp

use of org.demoiselle.signer.timestamp.Timestamp in project signer by demoiselle.

the class TimeStampOperator method invoke.

/**
 * Sends the time stamp request {@link createRequest} to a time stamp server
 *
 * @param request request to be sent
 * @return The time stamp returned by the server
 */
public byte[] invoke(byte[] request) throws CertificateCoreException {
    try {
        logger.info(timeStampMessagesBundle.getString("info.timestamp.init.request"));
        Connector connector = ConnectorFactory.buildConnector(ConnectionType.SOCKET);
        connector.setHostname(TimeStampConfig.getInstance().getTspHostname());
        connector.setPort(TimeStampConfig.getInstance().getTSPPort());
        logger.info(timeStampMessagesBundle.getString("info.timestamp.response"));
        inputStream = connector.connect(request);
        long tempo;
        // Valor do timeout da verificacao de dados disponiveis para leitura
        int timeOut = 3500;
        // Verificando se os 4 bytes iniciais estao disponiveis para leitura
        for (tempo = System.currentTimeMillis() + timeOut; inputStream.available() < 4 && System.currentTimeMillis() < tempo; ) {
            try {
                Thread.sleep(1L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // Lendo tamanho total
        byte[] tamanhoRetorno = new byte[4];
        inputStream.read(tamanhoRetorno, 0, 4);
        int tamanho = new BigInteger(tamanhoRetorno).intValue();
        // Verificando se os bytes na quantidade "tamanho" estao disponiveis
        if (System.currentTimeMillis() < tempo) {
            while (inputStream.available() < tamanho && System.currentTimeMillis() < tempo) {
                try {
                    Thread.sleep(1L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (System.currentTimeMillis() >= tempo) {
                logger.error(timeStampMessagesBundle.getString("info.timestamp.timeout"));
            }
        } else {
            logger.error(timeStampMessagesBundle.getString("info.timestamp.timeout"));
        }
        // Lendo flag
        byte[] retornoFlag = new byte[1];
        inputStream.read(retornoFlag, 0, 1);
        // tamanho total menos o tamanho da flag
        tamanho -= 1;
        // Lendo dados carimbo
        byte[] retornoCarimboDeTempo = new byte[tamanho];
        inputStream.read(retornoCarimboDeTempo, 0, tamanho);
        timeStampResponse = new TimeStampResponse(retornoCarimboDeTempo);
        logger.info(timeStampMessagesBundle.getString("info.timestamp.status", timeStampResponse.getStatus()));
        switch(timeStampResponse.getStatus()) {
            case 0:
                {
                    logger.info(timeStampMessagesBundle.getString("info.pkistatus.granted"));
                    break;
                }
            case 1:
                {
                    logger.info(timeStampMessagesBundle.getString("info.pkistatus.grantedWithMods"));
                    break;
                }
            case 2:
                {
                    logger.info(timeStampMessagesBundle.getString("error.pkistatus.rejection"));
                    throw new CertificateCoreException(timeStampMessagesBundle.getString("error.pkistatus.rejection"));
                }
            case 3:
                {
                    logger.info(timeStampMessagesBundle.getString("error.pkistatus.waiting"));
                    throw new CertificateCoreException(timeStampMessagesBundle.getString("error.pkistatus.waiting"));
                }
            case 4:
                {
                    logger.info(timeStampMessagesBundle.getString("error.pkistatus.revocation.warn"));
                    throw new CertificateCoreException(timeStampMessagesBundle.getString("error.pkistatus.revocation.warn"));
                }
            case 5:
                {
                    logger.info(timeStampMessagesBundle.getString("error.pkistatus.revocation.notification"));
                    throw new CertificateCoreException(timeStampMessagesBundle.getString("error.pkistatus.revocation.notification"));
                }
            default:
                {
                    logger.info(timeStampMessagesBundle.getString("error.pkistatus.unknown"));
                    throw new CertificateCoreException(timeStampMessagesBundle.getString("error.pkistatus.unknown"));
                }
        }
        // ok
        int failInfo = -1;
        if (timeStampResponse.getFailInfo() != null) {
            failInfo = Integer.parseInt(new String(timeStampResponse.getFailInfo().getBytes()));
        }
        logger.info(timeStampMessagesBundle.getString("info.timestamp.failinfo", failInfo));
        switch(failInfo) {
            case 0:
                logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.badAlg"));
                break;
            case 2:
                logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.badRequest"));
                break;
            case 5:
                logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.badDataFormat"));
                break;
            case 14:
                logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.timeNotAvailable"));
                break;
            case 15:
                logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.unacceptedPolicy"));
                break;
            case 16:
                logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.unacceptedExtension"));
                break;
            case 17:
                logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.addInfoNotAvailable"));
                break;
            case 25:
                logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.systemFailure"));
                break;
        }
        timeStampResponse.validate(timeStampRequest);
        TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
        this.setTimestamp(new Timestamp(timeStampToken));
        if (timeStampToken == null) {
            throw new CertificateCoreException(timeStampMessagesBundle.getString("error.timestamp.token.null"));
        }
        connector.close();
        // Imprime os dados do carimbo de tempo
        logger.info(timestamp.toString());
        // Retorna o carimbo de tempo gerado
        return timestamp.getEncoded();
    } catch (CertificateCoreException | TSPException | IOException e) {
        throw new CertificateCoreException(e.getMessage());
    }
}
Also used : IOException(java.io.IOException) Timestamp(org.demoiselle.signer.timestamp.Timestamp) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) TimeStampResponse(org.bouncycastle.tsp.TimeStampResponse) BigInteger(java.math.BigInteger) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken)

Aggregations

Timestamp (org.demoiselle.signer.timestamp.Timestamp)10 IOException (java.io.IOException)8 CertificateCoreException (org.demoiselle.signer.core.exception.CertificateCoreException)7 SignerException (org.demoiselle.signer.policy.impl.cades.SignerException)6 TSPException (org.bouncycastle.tsp.TSPException)5 CMSException (org.bouncycastle.cms.CMSException)4 CMSSignedData (org.bouncycastle.cms.CMSSignedData)4 BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)4 TimeStampOperator (org.demoiselle.signer.timestamp.connector.TimeStampOperator)4 KeyStoreException (java.security.KeyStoreException)3 TimeStampToken (org.bouncycastle.tsp.TimeStampToken)3 SignedOrUnsignedAttribute (org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.SignedOrUnsignedAttribute)3 X509Certificate (java.security.cert.X509Certificate)2 ParseException (java.text.ParseException)2 Date (java.util.Date)2 LinkedList (java.util.LinkedList)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2 ASN1UTCTime (org.bouncycastle.asn1.ASN1UTCTime)2 Attribute (org.bouncycastle.asn1.cms.Attribute)2 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)2