예제 #1
0
 /**
  * Adds a new uncomplete signature to signed doc
  *
  * @param cert signers certificate
  * @param claimedRoles signers claimed roles
  * @param adr signers address
  * @return new Signature object
  */
 public Signature prepareSignature(
     X509Certificate cert, String[] claimedRoles, SignatureProductionPlace adr)
     throws SignedDocException {
   Signature sig = new Signature(this);
   sig.setId(getNewSignatureId());
   // create SignedInfo block
   // ROB
   SignedInfo si =
       new SignedInfo(sig, RSA_SHA256_SIGNATURE_METHOD, CANONICALIZATION_METHOD_20010315);
   // add DataFile references
   for (int i = 0; i < countDataFiles(); i++) {
     DataFile df = getDataFile(i);
     Reference ref = new Reference(si, df);
     si.addReference(ref);
   }
   // create key info
   KeyInfo ki = new KeyInfo(cert);
   sig.setKeyInfo(ki);
   ki.setSignature(sig);
   CertValue cval = new CertValue();
   cval.setType(CertValue.CERTVAL_TYPE_SIGNER);
   cval.setCert(cert);
   sig.addCertValue(cval);
   CertID cid = new CertID(sig, cert, CertID.CERTID_TYPE_SIGNER);
   sig.addCertID(cid);
   // create signed properties
   SignedProperties sp = new SignedProperties(sig, cert, claimedRoles, adr);
   Reference ref = new Reference(si, sp);
   si.addReference(ref);
   sig.setSignedInfo(si);
   sig.setSignedProperties(sp);
   addSignature(sig);
   return sig;
 }
 /**
  * Handles a key-pressed event.
  *
  * @param e input key event
  */
 @Override
 public void keyPressed(KeyEvent e) {
   for (KeyInfo keyInfo : bindings.keySet()) {
     if (keyInfo.matchesEvent(e)) {
       processAction(bindings.get(keyInfo));
     }
   }
 }
  private void reorganizeRows(List<PrintElement> printElements) {
    int row = -1;
    int lastY = -1;
    KeyInfo lastRowKey = null;
    for (PrintElement printElement : printElements) {
      KeyInfo currentKeyInfo = printElement.getKeyInfo();
      if (printElement.getY() != lastY) {
        row++;
        lastY = printElement.getY();
      } else if (lastRowKey != null
          && currentKeyInfo != null
          && lastRowKey.getRowIndex() != currentKeyInfo.getRowIndex()) {
        row++;
      }
      printElement.setRow(row);
      lastRowKey = currentKeyInfo;
      if (printElement instanceof GroupPrintElements) {
        reorganizeRows(((GroupPrintElements) printElement).getPrintElements());
      }
    }

    PrintElement lastPrintElement = null;
    for (Iterator<PrintElement> iterator = printElements.iterator(); iterator.hasNext(); ) {
      PrintElement printElement = iterator.next();
      if (printElement instanceof GroupPrintElements) {
        if (((GroupPrintElements) printElement).getGroupDefinition() != null) {
          // subreport.. must continue;
          continue;
        }
      }
      if (lastPrintElement != null) {
        lastY = lastPrintElement.getJrPrintElement().getY();
        int currentY = printElement.getJrPrintElement().getY();
        if (currentY < lastY) { // page flip
          ReportSection lastSection = lastPrintElement.getReportItem().getRow().getSection();
          ReportSection currentSection = printElement.getReportItem().getRow().getSection();
          ReportSectionType lastSectionType = lastSection.getType();
          ReportSectionType currentSessionType = currentSection.getType();
          if ((asList(GROUP_HEADER, GROUP_DETAIL).contains(lastSectionType)
                  && asList(SUMARY_DATA_HEADER, SUMARY_DATA_DETAIL).contains(currentSessionType))
              || (asList(DETAIL).contains(lastSectionType)
                  && asList(DETAIL_HEADER, SUMARY_DATA_HEADER, SUMARY_DATA_DETAIL)
                      .contains(currentSessionType))) {
            if (lastPrintElement.getSource().equals(printElement.getSource())) {
              iterator.remove();
              continue;
            }
          }
        }
      }
      lastPrintElement = printElement;
    }
  }
예제 #4
0
  /**
   * Show certificate.
   *
   * @param certId certificate id
   * @throws Exception if an error occurs
   */
  @Command(description = "Show certificate")
  public void showCertificate(@Param(name = "certId", description = "Certificate ID") String certId)
      throws Exception {
    List<TokenInfo> tokens = SignerClient.execute(new ListTokens());
    for (TokenInfo token : tokens) {
      for (KeyInfo key : token.getKeyInfo()) {
        for (CertificateInfo cert : key.getCerts()) {
          if (certId.equals(cert.getId())) {
            X509Certificate x509 = readCertificate(cert.getCertificateBytes());
            System.out.println(x509);
            return;
          }
        }
      }
    }

    System.out.println("Certificate " + certId + " not found");
  }
예제 #5
0
  /**
   * 取主键的序号
   *
   * @return
   */
  private String createSerialNo(String tableName) {
    KeyInfo keyInfo;

    tableName = tableName.toLowerCase();
    if (_keyList.containsKey(tableName)) {
      keyInfo = _keyList.get(tableName);
    } else {
      // 如果缓存对象数量超过1000,则清除所有缓存对象
      if (_keyList.size() > 1000) {
        _keyList.clear();
      }

      keyInfo = new KeyInfo(POOL_SIZE, tableName);
      _keyList.put(tableName, keyInfo);
    }

    // 取新的序号
    int serial = keyInfo.getNextKey();
    return Integer.toString(serial);
  }
예제 #6
0
  /**
   * Generate key on token.
   *
   * @param tokenId token id
   * @throws Exception if an error occurs
   */
  @Command(description = "Generate key on token")
  public void generateKey(@Param(name = "tokenId", description = "Token ID") String tokenId)
      throws Exception {
    Map<String, Object> logData = new LinkedHashMap<>();
    logData.put(TOKEN_ID_PARAM, tokenId);

    KeyInfo response;

    try {
      response = SignerClient.execute(new GenerateKey(tokenId));

      logData.put(KEY_ID_PARAM, response.getId());
      AuditLogger.log(GENERATE_A_KEY_ON_THE_TOKEN_EVENT, XROAD_USER, logData);
    } catch (Exception e) {
      AuditLogger.log(GENERATE_A_KEY_ON_THE_TOKEN_EVENT, XROAD_USER, e.getMessage(), logData);

      throw e;
    }

    System.out.println(response.getId());
  }
  protected void doTest(final SplitMode splitMode, boolean txFail, boolean discard)
      throws Exception {
    waitForClusterToForm(OPTIMISTIC_TX_CACHE_NAME);

    final KeyInfo keyInfo = createKeys(OPTIMISTIC_TX_CACHE_NAME);
    final Cache<Object, String> originator = cache(0, OPTIMISTIC_TX_CACHE_NAME);
    final FilterCollection filterCollection =
        createFilters(OPTIMISTIC_TX_CACHE_NAME, discard, getCommandClass(), splitMode);

    Future<Void> put =
        fork(
            () -> {
              final DummyTransactionManager transactionManager =
                  (DummyTransactionManager) originator.getAdvancedCache().getTransactionManager();
              transactionManager.begin();
              keyInfo.putFinalValue(originator);
              final DummyTransaction transaction = transactionManager.getTransaction();
              transaction.runPrepare();
              transaction.runCommit(forceRollback());
              transaction.throwRollbackExceptionIfAny();
              return null;
            });

    filterCollection.await(30, TimeUnit.SECONDS);
    splitMode.split(this);
    filterCollection.unblock();

    try {
      put.get();
      assertFalse(txFail);
    } catch (ExecutionException e) {
      assertTrue(txFail);
    }

    checkLocksDuringPartition(splitMode, keyInfo, discard);

    mergeCluster(OPTIMISTIC_TX_CACHE_NAME);
    finalAsserts(OPTIMISTIC_TX_CACHE_NAME, keyInfo, txFail ? INITIAL_VALUE : FINAL_VALUE);
  }
예제 #8
0
  @Override
  public KeySelectorResult select(
      final KeyInfo ki, final Purpose p, final AlgorithmMethod m, final XMLCryptoContext c)
      throws KeySelectorException {

    if (ki == null) throw new KeySelectorException("KeyInfo is null");

    final SignatureMethod sm = (SignatureMethod) m;
    @SuppressWarnings("unchecked")
    final List<Object> list = ki.getContent();

    for (final Object l : list) {
      final XMLStructure s = (XMLStructure) l;
      PublicKey pk = null;
      if (s instanceof KeyValue) {
        try {
          pk = ((KeyValue) s).getPublicKey();
        } catch (final KeyException ke) {
          throw new KeySelectorException(ke);
        }

      } else if (s instanceof X509Data) {
        for (final Object d : ((X509Data) s).getContent()) {
          if (d instanceof X509Certificate) {
            pk = ((Certificate) d).getPublicKey();
          }
        }
      }

      if (pk != null) {
        final String sa = sm.getAlgorithm();
        final String ka = pk.getAlgorithm();
        if ("DSA".equalsIgnoreCase(ka) && "http://www.w3.org/2000/09/xmldsig#dsa-sha1".equals(sa)
            || "RSA".equalsIgnoreCase(ka)
                && "http://www.w3.org/2000/09/xmldsig#rsa-sha1".equals(sa)) {
          return new MyKeySelectorResult(pk);
        }
      }
    }

    throw new KeySelectorException("No KeyValue element found");
  }
예제 #9
0
  /**
   * Adds a new uncomplete signature to signed doc
   *
   * @param sdoc SignedDoc object
   * @param profile new signature profile. Use NULL for default
   * @param cert signers certificate
   * @param claimedRoles signers claimed roles
   * @param adr signers address
   * @param sId new signature id, Use NULL for default value
   * @param sSigMethod signature method uri - ddoc: SignedDoc.RSA_SHA1_SIGNATURE_METHOD, bdoc:
   *     depends on card type. Use null for default value
   * @param sDigType digest type (all other hashes but SignedInfo). Use null for default type
   * @return new Signature object
   */
  public static Signature prepareXadesBES(
      SignedDoc sdoc,
      String profile,
      X509Certificate cert,
      String[] claimedRoles,
      SignatureProductionPlace adr,
      String sId,
      String sSigMethod,
      String sDigType)
      throws DigiDocException {
    if (m_logger.isDebugEnabled())
      m_logger.debug(
          "Prepare signature in sdoc: "
              + sdoc.getFormat()
              + "/"
              + sdoc.getVersion()
              + "/"
              + sdoc.getProfile()
              + " profile: "
              + profile
              + " signer: "
              + ((cert != null)
                  ? SignedDoc.getCommonName(cert.getSubjectDN().getName())
                  : "unknown")
              + " id "
              + sId);
    boolean bWeakSig = false;
    for (int i = 0; i < sdoc.countSignatures(); i++) {
      Signature sig = sdoc.getSignature(i);
      if (sig.getAltDigestMatch()) bWeakSig = true;
    }
    if (bWeakSig) {
      m_logger.error(
          "One or more signatures has wrong DataFile hash even if alternative hash matches!");
      throw new DigiDocException(
          DigiDocException.ERR_VERIFY,
          "One or more signatures has wrong DataFile hash even if alternative hash matches!",
          null);
    }
    // count roles
    if (claimedRoles != null && claimedRoles.length > 1) {
      m_logger.error("Currently supports no more than 1 ClaimedRole");
      throw new DigiDocException(
          DigiDocException.ERR_UNSUPPORTED, "Currently supports no more than 1 ClaimedRole", null);
    }
    // cannot proceed if cert has not been read
    if (cert == null) {
      m_logger.error("Signers certificate missing during signature preparation!");
      throw new DigiDocException(
          DigiDocException.ERR_SIGNERS_CERT,
          "Signers certificate missing during signature preparation!",
          null);
    }
    boolean bCheckNonRepu = ConfigManager.instance().getBooleanProperty("KEY_USAGE_CHECK", true);
    if (bCheckNonRepu && !ConfigManager.isSignatureKey(cert)) {
      if (m_logger.isDebugEnabled())
        m_logger.debug("Signers cert does not have non-repudiation bit set!");
      throw new DigiDocException(
          DigiDocException.ERR_SIGNERS_CERT_NONREPUD,
          "Signers cert does not have non-repudiation bit set!",
          null);
    }
    Signature sig = new Signature(sdoc);
    sig.setId(sId != null ? sId : sdoc.getNewSignatureId());
    if (profile != null) { // use new profile for this signature
      sig.setProfile(profile);
      if (sdoc.getProfile() == null || sdoc.getProfile().equals(SignedDoc.BDOC_PROFILE_BES))
        sdoc.setProfile(profile); // change also container to new profile
    } else // use default profile
    sig.setProfile(sdoc.getProfile());

    // create SignedInfo block
    SignedInfo si =
        new SignedInfo(
            sig,
            ((sSigMethod != null) ? sSigMethod : SignedDoc.RSA_SHA1_SIGNATURE_METHOD),
            SignedDoc.CANONICALIZATION_METHOD_20010315);
    if (sdoc.getFormat().equals(SignedDoc.FORMAT_BDOC)
        && sdoc.getVersion().equals(SignedDoc.BDOC_VERSION_2_1)) {
      si.setCanonicalizationMethod(SignedDoc.CANONICALIZATION_METHOD_1_1);
      sdoc.setDefaultNsPref(SignedDoc.FORMAT_BDOC);
    }
    if (m_logger.isDebugEnabled())
      m_logger.debug(
          "Signer: "
              + cert.getSubjectDN().getName()
              + " EC key: "
              + isEcPubKey(cert)
              + " pre-2011: "
              + isPre2011IdCard(cert)
              + " digi-id: "
              + isDigiIdCard(cert)
              + " 2011: "
              + is2011Card(cert));
    if (sSigMethod == null) { // default values
      if (sdoc.getFormat().equals(SignedDoc.FORMAT_BDOC)) {
        if (isPre2011IdCard(cert)) {
          if (m_logger.isDebugEnabled())
            m_logger.debug("Generating rsa-sha224 signature for pre-2011 card");
          si.setSignatureMethod(SignedDoc.RSA_SHA224_SIGNATURE_METHOD);
        } else {
          String dType =
              ConfigManager.instance().getStringProperty("DIGIDOC_DIGEST_TYPE", "SHA-256");
          String sSigMeth = ConfigManager.digType2SigMeth(dType, isEcPubKey(cert));
          if (m_logger.isDebugEnabled())
            m_logger.debug("Generating digest: " + dType + " and signature: " + sSigMeth);
          if (sSigMeth != null) si.setSignatureMethod(sSigMeth);
          else
            throw new DigiDocException(
                DigiDocException.ERR_DIGEST_ALGORITHM, "Invalid digest type: " + dType, null);
        }
      }
    }
    if (sdoc.getFormat().equals(SignedDoc.FORMAT_XADES)
        || sdoc.getFormat().equals(SignedDoc.FORMAT_BDOC)) si.setId(sig.getId() + "-SignedInfo");
    // SignedDataObjectProperties
    SignedDataObjectProperties sdop = new SignedDataObjectProperties();
    // add DataFile references
    for (int i = 0; i < sdoc.countDataFiles(); i++) {
      DataFile df = sdoc.getDataFile(i);
      if (sdoc.getFormat().equals(SignedDoc.FORMAT_BDOC)) {
        if (!df.isDigestsCalculated()) {
          try {
            InputStream is = null;
            if (df.getDfCacheFile() != null) is = df.getBodyAsStream();
            if (is == null) is = sdoc.findDataFileAsStream(df.getFileName());
            if (is == null) is = new java.io.FileInputStream(df.getFileName());
            df.calcHashes(is);
          } catch (java.io.FileNotFoundException ex) {
            throw new DigiDocException(
                DigiDocException.ERR_READ_FILE, "Cannot read file: " + df.getFileName(), null);
          }
        }
      } else {
        if (!df.isDigestsCalculated()) df.calculateFileSizeAndDigest(null);
      }
      if (m_logger.isDebugEnabled()) m_logger.debug("Add ref for df: " + df.getId());
      Reference ref = new Reference(si, df, sDigType);
      if (sdoc.getFormat().equals(SignedDoc.FORMAT_XADES)
          || sdoc.getFormat().equals(SignedDoc.FORMAT_BDOC)) ref.setId(sig.getId() + "-ref-" + i);
      si.addReference(ref);
      if (sdoc.getFormat().equals(SignedDoc.FORMAT_BDOC)
          && sdoc.getVersion().equals(SignedDoc.BDOC_VERSION_2_1)) {
        DataObjectFormat dof = new DataObjectFormat("#" + ref.getId());
        dof.setMimeType(df.getMimeType());
        sdop.addDataObjectFormat(dof);
      }
    }
    // manifest.xml reference - bdoc 2.1-s ei allkirjasta manifest.xml-i
    // create key info
    KeyInfo ki = new KeyInfo(cert);
    if (sdoc.getFormat().equals(SignedDoc.FORMAT_XADES)
        || sdoc.getFormat().equals(SignedDoc.FORMAT_BDOC)) ki.setId(sig.getId() + "-KeyInfo");
    sig.setKeyInfo(ki);
    ki.setSignature(sig);
    registerCert(cert, CertValue.CERTVAL_TYPE_SIGNER, null, sig);
    if (m_logger.isDebugEnabled()) m_logger.debug("Signer cert: " + cert.getSubjectDN().getName());
    boolean bUseLocal = ConfigManager.instance().getBooleanProperty("DIGIDOC_USE_LOCAL_TSL", false);

    if (sdoc.getFormat().equals(SignedDoc.FORMAT_XADES)
        || sdoc.getFormat().equals(SignedDoc.FORMAT_BDOC)) {
      TrustServiceFactory tslFac = ConfigManager.instance().getTslFactory();
      // first lookup in TSL-s
      X509Certificate ca = tslFac.findCaForCert(cert, bUseLocal, null);
      if (ca != null) {
        String caId = sig.getId() + "-" + ConvertUtils.getCommonName(ca.getSubjectDN().getName());
        registerCert(ca, CertValue.CERTVAL_TYPE_CA, caId, sig);
      }
      // TODO: maybe copy local CA certs to signature until the first ca that is in TSL?
    }
    // create signed properties
    SignedProperties sp = new SignedProperties(sig, cert, claimedRoles, adr);
    sig.setSignedProperties(sp);
    // bdoc 2.0 nonce policy
    if (sdoc.getFormat().equals(SignedDoc.FORMAT_BDOC)
        && sdoc.getVersion().equals(SignedDoc.BDOC_VERSION_2_1)
        && (sig.getProfile().equals(SignedDoc.BDOC_PROFILE_TM)
            || sig.getProfile().equals(SignedDoc.BDOC_PROFILE_BES)
            || sig.getProfile().equals(SignedDoc.BDOC_PROFILE_CL)
            || sig.getProfile().equals(SignedDoc.BDOC_PROFILE_TMA))) {
      sp.setSignedDataObjectProperties(sdop);
      Identifier id1 = new Identifier(Identifier.OIDAsURN);
      id1.setUri(BDOC_210_OID);
      ObjectIdentifier oid1 = new ObjectIdentifier(id1);
      SignaturePolicyId spi1 = new SignaturePolicyId(oid1);
      spi1.setDigestAlgorithm(BDOC_210_DIGEST_METHOD);
      spi1.setDigestValue(ConvertUtils.hex2bin(BDOC_210_DIGEST_HEX));
      // System.out.println("Spec hash: " + BDOC_210_DIGEST_HEX + " b64: " +
      // Base64Util.encode(ConvertUtils.hex2bin(BDOC_210_DIGEST_HEX)));
      spi1.addSigPolicyQualifier(new SpUri(BDOC_210_SPURI));
      SignaturePolicyIdentifier spid1 = new SignaturePolicyIdentifier(spi1);
      sp.setSignaturePolicyIdentifier(spid1);
    } else {
      SignaturePolicyIdentifier spid1 = new SignaturePolicyIdentifier(null);
      sp.setSignaturePolicyIdentifier(spid1);
    }
    Reference ref = new Reference(si, sp, sDigType);
    if (sdoc.getFormat().equals(SignedDoc.FORMAT_XADES)
        || sdoc.getFormat().equals(SignedDoc.FORMAT_BDOC)) ref.setId(sig.getId() + "-ref-sp");
    ref.setType(SignedDoc.SIGNEDPROPERTIES_TYPE);
    si.addReference(ref);
    sig.setSignedInfo(si);
    sdoc.addSignature(sig);
    if (m_logger.isDebugEnabled())
      m_logger.debug("Prepared signature: " + sig.getId() + "/" + sig.getProfile());

    return sig;
  }