use of org.bouncycastle.tsp.TimeStampToken in project signer by demoiselle.
the class CAdESSigner method validateTimestamp.
/**
* validade a timestampo on signature
* @param attributeTimeStamp
* @param varSignature
* @return
*/
@Deprecated
private Timestamp validateTimestamp(Attribute attributeTimeStamp, byte[] varSignature) {
try {
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(varSignature, varTimeStamp, null);
return timeStampSigner;
} catch (CertificateCoreException | IOException | TSPException | CMSException e) {
throw new SignerException(e);
}
}
use of org.bouncycastle.tsp.TimeStampToken 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());
}
}
use of org.bouncycastle.tsp.TimeStampToken in project poi by apache.
the class TSPTimeStampService method timeStamp.
@SuppressWarnings("unchecked")
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
// digest the message
MessageDigest messageDigest = CryptoFunctions.getMessageDigest(signatureConfig.getTspDigestAlgo());
byte[] digest = messageDigest.digest(data);
// generate the TSP request
BigInteger nonce = new BigInteger(128, new SecureRandom());
TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
requestGenerator.setCertReq(true);
String requestPolicy = signatureConfig.getTspRequestPolicy();
if (requestPolicy != null) {
requestGenerator.setReqPolicy(new ASN1ObjectIdentifier(requestPolicy));
}
ASN1ObjectIdentifier digestAlgoOid = mapDigestAlgoToOID(signatureConfig.getTspDigestAlgo());
TimeStampRequest request = requestGenerator.generate(digestAlgoOid, digest, nonce);
byte[] encodedRequest = request.getEncoded();
// create the HTTP POST request
Proxy proxy = Proxy.NO_PROXY;
if (signatureConfig.getProxyUrl() != null) {
URL proxyUrl = new URL(signatureConfig.getProxyUrl());
String host = proxyUrl.getHost();
int port = proxyUrl.getPort();
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getByName(host), (port == -1 ? 80 : port)));
}
HttpURLConnection huc = (HttpURLConnection) new URL(signatureConfig.getTspUrl()).openConnection(proxy);
if (signatureConfig.getTspUser() != null) {
String userPassword = signatureConfig.getTspUser() + ":" + signatureConfig.getTspPass();
String encoding = DatatypeConverter.printBase64Binary(userPassword.getBytes(Charset.forName("iso-8859-1")));
huc.setRequestProperty("Authorization", "Basic " + encoding);
}
huc.setRequestMethod("POST");
huc.setConnectTimeout(20000);
huc.setReadTimeout(20000);
// also sets method to POST.
huc.setDoOutput(true);
huc.setRequestProperty("User-Agent", signatureConfig.getUserAgent());
huc.setRequestProperty("Content-Type", signatureConfig.isTspOldProtocol() ? "application/timestamp-request" : // "; charset=ISO-8859-1");
"application/timestamp-query");
OutputStream hucOut = huc.getOutputStream();
hucOut.write(encodedRequest);
// invoke TSP service
huc.connect();
int statusCode = huc.getResponseCode();
if (statusCode != 200) {
LOG.log(POILogger.ERROR, "Error contacting TSP server ", signatureConfig.getTspUrl() + ", had status code " + statusCode + "/" + huc.getResponseMessage());
throw new IOException("Error contacting TSP server " + signatureConfig.getTspUrl() + ", had status code " + statusCode + "/" + huc.getResponseMessage());
}
// HTTP input validation
String contentType = huc.getHeaderField("Content-Type");
if (null == contentType) {
throw new RuntimeException("missing Content-Type header");
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
IOUtils.copy(huc.getInputStream(), bos);
LOG.log(POILogger.DEBUG, "response content: ", HexDump.dump(bos.toByteArray(), 0, 0));
if (!contentType.startsWith(signatureConfig.isTspOldProtocol() ? "application/timestamp-response" : "application/timestamp-reply")) {
throw new RuntimeException("invalid Content-Type: " + contentType + // dump the first few bytes
": " + HexDump.dump(bos.toByteArray(), 0, 0, 200));
}
if (bos.size() == 0) {
throw new RuntimeException("Content-Length is zero");
}
// TSP response parsing and validation
TimeStampResponse timeStampResponse = new TimeStampResponse(bos.toByteArray());
timeStampResponse.validate(request);
if (0 != timeStampResponse.getStatus()) {
LOG.log(POILogger.DEBUG, "status: " + timeStampResponse.getStatus());
LOG.log(POILogger.DEBUG, "status string: " + timeStampResponse.getStatusString());
PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
if (null != failInfo) {
LOG.log(POILogger.DEBUG, "fail info int value: " + failInfo.intValue());
if (/*PKIFailureInfo.unacceptedPolicy*/
(1 << 8) == failInfo.intValue()) {
LOG.log(POILogger.DEBUG, "unaccepted policy");
}
}
throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
}
TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
SignerId signerId = timeStampToken.getSID();
BigInteger signerCertSerialNumber = signerId.getSerialNumber();
X500Name signerCertIssuer = signerId.getIssuer();
LOG.log(POILogger.DEBUG, "signer cert serial number: " + signerCertSerialNumber);
LOG.log(POILogger.DEBUG, "signer cert issuer: " + signerCertIssuer);
// TSP signer certificates retrieval
Collection<X509CertificateHolder> certificates = timeStampToken.getCertificates().getMatches(null);
X509CertificateHolder signerCert = null;
Map<X500Name, X509CertificateHolder> certificateMap = new HashMap<X500Name, X509CertificateHolder>();
for (X509CertificateHolder certificate : certificates) {
if (signerCertIssuer.equals(certificate.getIssuer()) && signerCertSerialNumber.equals(certificate.getSerialNumber())) {
signerCert = certificate;
}
certificateMap.put(certificate.getSubject(), certificate);
}
// TSP signer cert path building
if (signerCert == null) {
throw new RuntimeException("TSP response token has no signer certificate");
}
List<X509Certificate> tspCertificateChain = new ArrayList<X509Certificate>();
JcaX509CertificateConverter x509converter = new JcaX509CertificateConverter();
x509converter.setProvider("BC");
X509CertificateHolder certificate = signerCert;
do {
LOG.log(POILogger.DEBUG, "adding to certificate chain: " + certificate.getSubject());
tspCertificateChain.add(x509converter.getCertificate(certificate));
if (certificate.getSubject().equals(certificate.getIssuer())) {
break;
}
certificate = certificateMap.get(certificate.getIssuer());
} while (null != certificate);
// verify TSP signer signature
X509CertificateHolder holder = new X509CertificateHolder(tspCertificateChain.get(0).getEncoded());
DefaultCMSSignatureAlgorithmNameGenerator nameGen = new DefaultCMSSignatureAlgorithmNameGenerator();
DefaultSignatureAlgorithmIdentifierFinder sigAlgoFinder = new DefaultSignatureAlgorithmIdentifierFinder();
DefaultDigestAlgorithmIdentifierFinder hashAlgoFinder = new DefaultDigestAlgorithmIdentifierFinder();
BcDigestCalculatorProvider calculator = new BcDigestCalculatorProvider();
BcRSASignerInfoVerifierBuilder verifierBuilder = new BcRSASignerInfoVerifierBuilder(nameGen, sigAlgoFinder, hashAlgoFinder, calculator);
SignerInformationVerifier verifier = verifierBuilder.build(holder);
timeStampToken.validate(verifier);
// verify TSP signer certificate
if (signatureConfig.getTspValidator() != null) {
signatureConfig.getTspValidator().validate(tspCertificateChain, revocationData);
}
LOG.log(POILogger.DEBUG, "time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());
return timeStampToken.getEncoded();
}
use of org.bouncycastle.tsp.TimeStampToken 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());
}
}
use of org.bouncycastle.tsp.TimeStampToken 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();
}
Aggregations