Package br.net.woodstock.rockframework.security.sign

Examples of br.net.woodstock.rockframework.security.sign.SignerException


          }
        }
      }
      return true;
    } catch (Exception e) {
      throw new SignerException(e);
    }
  }
View Full Code Here


  }

  @Override
  public byte[] sign(final byte[] data) {
    if (this.privateKey == null) {
      throw new SignerException("Private key is null");
    }
    try {
      Signature s = Signature.getInstance(this.signType.getAlgorithm());

      s.initSign(this.privateKey);
      s.update(data);

      byte[] bytes = s.sign();
      return bytes;
    } catch (NoSuchAlgorithmException e) {
      throw new SignerException(e);
    } catch (InvalidKeyException e) {
      throw new SignerException(e);
    } catch (SignatureException e) {
      throw new SignerException(e);
    }
  }
View Full Code Here

  }

  @Override
  public boolean verify(final byte[] data, final byte[] signature) {
    if (this.publicKey == null) {
      throw new SignerException("Public key is null");
    }
    try {
      Signature s = Signature.getInstance(this.signType.getAlgorithm());

      s.initVerify(this.publicKey);
      s.update(data);

      boolean ok = s.verify(signature);
      return ok;
    } catch (NoSuchAlgorithmException e) {
      throw new SignerException(e);
    } catch (InvalidKeyException e) {
      throw new SignerException(e);
    } catch (SignatureException e) {
      throw new SignerException(e);
    }
  }
View Full Code Here

      for (Alias alias : this.parameters.getAliases()) {
        currentData = this.singleSign(data, alias);
      }
      return currentData;
    } catch (Exception e) {
      throw new SignerException(e);
    }
  }
View Full Code Here

    try {
      Store store = this.parameters.getStore();
      PrivateKeyEntry privateEntry = (PrivateKeyEntry) store.get(alias, StoreEntryType.PRIVATE_KEY);

      if (privateEntry == null) {
        throw new SignerException("Private key '" + alias.getName() + " not found in store");
      }

      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

      PrivateKey privateKey = privateEntry.getValue();
      Certificate[] chain = privateEntry.getChain();
      X509Certificate certificate = (X509Certificate) chain[0];

      DigestType digestType = this.getDigestTypeFromSignature(certificate.getSigAlgName());
      Calendar calendar = Calendar.getInstance();

      PdfReader reader = new PdfReader(data);
      PdfStamper stamper = PdfStamper.createSignature(reader, outputStream, PDFSigner.PDF_SIGNATURE_VERSION, null, true);

      PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
      appearance.setCrypto(privateKey, chain, null, PdfSignatureAppearance.SELF_SIGNED);

      if (this.parameters.getSignatureInfo() != null) {
        appearance.setContact(this.parameters.getSignatureInfo().getContactInfo());
        appearance.setLocation(this.parameters.getSignatureInfo().getLocation());
        appearance.setReason(this.parameters.getSignatureInfo().getReason());
      }

      appearance.setSignDate(calendar);

      PdfSignature signature = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
      signature.setReason(appearance.getReason());
      signature.setLocation(appearance.getLocation());
      signature.setContact(appearance.getContact());
      signature.setDate(new PdfDate(appearance.getSignDate()));

      if ((this.parameters.getSignatureInfo() != null) && (ConditionUtils.isNotEmpty(this.parameters.getSignatureInfo().getName()))) {
        signature.setName(this.parameters.getSignatureInfo().getName());
      } else {
        signature.setName(BouncyCastleProviderHelper.getName(certificate.getSubjectX500Principal()));
      }

      appearance.setCryptoDictionary(signature);

      int contentSize = 0x2502;
      HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
      exc.put(PdfName.CONTENTS, new Integer(contentSize));
      appearance.preClose(exc);

      Digester digester = new BasicDigester(digestType);
      byte[] rangeStream = IOUtils.toByteArray(appearance.getRangeStream());
      byte[] hash = digester.digest(rangeStream);

      TSAClient tsc = null;
      if (this.parameters.getTimeStampClient() != null) {
        tsc = new DelegateITextTSAClient(this.parameters.getTimeStampClient());
      }

      byte[] oscp = null;
      if (ConditionUtils.isNotEmpty(chain)) {
        String oscpUrl = PdfPKCS7.getOCSPURL(certificate);
        X509Certificate parentCertificate = null;

        for (Certificate c : chain) {
          if (!certificate.equals(c)) {
            parentCertificate = (X509Certificate) c;
            break;
          }
        }

        if (parentCertificate != null) {
          if ((oscpUrl != null) && (oscpUrl.trim().length() > 0)) {
            OcspClient ocspClient = new OcspClientBouncyCastle(certificate, parentCertificate, oscpUrl);
            oscp = ocspClient.getEncoded();
          }
        }
      }

      PdfPKCS7 pkcs7 = new PdfPKCS7(privateKey, chain, null, digestType.getAlgorithm(), null, false);
      byte[] authenticatedAttributes = pkcs7.getAuthenticatedAttributeBytes(hash, calendar, oscp);
      pkcs7.update(authenticatedAttributes, 0, authenticatedAttributes.length);

      if (this.parameters.getSignatureInfo() != null) {
        pkcs7.setLocation(this.parameters.getSignatureInfo().getLocation());
        pkcs7.setReason(this.parameters.getSignatureInfo().getReason());
        pkcs7.setSignName(this.parameters.getSignatureInfo().getName());
      }

      if (tsc == null) {
        pkcs7.setSignDate(calendar);
      }

      byte[] encodedPkcs7 = pkcs7.getEncodedPKCS7(hash, calendar, tsc, oscp);

      byte[] output = new byte[(contentSize - 2) / 2];

      System.arraycopy(encodedPkcs7, 0, output, 0, encodedPkcs7.length);

      PdfDictionary newDictionary = new PdfDictionary();
      PdfString content = new PdfString(output);
      content.setHexWriting(true);
      newDictionary.put(PdfName.CONTENTS, content);
      appearance.close(newDictionary);

      return outputStream.toByteArray();
    } catch (Exception e) {
      throw new SignerException(e);
    }
  }
View Full Code Here

          }
        }
      }
      return true;
    } catch (Exception e) {
      throw new SignerException(e);
    }
  }
View Full Code Here

      for (Alias alias : this.parameters.getAliases()) {
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) this.parameters.getStore().get(alias, StoreEntryType.PRIVATE_KEY);

        if (privateKeyEntry == null) {
          throw new SignerException("PrivateKey not found for alias '" + alias.getName() + "'");
        }

        PrivateKey privateKey = privateKeyEntry.getValue();
        Certificate[] chain = privateKeyEntry.getChain();
        Certificate certificate = chain[0];

        JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(signatureType.getAlgorithm());
        contentSignerBuilder.setProvider(BouncyCastleProviderHelper.PROVIDER_NAME);

        ContentSigner contentSigner = contentSignerBuilder.build(privateKey);

        JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder();
        digestCalculatorProviderBuilder.setProvider(BouncyCastleProviderHelper.PROVIDER_NAME);
        DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build();

        JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digestCalculatorProvider);

        if (this.parameters.isDataDigested()) {
          Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(data)));
          ASN1EncodableVector v = new ASN1EncodableVector();
          v.add(attr);
          signerInfoGeneratorBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)));
        }

        SignerInfoGenerator signerInfoGenerator = signerInfoGeneratorBuilder.build(contentSigner, (X509Certificate) certificate);

        signedDataGenerator.addSignerInfoGenerator(signerInfoGenerator);
        signedDataGenerator.addCertificates(this.getCertificateStore(chain));
      }

      CMSTypedData content = null;
      boolean encapsulate = true;

      if (this.parameters.isDataDigested()) {
        content = new CMSAbsentContent();
        encapsulate = false;
      } else {
        if ((this.parameters.isMergeSignatures()) && (this.isSigned(data))) {
          CMSSignedData signedData = new CMSSignedData(data);
          signedDataGenerator.addSigners(signedData.getSignerInfos());
          content = (CMSTypedData) signedData.getSignedContent();
        } else {
          content = new CMSProcessableByteArray(data);
        }

        if (PKCS7SignatureMode.DETACHED.equals(mode)) {
          encapsulate = false;
        }
      }

      CMSSignedData signedData = null;

      if (this.parameters.isDataDigested()) {
        signedData = signedDataGenerator.generate(CMSSignedGenerator.DATA, null, false, Security.getProvider(BouncyCastleProviderHelper.PROVIDER_NAME), true);
      } else {
        signedData = signedDataGenerator.generate(content, encapsulate);
      }

      if (timeStampClient != null) {
        SignerInformationStore signerInformationStore = signedData.getSignerInfos();
        List list = new ArrayList();
        for (Object o : signerInformationStore.getSigners()) {
          SignerInformation signerInformation = (SignerInformation) o;
          TimeStamp timeStamp = timeStampClient.getTimeStamp(signerInformation.getSignature());
          DERObject derObject = BouncyCastleProviderHelper.toDERObject(timeStamp.getEncoded());
          DERSet derSet = new DERSet(derObject);

          Hashtable hashtable = new Hashtable();
          Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, derSet);
          hashtable.put(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, attribute);

          AttributeTable unsignedAtts = new AttributeTable(hashtable);

          list.add(SignerInformation.replaceUnsignedAttributes(signerInformation, unsignedAtts));
        }

        SignerInformationStore tmpSignerInformationStore = new SignerInformationStore(list);

        signedData = CMSSignedData.replaceSigners(signedData, tmpSignerInformationStore);
      }

      return signedData.getEncoded();
    } catch (Exception e) {
      throw new SignerException(e);
    }
  }
View Full Code Here

      if (content != null) {
        return this.verifyAttached(data, signature);
      }
      return this.verifyDetached(data, signature);
    } catch (Exception e) {
      throw new SignerException(e);
    }
  }
View Full Code Here

        }
      }

      return CollectionUtils.toArray(signatures, Signature.class);
    } catch (Exception e) {
      throw new SignerException(e);
    }
  }
View Full Code Here

    try {
      CMSSignedData signedData = new CMSSignedData(data);
      CMSProcessable processable = signedData.getSignedContent();
      return this.getContent(processable);
    } catch (Exception e) {
      throw new SignerException(e);
    }
  }
View Full Code Here

TOP

Related Classes of br.net.woodstock.rockframework.security.sign.SignerException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.