Ejemplo n.º 1
0
  @Test
  public void testCMD() throws Exception {
    Authentication auth =
        new SkeletonKeyClientBuilder()
            .username("wburke")
            .password("geheim")
            .authentication("Skeleton Key");
    ResteasyClient client = new ResteasyClient();
    WebTarget target = client.target(generateBaseUrl());
    String tiny = target.path("tokens").path("url").request().post(Entity.json(auth), String.class);
    System.out.println(tiny);
    System.out.println("tiny.size: " + tiny.length());
    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    X509Certificate cert = KeyTools.generateTestCertificate(keyPair);

    byte[] signed = p7s(privateKey, cert, null, tiny.getBytes());

    CMSSignedData data = new CMSSignedData(signed);
    byte[] bytes = (byte[]) data.getSignedContent().getContent();
    System.out.println("BYTES: " + new String(bytes));
    System.out.println("size:" + signed.length);
    System.out.println("Base64.size: " + Base64.encodeBytes(signed).length());

    SignerInformation signer =
        (SignerInformation) data.getSignerInfos().getSigners().iterator().next();
    System.out.println("valid: " + signer.verify(cert, "BC"));
  }
  private SignatureData getFromCmsSignature(
      SignatureVerificationRequest signatureVerificationRequest,
      SignatureVerificationResponse response)
      throws CMSException {
    String signature = signatureVerificationRequest.getSignature();
    byte[] decoded = Base64.decode(signature);
    CMSSignedData cmsSignedData = new CMSSignedData(decoded);
    String encodedSignedData = new String((byte[]) cmsSignedData.getSignedContent().getContent());

    // Fetch information about the issuers
    List<String> certInfos = new ArrayList<String>();
    Collection certificates = cmsSignedData.getCertificates().getMatches(null);
    for (Object certificate : certificates) {
      X509CertificateHolder holder = (X509CertificateHolder) certificate;
      certInfos.add(holder.getSubject().toString());
      CertificateInfo ci = new CertificateInfo();
      ci.setSubjectDn(holder.getSubject().toString());
      ci.setValidTo(simpleDateFormat.format(holder.getNotAfter()));
      response.getCertificateInfos().getCertificateInfo().add(ci);
    }

    // Fetch timestamp
    Date signingDate = findTimestamp(cmsSignedData);
    String dateString = simpleDateFormat.format(signingDate);
    response.setSignatureDate(dateString);

    // Create the SignatureData to be verified
    SignatureData signData = new SignatureData();
    signData.setEncodedTbs(encodedSignedData);
    signData.setSignature(signature);
    ELegType clientType = new ELegType("test", "test", PkiClient.NETMAKER_NETID_4);
    signData.setClientType(clientType);
    return signData;
  }
Ejemplo n.º 3
0
 private static ProvisioningProfile create(File file) {
   InputStream in = null;
   try {
     in = new BufferedInputStream(new FileInputStream(file));
     CMSSignedData data = new CMSSignedData(in);
     byte[] content = (byte[]) data.getSignedContent().getContent();
     NSDictionary dict = (NSDictionary) PropertyListParser.parse(content);
     return new ProvisioningProfile(file, dict);
   } catch (Exception e) {
     throw new RuntimeException(e);
   } finally {
     IOUtils.closeQuietly(in);
   }
 }
Ejemplo n.º 4
0
  /**
   * If the {@code DSSDocument} is a CMS message and the signed content's content is not null then
   * the {@code CMSSignedData} is returned. All exceptions are hidden
   *
   * @param dssDocument
   * @return {@code CMSSignedData} or {@code null}
   */
  public static CMSSignedData getOriginalSignedData(final DSSDocument dssDocument) {

    CMSSignedData originalSignedData = null;

    try {
      // check if input toSignDocument is already signed
      originalSignedData = new CMSSignedData(dssDocument.getBytes());
      if (originalSignedData.getSignedContent().getContent() == null) {
        originalSignedData = null;
      }
    } catch (Exception e) {
      // not a parallel signature
    }
    return originalSignedData;
  }
Ejemplo n.º 5
0
  public boolean verifyEstrai(String pathBase, File pathFilesSignedd) {

    boolean esito = false;

    byte[] buffer = new byte[(int) pathFilesSignedd.length()];
    DataInputStream in;
    try {
      in = new DataInputStream(new FileInputStream(pathFilesSignedd));

      in.readFully(buffer);
      in.close();

      Security.addProvider(new BouncyCastleProvider());
      CMSSignedData signature = new CMSSignedData(buffer);
      SignerInformation signer =
          (SignerInformation) signature.getSignerInfos().getSigners().iterator().next();
      CertStore cs = signature.getCertificatesAndCRLs("Collection", "BC");

      Iterator iter = cs.getCertificates(signer.getSID()).iterator();
      X509Certificate certificate = (X509Certificate) iter.next();
      CMSProcessable sc = signature.getSignedContent();
      byte[] data = (byte[]) sc.getContent();

      // Verifie la signature
      // System.out.println(signer.verify(certificate, "BC"));
      esito = signer.verify(certificate.getPublicKey(), "BC");
      System.out.println("Verifica FILE: " + esito);

      String fatturapaName =
          pathFilesSignedd.getName().substring(0, pathFilesSignedd.getName().length() - 4).trim();
      System.out.println(" test:" + fatturapaName);
      FileOutputStream envfos = new FileOutputStream(new File(pathBase, fatturapaName));
      envfos.write(data);
      envfos.close();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return esito;
  }
Ejemplo n.º 6
0
  // ROB duplicato del metodo in VerifyTask ...
  private InputStream getCmsInputStream(String path) {

    FileInputStream is = null;
    try {
      is = new FileInputStream(path);
    } catch (FileNotFoundException ex) {
      System.out.println("Errore nell'acquisizione del file: " + ex);
    }
    ByteArrayInputStream bais = null;
    try {
      CMSSignedData cms = new CMSSignedData(is);

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      cms.getSignedContent().write(baos);
      bais = new ByteArrayInputStream(baos.toByteArray());
    } catch (CMSException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return bais;
  }
  @Test
  public void testCMSSignature() throws Exception {
    // setup
    byte[] toBeSigned = "hello world".getBytes();
    String signatureDescription = "Test CMS Signature";
    CMSTestSignatureService signatureService =
        new CMSTestSignatureService(toBeSigned, signatureDescription);

    KeyPair keyPair = PkiTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate =
        PkiTestUtils.generateCertificate(
            keyPair.getPublic(),
            "CN=Test",
            notBefore,
            notAfter,
            null,
            keyPair.getPrivate(),
            true,
            0,
            null,
            null,
            new KeyUsage(KeyUsage.nonRepudiation));
    List<X509Certificate> signingCertificateChain = new LinkedList<X509Certificate>();
    signingCertificateChain.add(certificate);

    // operate
    DigestInfo digestInfo =
        signatureService.preSign(null, signingCertificateChain, null, null, null);

    // verify
    assertNotNull(digestInfo);
    byte[] digestValue = digestInfo.digestValue;
    LOG.debug("digest value: " + Hex.encodeHexString(digestValue));
    assertNotNull(digestValue);
    assertEquals(signatureDescription, digestInfo.description);
    assertEquals("SHA1", digestInfo.digestAlgo);

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
    byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestValue);
    byte[] signatureValue = cipher.doFinal(digestInfoValue);
    LOG.debug("signature value: " + Hex.encodeHexString(signatureValue));

    // operate
    signatureService.postSign(signatureValue, signingCertificateChain);

    // verify
    byte[] cmsSignature = signatureService.getCMSSignature();
    CMSSignedData signedData = new CMSSignedData(cmsSignature);
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator<SignerInformation> iter = signers.getSigners().iterator();
    while (iter.hasNext()) {
      SignerInformation signer = iter.next();
      SignerId signerId = signer.getSID();
      assertTrue(signerId.match(certificate));
      assertTrue(signer.verify(keyPair.getPublic(), BouncyCastleProvider.PROVIDER_NAME));
    }
    byte[] data = (byte[]) signedData.getSignedContent().getContent();
    assertArrayEquals(toBeSigned, data);
  }
 public byte[] getEncodedEncapsulatedData() throws IOException {
   CMSProcessable content = cmsSignedData.getSignedContent();
   if (content == null) return null;
   return (byte[]) content.getContent();
 }