public byte[] getTimeStampToken(byte[] digest) throws NoSuchAlgorithmException, UnsupportedEncodingException, TSPException { TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.setCertReq(true); if (tsaOid != null) tsqGenerator.setReqPolicy(tsaOid); TimeStampRequest tsReq = tsqGenerator.generate(TSPAlgorithms.SHA1, digest, BigInteger.valueOf(100)); byte[] respBytes; try { byte[] requestBytes = tsReq.getEncoded(); URL url = new URL(tsaURL); HttpsURLConnection tsaConnection = (HttpsURLConnection) url.openConnection(); String user_pass = Base64.encodeToString((tsaUsername + ":" + tsaPassword).getBytes(), 0); tsaConnection.setRequestProperty("Authorization", "Basic " + user_pass); tsaConnection.setDoInput(true); tsaConnection.setDoOutput(true); tsaConnection.setUseCaches(false); tsaConnection.setRequestProperty("Content-Type", "application/timestamp-query"); tsaConnection.setRequestProperty("Content-Transfer-Encoding", "binary"); OutputStream out = tsaConnection.getOutputStream(); out.write(requestBytes); out.close(); InputStream inp = tsaConnection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = inp.read(buffer, 0, buffer.length)) >= 0) { baos.write(buffer, 0, bytesRead); } respBytes = baos.toByteArray(); String encoding = tsaConnection.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("base64")) { respBytes = Base64.decode(new String(respBytes), 0); } if (respBytes == null) { String error = "Error: Impossible to get TSA response"; Log.e(TAG, error); } TimeStampResponse tsRes = new TimeStampResponse(respBytes); tsRes.validate(tsReq); PKIFailureInfo failure = tsRes.getFailInfo(); int value = (failure == null) ? 0 : failure.intValue(); if (value != 0) { String error = "Error: Invalid TSA response (" + tsRes.getStatusString() + ")"; Log.e(TAG, error); return null; } TimeStampToken myTSToken = tsRes.getTimeStampToken(); if (myTSToken == null) { String error = "Error: Invalid TSA response (NULL)"; Log.e(TAG, error); return null; } return myTSToken.getEncoded(); } catch (IOException | TSPException e) { Log.e(TAG, e.getMessage()); } return null; }