Search in sources :

Example 6 with TSPException

use of org.bouncycastle.tsp.TSPException 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)

Example 7 with TSPException

use of org.bouncycastle.tsp.TSPException in project keystore-explorer by kaikramer.

the class TimeStampingClient method getTimeStampToken.

/**
 * Get RFC 3161 timeStampToken.
 *
 * @param tsaUrl Location of TSA
 * @param data The data to be time-stamped
 * @param hashAlg The algorithm used for generating a hash value of the data to be time-stamped
 * @return encoded, TSA signed data of the timeStampToken
 * @throws IOException
 */
public static byte[] getTimeStampToken(String tsaUrl, byte[] data, DigestType hashAlg) throws IOException {
    TimeStampResponse response = null;
    try {
        // calculate hash value
        MessageDigest digest = MessageDigest.getInstance(hashAlg.jce());
        byte[] hashValue = digest.digest(data);
        // Setup the time stamp request
        TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        TimeStampRequest request = tsqGenerator.generate(new ASN1ObjectIdentifier(hashAlg.oid()), hashValue, nonce);
        byte[] requestBytes = request.getEncoded();
        // send http request
        byte[] respBytes = queryServer(tsaUrl, requestBytes);
        // process response
        response = new TimeStampResponse(respBytes);
        // validate communication level attributes (RFC 3161 PKIStatus)
        response.validate(request);
        PKIFailureInfo failure = response.getFailInfo();
        int value = failure == null ? 0 : failure.intValue();
        if (value != 0) {
            throw new IOException("Server returned error code: " + String.valueOf(value));
        }
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    } catch (TSPException e) {
        throw new IOException(e);
    }
    // extract the time stamp token
    TimeStampToken tsToken = response.getTimeStampToken();
    if (tsToken == null) {
        throw new IOException("TSA returned no time stamp token: " + response.getStatusString());
    }
    return tsToken.getEncoded();
}
Also used : IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) TimeStampRequest(org.bouncycastle.tsp.TimeStampRequest) PKIFailureInfo(org.bouncycastle.asn1.cmp.PKIFailureInfo) TimeStampResponse(org.bouncycastle.tsp.TimeStampResponse) BigInteger(java.math.BigInteger) TimeStampRequestGenerator(org.bouncycastle.tsp.TimeStampRequestGenerator) TSPException(org.bouncycastle.tsp.TSPException) MessageDigest(java.security.MessageDigest) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 8 with TSPException

use of org.bouncycastle.tsp.TSPException in project pdfbox by apache.

the class CertInformationCollector method addTimestampCerts.

/**
 * Processes an embedded signed timestamp, that has been placed into a signature. The
 * certificates and its chain(s) will be processed the same way as the signature itself.
 *
 * @param signerInformation of the signature, to get unsigned attributes from it.
 * @throws IOException
 * @throws CertificateProccessingException
 */
private void addTimestampCerts(SignerInformation signerInformation) throws IOException, CertificateProccessingException {
    AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
    if (unsignedAttributes == null) {
        return;
    }
    Attribute tsAttribute = signerInformation.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
    if (tsAttribute.getAttrValues() instanceof DERSet) {
        DERSet tsSet = (DERSet) tsAttribute.getAttrValues();
        tsSet.getEncoded("DER");
        DERSequence tsSeq = (DERSequence) tsSet.getObjectAt(0);
        try {
            TimeStampToken tsToken = new TimeStampToken(new CMSSignedData(tsSeq.getEncoded("DER")));
            rootCertInfo.tsaCerts = new CertSignatureInformation();
            @SuppressWarnings("unchecked") Store<X509CertificateHolder> certificatesStore = tsToken.getCertificates();
            processSignerStore(certificatesStore, tsToken.toCMSSignedData(), rootCertInfo.tsaCerts);
        } catch (TSPException | CMSException e) {
            throw new IOException("Error parsing timestamp token", e);
        }
    }
}
Also used : Attribute(org.bouncycastle.asn1.cms.Attribute) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) IOException(java.io.IOException) DERSet(org.bouncycastle.asn1.DERSet) CMSSignedData(org.bouncycastle.cms.CMSSignedData) DERSequence(org.bouncycastle.asn1.DERSequence) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

IOException (java.io.IOException)8 TSPException (org.bouncycastle.tsp.TSPException)8 TimeStampToken (org.bouncycastle.tsp.TimeStampToken)8 CMSException (org.bouncycastle.cms.CMSException)4 CMSSignedData (org.bouncycastle.cms.CMSSignedData)4 CertificateCoreException (org.demoiselle.signer.core.exception.CertificateCoreException)4 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)3 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)3 TimeStampResponse (org.bouncycastle.tsp.TimeStampResponse)3 Timestamp (org.demoiselle.signer.timestamp.Timestamp)3 BigInteger (java.math.BigInteger)2 MessageDigest (java.security.MessageDigest)2 CertificateException (java.security.cert.CertificateException)2 TimeStampRequest (org.bouncycastle.tsp.TimeStampRequest)2 TimeStampRequestGenerator (org.bouncycastle.tsp.TimeStampRequestGenerator)2 SignerException (org.demoiselle.signer.policy.impl.cades.SignerException)2 TimeStampOperator (org.demoiselle.signer.timestamp.connector.TimeStampOperator)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SecureRandom (java.security.SecureRandom)1 X509Certificate (java.security.cert.X509Certificate)1