Esempio n. 1
0
  public static String getPkcs11SignerConfWithoutAlgo(
      final String pkcs11ModuleName,
      final P11SlotIdentifier slotId,
      final P11KeyIdentifier keyId,
      final int parallelism) {
    ParamChecker.assertNotNull("keyId", keyId);

    CmpUtf8Pairs conf = new CmpUtf8Pairs();
    conf.putUtf8Pair("parallelism", Integer.toString(parallelism));

    if (pkcs11ModuleName != null && pkcs11ModuleName.length() > 0) {
      conf.putUtf8Pair("module", pkcs11ModuleName);
    }

    if (slotId.getSlotId() != null) {
      conf.putUtf8Pair("slot-id", slotId.getSlotId().toString());
    } else {
      conf.putUtf8Pair("slot", slotId.getSlotIndex().toString());
    }

    if (keyId.getKeyId() != null) {
      conf.putUtf8Pair("key-id", Hex.toHexString(keyId.getKeyId()));
    }

    if (keyId.getKeyLabel() != null) {
      conf.putUtf8Pair("key-label", keyId.getKeyLabel());
    }

    return conf.getEncoded();
  }
Esempio n. 2
0
  public static void bcHMacMD5() {
    HMac hmac = new HMac(new MD5Digest());
    hmac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("aaaaaaaaaa")));
    hmac.update(src.getBytes(), 0, src.getBytes().length);

    byte[] hmacMD5Bytes = new byte[hmac.getMacSize()];
    hmac.doFinal(hmacMD5Bytes, 0);

    System.out.println(
        "bc hmacMD5:" + org.bouncycastle.util.encoders.Hex.toHexString(hmacMD5Bytes));
  }
  /**
   * Get bytes from an InputStream.
   *
   * @param is
   * @param md5Hash
   * @return An byte array containing all the bytes read from the InputStream. <code>null</code> is
   *     returned if error occurred when reading inputs.
   * @throws SocketTimeoutException
   * @throws IllegalAccessException MD5 error.
   */
  public static byte[] get(InputStream is, String md5Hash)
      throws SocketTimeoutException, IllegalAccessException {
    // Read the response from server
    byte[] returnedBytes = null;
    byte[] buffer = new byte[128];
    LinkedList<byte[]> downloadedList = new LinkedList<byte[]>();

    int len;
    int downloaded = 0; // The total length of downloaded bytes.
    try {
      while (true) {
        // Read from stream.
        len = is.read(buffer);

        if (len == -1) {
          // Reading ends.
          break;
        } else {
          byte[] currentBytes = new byte[len];
          System.arraycopy(buffer, 0, currentBytes, 0, len);
          downloadedList.add(currentBytes);
        }
        downloaded += len;
      }

      // Construct the returned byte array by collecting all the bytes from the list.
      returnedBytes = new byte[downloaded];
      int copiedIndex = 0;
      Iterator<byte[]> list = downloadedList.iterator();
      while (list.hasNext()) {
        byte[] currentBytes = list.next();
        System.arraycopy(currentBytes, 0, returnedBytes, copiedIndex, currentBytes.length);
        copiedIndex += currentBytes.length;
      }

      // If MD5 is given, check the stream result.
      if (md5Hash != null && md5Hash.length() > 0) {
        // System.out.println("[StreamReader] Check MD5");
        ByteArrayInputStream bais = null;
        DigestInputStream dis = null;
        MessageDigest digest = null;
        try {
          digest = MessageDigest.getInstance("MD5");
          bais = new ByteArrayInputStream(returnedBytes);
          dis = new DigestInputStream(bais, digest);

          while (dis.read(buffer) > 0) {}

          String receiveMD5 = Hex.toHexString(digest.digest());
          if (receiveMD5.compareToIgnoreCase(md5Hash) != 0)
            throw new IllegalAccessException("The MD5 of the request body is not correct.");
          // else
          //	System.out.println("[StreamReader] MD5 OK.");
        } catch (NoSuchAlgorithmException e) {
          e.printStackTrace();
        } finally {
          if (dis != null) dis.close();
          if (bais != null) bais.close();
        }
      }

      return returnedBytes;
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } finally {
      try {
        if (is != null) is.close();
      } catch (Exception e) {
      }
    }
  }
Esempio n. 4
0
  @Override
  protected void onDocumentSigned(byte[] byteArray) {
    try {
      InputStream inputStream = new ByteArrayInputStream(byteArray);

      PDDocument document = PDDocument.load(inputStream);
      List<PDSignature> signatures = document.getSignatureDictionaries();
      assertEquals(1, signatures.size());

      for (PDSignature pdSignature : signatures) {
        byte[] contents = pdSignature.getContents(byteArray);
        byte[] signedContent = pdSignature.getSignedContent(byteArray);

        logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

        // IOUtils.write(contents, new FileOutputStream("sig.p7s"));

        ASN1InputStream asn1sInput = new ASN1InputStream(contents);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);

        SignedData signedData =
            SignedData.getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

        ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
        ASN1ObjectIdentifier oidDigestAlgo =
            ASN1ObjectIdentifier.getInstance(
                ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
        DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
        logger.info("DIGEST ALGO : " + digestAlgorithm);

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
        logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);
        assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

        ASN1Encodable content = encapContentInfo.getContent();
        logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
        assertNull(content);

        List<X509Certificate> certificates = extractCertificates(signedData);

        ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
        logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
        SignerInfo signedInfo =
            SignerInfo.getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

        ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
        logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

        List<ASN1ObjectIdentifier> attributeOids = new ArrayList<ASN1ObjectIdentifier>();
        for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
          Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
          attributeOids.add(attribute.getAttrType());
        }
        logger.info("List of OID for Auth Attrb : " + attributeOids);

        Attribute attributeDigest = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(1));
        assertEquals(PKCSObjectIdentifiers.pkcs_9_at_messageDigest, attributeDigest.getAttrType());

        ASN1OctetString asn1ObjString =
            ASN1OctetString.getInstance(attributeDigest.getAttrValues().getObjectAt(0));
        String embeddedDigest = Base64.encode(asn1ObjString.getOctets());
        logger.info("MESSAGE DIGEST : " + embeddedDigest);

        byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
        String computedDigestSignedContentEncodeBase64 = Base64.encode(digestSignedContent);
        logger.info(
            "COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
        assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

        SignerIdentifier sid = signedInfo.getSID();
        logger.info("SIGNER IDENTIFIER : " + sid.getId());

        IssuerAndSerialNumber issuerAndSerialNumber =
            IssuerAndSerialNumber.getInstance(signedInfo.getSID());
        ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
        logger.info(
            "ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

        BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
        X509Certificate signerCertificate = null;
        for (X509Certificate x509Certificate : certificates) {
          if (serial.equals(x509Certificate.getSerialNumber())) {
            signerCertificate = x509Certificate;
          }
        }
        assertNotNull(signerCertificate);

        String algorithm = signerCertificate.getPublicKey().getAlgorithm();
        EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

        ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
        String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

        logger.info("SIGNATURE VALUE : " + signatureValue);

        Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
        cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
        byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

        ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

        ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
        logger.info("DECRYPTED : " + seqDecrypt);

        DigestInfo digestInfo = new DigestInfo(seqDecrypt);
        assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

        String decryptedDigestEncodeBase64 = Base64.encode(digestInfo.getDigest());
        logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

        byte[] encoded = authenticatedAttributeSet.getEncoded();
        byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
        String computedDigestFromSignatureEncodeBase64 = Base64.encode(digest);
        logger.info(
            "COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

        assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

        IOUtils.closeQuietly(inputDecrypted);
        IOUtils.closeQuietly(asn1sInput);
      }

      IOUtils.closeQuietly(inputStream);
      document.close();
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      fail(e.getMessage());
    }
  }