Exemplo n.º 1
0
  @Override
  public String getDigest(final DigestAlgorithm digestAlgorithm) {

    final byte[] digestBytes = DSSUtils.digest(digestAlgorithm, getBytes());
    final String base64Encode = DSSUtils.base64Encode(digestBytes);
    return base64Encode;
  }
Exemplo n.º 2
0
  private void setSigningCertificateAndChain(
      final WSParameters wsParameters, final SignatureParameters params) {

    final byte[] signingCertBytes = wsParameters.getSigningCertificateBytes();
    if (signingCertBytes == null) {
      return;
    }
    final X509Certificate x509SigningCertificate = DSSUtils.loadCertificate(signingCertBytes);
    params.setSigningCertificate(x509SigningCertificate);

    final List<X509Certificate> chain = new ArrayList<X509Certificate>();
    chain.add(x509SigningCertificate);
    final List<byte[]> certificateChainByteArrayList =
        wsParameters.getCertificateChainByteArrayList();
    if (certificateChainByteArrayList != null) {

      for (final byte[] x509CertificateBytes : certificateChainByteArrayList) {

        final X509Certificate x509Certificate = DSSUtils.loadCertificate(x509CertificateBytes);
        if (!chain.contains(x509Certificate)) {

          chain.add(x509Certificate);
        }
      }
    }
    params.setCertificateChain(chain);
  }
  private X509Certificate readLOTLCertificate() throws DSSException {

    X509Certificate lotlCert;
    if (lotlCertificate == null) {

      final String msg =
          "The LOTL signing certificate property must contain a reference to a certificate.";
      diagnosticInfo.put(lotlUrl, msg);
      throw new DSSException(msg);
    }
    InputStream inputStream = null;
    try {

      inputStream = getLotlCertificateInputStream();
      lotlCert = DSSUtils.loadCertificate(inputStream);
    } catch (DSSException e) {

      final String msg = "Cannot read LOTL signing certificate.";
      diagnosticInfo.put(lotlUrl, msg);
      throw e;
    } finally {

      DSSUtils.closeQuietly(inputStream);
    }
    return lotlCert;
  }
Exemplo n.º 4
0
  /**
   * Configure the proxy with the required credential if needed
   *
   * @param httpClientBuilder
   * @param credsProvider
   * @param url
   * @return
   * @throws java.net.MalformedURLException
   */
  private HttpClientBuilder configureProxy(
      HttpClientBuilder httpClientBuilder, CredentialsProvider credsProvider, String url)
      throws DSSException {

    try {

      if (proxyPreferenceManager == null) {
        return httpClientBuilder;
      }
      final String protocol = new URL(url).getProtocol();

      final boolean proxyHTTPS =
          Protocol.isHttps(protocol) && proxyPreferenceManager.isHttpsEnabled();
      final boolean proxyHTTP = Protocol.isHttp(protocol) && proxyPreferenceManager.isHttpEnabled();

      if (!proxyHTTPS && !proxyHTTP) {
        return httpClientBuilder;
      }

      String proxyHost = null;
      int proxyPort = 0;
      String proxyUser = null;
      String proxyPassword = null;

      if (proxyHTTPS) {
        LOG.debug("Use proxy https parameters");
        final Long port = proxyPreferenceManager.getHttpsPort();
        proxyPort = port != null ? port.intValue() : 0;
        proxyHost = proxyPreferenceManager.getHttpsHost();
        proxyUser = proxyPreferenceManager.getHttpsUser();
        proxyPassword = proxyPreferenceManager.getHttpsPassword();
      } else // noinspection ConstantConditions
      if (proxyHTTP) {
        LOG.debug("Use proxy http parameters");
        final Long port = proxyPreferenceManager.getHttpPort();
        proxyPort = port != null ? port.intValue() : 0;
        proxyHost = proxyPreferenceManager.getHttpHost();
        proxyUser = proxyPreferenceManager.getHttpUser();
        proxyPassword = proxyPreferenceManager.getHttpPassword();
      }

      if (DSSUtils.isNotEmpty(proxyUser) && DSSUtils.isNotEmpty(proxyPassword)) {
        LOG.debug("proxy user: "******":" + proxyPassword);
        AuthScope proxyAuth = new AuthScope(proxyHost, proxyPort);
        UsernamePasswordCredentials proxyCredentials =
            new UsernamePasswordCredentials(proxyUser, proxyPassword);
        credsProvider.setCredentials(proxyAuth, proxyCredentials);
      }

      LOG.debug("proxy host/port: " + proxyHost + ":" + proxyPort);
      // TODO SSL peer shut down incorrectly when protocol is https
      HttpHost proxy = new HttpHost(proxyHost, proxyPort, Protocol.HTTP.getName());
      return httpClientBuilder.setProxy(proxy);
    } catch (MalformedURLException e) {
      throw new DSSException(e);
    }
  }
  /**
   * Gets the LOTL certificate as an inputStream stream
   *
   * @return the inputStream stream
   * @throws java.io.IOException
   */
  private InputStream getLotlCertificateInputStream() throws DSSException {

    InputStream inputStream = null;
    try {

      if (lotlCertificate.toLowerCase().startsWith(CP)) {

        final String lotlCertificate_ = lotlCertificate.substring(CP.length() - 1);
        inputStream = getClass().getResourceAsStream(lotlCertificate_);
      } else if (lotlCertificate.toLowerCase().startsWith(FILE)) {

        final URL url = new File(lotlCertificate.substring(FILE.length())).toURI().toURL();
        inputStream = url.openStream();
      } else {

        final URL url = new URL(lotlCertificate);
        inputStream = url.openStream();
      }
      return inputStream;
    } catch (Exception e) {

      DSSUtils.closeQuietly(inputStream);
      throw new DSSException(e);
    }
  }
Exemplo n.º 6
0
  /**
   * This method retrieves data using FTP protocol .
   *
   * @param urlString
   * @return
   */
  protected byte[] ftpGet(final String urlString) {

    InputStream inputStream = null;
    try {

      final URL url = new URL(urlString);
      inputStream = url.openStream();
      return DSSUtils.toByteArray(inputStream);
    } catch (Exception e) {

      LOG.warn(e.getMessage());
    } finally {
      DSSUtils.closeQuietly(inputStream);
    }
    return null;
  }
  /**
   * @param url
   * @param territory
   * @param signingCertList
   */
  protected void loadTSL(
      final String url, final String territory, final List<X509Certificate> signingCertList) {

    if (DSSUtils.isBlank(url)) {

      LOG.error("The URL is blank!");
      return;
    }
    final String trimmedUrl = url.trim();
    try {

      diagnosticInfo.put(trimmedUrl, "Loading");
      LOG.info("Downloading TrustStatusList for '{}' from url= {}", territory, trimmedUrl);
      final TrustStatusList countryTSL = getTrustStatusList(trimmedUrl, signingCertList);
      loadAllCertificatesFromOneTSL(countryTSL);
      LOG.info(".... done for '{}'", territory);
      diagnosticInfo.put(trimmedUrl, "Loaded " + new Date().toString());
    } catch (final DSSNullReturnedException e) {

      LOG.info("Download skipped.");
      // do nothing: it can happened when a mock data loader is used.
    } catch (final RuntimeException e) {

      makeATrace(trimmedUrl, "Other problem: " + e.toString(), e);
    }
  }
Exemplo n.º 8
0
 private byte[] fileGet(String urlString) {
   try {
     return DSSUtils.toByteArray(new URL(urlString).openStream());
   } catch (IOException e) {
     LOG.warn(e.toString(), e);
   }
   return null;
 }
Exemplo n.º 9
0
 /** @return the pkcs11File */
 public File getPkcs11File() {
   if (pkcs11File == null) {
     final String path = userPreferencesDAO.getPKCS11LibraryPath();
     if (DSSUtils.isNotEmpty(path)) {
       pkcs11File = new File(path);
     }
   }
   return pkcs11File;
 }
Exemplo n.º 10
0
  protected byte[] getContent(final HttpEntity responseEntity) throws DSSException {

    try {

      final InputStream content = responseEntity.getContent();
      final byte[] bytes = DSSUtils.toByteArray(content);
      content.close();
      return bytes;
    } catch (IOException e) {
      throw new DSSException(e);
    }
  }
Exemplo n.º 11
0
  @Override
  public void saveIncremental() throws IOException {
    try {
      document.saveIncremental(tempInput, tempOutput);
      tempOutput.close();
      tempInput.close();

      tempInput = new FileInputStream(tempDocumentOut);
      DSSUtils.copy(tempInput, output);
      tempInput.close();
    } catch (COSVisitorException e) {
      throw new IOException(e);
    }
  }
Exemplo n.º 12
0
  @Override
  public void save(final String filePath) {

    try {

      final FileOutputStream fos = new FileOutputStream(filePath);
      DSSUtils.write(getBytes(), fos);
      fos.close();
    } catch (FileNotFoundException e) {
      throw new DSSException(e);
    } catch (DSSException e) {
      throw new DSSException(e);
    } catch (IOException e) {
      throw new DSSException(e);
    }
  }
Exemplo n.º 13
0
  public PdfBoxWriter(PDDocument document, OutputStream output) throws IOException {

    this.document = document;
    try {
      this.output = output;

      File tempDocumentIn = new File("target/copyoffile.pdf");
      tempOutput = new FileOutputStream(tempDocumentIn);
      document.save(tempOutput);
      tempOutput.close();

      tempInput = new FileInputStream(tempDocumentIn);
      tempDocumentOut = new File("target/copyoffileout.pdf");
      tempOutput = new FileOutputStream(tempDocumentOut);
      DSSUtils.copy(tempInput, tempOutput);
      tempInput.close();

      tempInput = new FileInputStream(tempDocumentIn);

    } catch (COSVisitorException e) {
      throw new IOException(e);
    }
  }
Exemplo n.º 14
0
 /**
  * Creates dss document that retains the data in memory
  *
  * @param inputStream input stream representing the document
  * @param name the file name if the data originates from a file
  * @param mimeType the mime type of the file if the data originates from a file
  * @throws IOException
  */
 public InMemoryDocument(final InputStream inputStream, final String name, final MimeType mimeType)
     throws DSSException {
   this(DSSUtils.toByteArray(inputStream), name, mimeType);
 }
Exemplo n.º 15
0
 /** @return */
 public boolean hasSignaturePolicyAlgo() {
   return !DSSUtils.isEmpty(signaturePolicyAlgo);
 }
  private void alignSnSki() {
    final ServiceDigitalIdentityMultivalueAdapter serviceDigitalIdentityMultivalueAdapter =
        (ServiceDigitalIdentityMultivalueAdapter)
            certificateButton.getMultivaluePanel().getMultivalueModel();
    final List<DigitalIdentityType> digitalId =
        serviceDigitalIdentityMultivalueAdapter.getDigitalIdentityList().getDigitalId();

    boolean useSn = boxSN.isSelected();
    boolean useSki = boxSKI.isSelected();
    serviceDigitalIdentityMultivalueAdapter.setSn(useSn);
    serviceDigitalIdentityMultivalueAdapter.setSki(useSki);

    boolean snAdded = false;
    boolean skiAdded = false;

    // cleanup existing SN & SKI (might not be aligned with the certificates chosen
    for (Iterator<DigitalIdentityType> iterator = digitalId.iterator(); iterator.hasNext(); ) {
      DigitalIdentityType digitalIdentityType = iterator.next();
      if (digitalIdentityType.getX509SubjectName() != null) {
        iterator.remove();
      }
      if (digitalIdentityType.getX509SKI() != null) {
        iterator.remove();
      }
    }

    // cleanup SubjetName display
    distinguishedName.setText("");
    distinguishedName.setCaretPosition(0);

    // search new values
    for (final String key : serviceDigitalIdentityMultivalueAdapter.getKeys()) {
      final DigitalIdentityModel digitalIdentityModel =
          serviceDigitalIdentityMultivalueAdapter.getValue(key);
      if (digitalIdentityModel != null) {
        final X509Certificate certificate = digitalIdentityModel.getCertificate();
        if (certificate != null) {

          final DigitalIdentityType digitalIdentitySN = new DigitalIdentityType();
          final String x509SubjectName =
              certificate.getSubjectX500Principal().getName(X500Principal.RFC2253);
          digitalIdentitySN.setX509SubjectName(x509SubjectName);

          // updateUI too
          // TODO: might be interesting to display all different subjectName (with error message) if
          // use has chosen different certificitates
          distinguishedName.setText(x509SubjectName);
          distinguishedName.setCaretPosition(0);

          if (!snAdded && useSn) {
            digitalId.add(digitalIdentitySN);
            snAdded = true;
          }
          if (!skiAdded && useSki) {
            final byte[] skiValue = DSSUtils.getSki(certificate);
            if (skiValue != null && skiValue.length > 0) {
              final DigitalIdentityType digitalIdentitySKI = new DigitalIdentityType();
              digitalIdentitySKI.setX509SKI(skiValue);
              digitalId.add(digitalIdentitySKI);
              skiAdded = true;
            }
          }
        }
      }
    }
  }
Exemplo n.º 17
0
 /**
  * Creates dss document that retains the data in memory
  *
  * @param inputStream input stream representing the document
  * @throws DSSException
  */
 public InMemoryDocument(final InputStream inputStream) throws DSSException {
   this(DSSUtils.toByteArray(inputStream), null, null);
 }
Exemplo n.º 18
0
  /**
   * @throws IOException
   * @throws NoSuchAlgorithmException
   * @throws DSSException
   */
  public void signDocument() throws IOException, NoSuchAlgorithmException, DSSException {

    final SignatureModel model = getModel();

    final File fileToSign = model.getSelectedFile();
    final SignatureTokenConnection tokenConnection = model.getTokenConnection();
    final DSSPrivateKeyEntry privateKey = model.getSelectedPrivateKey();

    final SignatureParameters parameters = new SignatureParameters();
    parameters.setPrivateKeyEntry(privateKey);
    parameters.setSigningToken(tokenConnection);

    DigestAlgorithm digestAlgorithm = model.getSignatureDigestAlgorithm();
    if (digestAlgorithm == null) {
      parameters.setDigestAlgorithm(DigestAlgorithm.SHA256);
    } else {
      parameters.setDigestAlgorithm(digestAlgorithm);
    }
    if (model.isTslSignatureCheck()) {

      parameters.clearCertificateChain();
      parameters.setCertificateChain(parameters.getSigningCertificate());
      parameters.setSignatureLevel(SignatureLevel.XAdES_BASELINE_B);
      parameters.setSignaturePackaging(SignaturePackaging.ENVELOPED);

      final List<DSSReference> references = new ArrayList<DSSReference>();

      DSSReference dssReference = new DSSReference();
      dssReference.setId("xml_ref_id");
      dssReference.setUri("");

      final List<DSSTransform> transforms = new ArrayList<DSSTransform>();

      DSSTransform dssTransform = new DSSTransform();
      dssTransform.setAlgorithm(CanonicalizationMethod.ENVELOPED);
      transforms.add(dssTransform);

      dssTransform = new DSSTransform();
      dssTransform.setAlgorithm(CanonicalizationMethod.EXCLUSIVE);
      transforms.add(dssTransform);

      dssReference.setTransforms(transforms);
      references.add(dssReference);

      //			System.out.println("###APPLET - REFERENCES:");
      //			for (DSSReference reference : references) {
      //				System.out.println("    --> " + reference.getId() + "/" + reference.getUri() + "/" +
      // reference.getType());
      //				final List<DSSTransform> transforms_ = reference.getTransforms();
      //				for (DSSTransform transform : transforms_) {
      //
      //					System.out.println("    --> ---> " + transform.getElementName() + "/" +
      // transform.getTextContent() + "/" + transform.getAlgorithm());
      //				}
      //			}
      parameters.setReferences(references);

    } else {

      final String signatureLevelString = model.getLevel();
      final SignatureLevel signatureLevel = SignatureLevel.valueByName(signatureLevelString);
      parameters.setSignatureLevel(signatureLevel);
      parameters.setSignaturePackaging(model.getPackaging());

      if (model.isClaimedCheck()) {
        parameters.bLevel().addClaimedSignerRole(model.getClaimedRole());
      }
      if (model.isSignaturePolicyCheck()) {

        final byte[] hashValue = DSSUtils.base64Decode(model.getSignaturePolicyValue());
        final Policy policy = new Policy();
        policy.setId(model.getSignaturePolicyId());
        final DigestAlgorithm policyDigestAlgorithm =
            DigestAlgorithm.forName(model.getSignaturePolicyAlgo());
        policy.setDigestAlgorithm(policyDigestAlgorithm);
        policy.setDigestValue(hashValue);
        parameters.bLevel().setSignaturePolicy(policy);
      }
    }
    final DSSDocument signedDocument =
        SigningUtils.signDocument(serviceURL, fileToSign, parameters);
    final FileOutputStream fos = new FileOutputStream(model.getTargetFile());
    DSSUtils.copy(signedDocument.openStream(), fos);
    fos.close();
  }