private ECCCMSSharedInfo(ASN1Sequence seq) {
    this.keyInfo = AlgorithmIdentifier.getInstance(seq.getObjectAt(0));

    if (seq.size() == 2) {
      this.entityUInfo = null;
      this.suppPubInfo =
          ASN1OctetString.getInstance((ASN1TaggedObject) seq.getObjectAt(1), true).getOctets();
    } else {
      this.entityUInfo =
          ASN1OctetString.getInstance((ASN1TaggedObject) seq.getObjectAt(1), true).getOctets();
      this.suppPubInfo =
          ASN1OctetString.getInstance((ASN1TaggedObject) seq.getObjectAt(2), true).getOctets();
    }
  }
 public EncryptedContentInfo(ASN1Sequence seq) {
   contentType = (DERObjectIdentifier) seq.getObjectAt(0);
   contentEncryptionAlgorithm = AlgorithmIdentifier.getInstance(seq.getObjectAt(1));
   if (seq.size() > 2) {
     encryptedContent = ASN1OctetString.getInstance((ASN1TaggedObject) seq.getObjectAt(2), false);
   }
 }
  /**
   * decrypt the content and return an input stream.
   *
   * @deprecated use getContentStream(Recipient)
   */
  public CMSTypedStream getContentStream(Key key, Provider prov) throws CMSException {
    try {
      CMSEnvelopedHelper helper = CMSEnvelopedHelper.INSTANCE;
      AlgorithmIdentifier kekAlg =
          AlgorithmIdentifier.getInstance(info.getKeyEncryptionAlgorithm());
      ASN1Sequence kekAlgParams = (ASN1Sequence) kekAlg.getParameters();
      String kekAlgName = DERObjectIdentifier.getInstance(kekAlgParams.getObjectAt(0)).getId();
      String wrapAlgName = helper.getRFC3211WrapperName(kekAlgName);

      Cipher keyCipher = helper.createSymmetricCipher(wrapAlgName, prov);
      IvParameterSpec ivSpec =
          new IvParameterSpec(ASN1OctetString.getInstance(kekAlgParams.getObjectAt(1)).getOctets());
      keyCipher.init(
          Cipher.UNWRAP_MODE,
          new SecretKeySpec(((CMSPBEKey) key).getEncoded(kekAlgName), kekAlgName),
          ivSpec);

      Key sKey =
          keyCipher.unwrap(
              info.getEncryptedKey().getOctets(), getContentAlgorithmName(), Cipher.SECRET_KEY);

      return getContentFromSessionKey(sKey, prov);
    } catch (NoSuchAlgorithmException e) {
      throw new CMSException("can't find algorithm.", e);
    } catch (InvalidKeyException e) {
      throw new CMSException("key invalid in message.", e);
    } catch (NoSuchPaddingException e) {
      throw new CMSException("required padding not supported.", e);
    } catch (InvalidAlgorithmParameterException e) {
      throw new CMSException("invalid iv.", e);
    }
  }
  SignerInformation(
      SignerInfo info,
      ASN1ObjectIdentifier contentType,
      CMSProcessable content,
      IntDigestCalculator digestCalculator,
      SignatureAlgorithmIdentifierFinder sigAlgFinder) {
    this.info = info;
    this.contentType = contentType;
    this.sigAlgFinder = sigAlgFinder;
    this.isCounterSignature = contentType == null;

    SignerIdentifier s = info.getSID();

    if (s.isTagged()) {
      ASN1OctetString octs = ASN1OctetString.getInstance(s.getId());

      sid = new SignerId(octs.getOctets());
    } else {
      IssuerAndSerialNumber iAnds = IssuerAndSerialNumber.getInstance(s.getId());

      sid = new SignerId(iAnds.getName(), iAnds.getSerialNumber().getValue());
    }

    this.digestAlgorithm = info.getDigestAlgorithm();
    this.signedAttributeSet = info.getAuthenticatedAttributes();
    this.unsignedAttributeSet = info.getUnauthenticatedAttributes();
    this.encryptionAlgorithm = info.getDigestEncryptionAlgorithm();
    this.signature = info.getEncryptedDigest().getOctets();

    this.content = content;
    this.digestCalculator = digestCalculator;
  }
Example #5
0
  private PKIHeader(ASN1Sequence seq) {
    Enumeration en = seq.getObjects();

    pvno = DERInteger.getInstance(en.nextElement());
    sender = GeneralName.getInstance(en.nextElement());
    recipient = GeneralName.getInstance(en.nextElement());

    while (en.hasMoreElements()) {
      ASN1TaggedObject tObj = (ASN1TaggedObject) en.nextElement();

      switch (tObj.getTagNo()) {
        case 0:
          messageTime = DERGeneralizedTime.getInstance(tObj, true);
          break;
        case 1:
          protectionAlg = AlgorithmIdentifier.getInstance(tObj, true);
          break;
        case 2:
          senderKID = ASN1OctetString.getInstance(tObj, true);
          break;
        case 3:
          recipKID = ASN1OctetString.getInstance(tObj, true);
          break;
        case 4:
          transactionID = ASN1OctetString.getInstance(tObj, true);
          break;
        case 5:
          senderNonce = ASN1OctetString.getInstance(tObj, true);
          break;
        case 6:
          recipNonce = ASN1OctetString.getInstance(tObj, true);
          break;
        case 7:
          freeText = PKIFreeText.getInstance(tObj, true);
          break;
        case 8:
          generalInfo = ASN1Sequence.getInstance(tObj, true);
          break;
        default:
          throw new IllegalArgumentException("unknown tag number: " + tObj.getTagNo());
      }
    }
  }
  public void multipartMixedTest(MimeBodyPart part1, MimeBodyPart part2) throws Exception {
    MimeMultipart mp = new MimeMultipart();

    mp.addBodyPart(part1);
    mp.addBodyPart(part2);

    MimeBodyPart m = new MimeBodyPart();

    m.setContent(mp);

    MimeMultipart smm =
        generateMultiPartRsa("SHA1withRSA", m, SMIMESignedGenerator.RFC3851_MICALGS);
    SMIMESigned s = new SMIMESigned(smm);

    verifySigners(s.getCertificates(), s.getSignerInfos());

    AttributeTable attr =
        ((SignerInformation) s.getSignerInfos().getSigners().iterator().next())
            .getSignedAttributes();

    Attribute a = attr.get(CMSAttributes.messageDigest);
    byte[] contentDigest =
        ASN1OctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets();

    mp = (MimeMultipart) m.getContent();
    ContentType contentType = new ContentType(mp.getContentType());
    String boundary = "--" + contentType.getParameter("boundary");

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    LineOutputStream lOut = new LineOutputStream(bOut);

    Enumeration headers = m.getAllHeaderLines();
    while (headers.hasMoreElements()) {
      lOut.writeln((String) headers.nextElement());
    }

    lOut.writeln(); // CRLF separator

    lOut.writeln(boundary);
    writePart(mp.getBodyPart(0), bOut);
    lOut.writeln(); // CRLF terminator

    lOut.writeln(boundary);
    writePart(mp.getBodyPart(1), bOut);
    lOut.writeln();

    lOut.writeln(boundary + "--");

    MessageDigest dig = MessageDigest.getInstance("SHA1", BC);

    assertTrue(Arrays.equals(contentDigest, dig.digest(bOut.toByteArray())));
  }
 private byte[] getSubjectKeyId(X509Certificate cert) throws IOException {
   byte[] extvalue = cert.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
   if (extvalue == null) {
     return null;
   }
   ASN1OctetString str =
       ASN1OctetString.getInstance(
           new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject());
   SubjectKeyIdentifier keyId =
       SubjectKeyIdentifier.getInstance(
           new ASN1InputStream(new ByteArrayInputStream(str.getOctets())).readObject());
   return keyId.getKeyIdentifier();
 }
Example #8
0
 public KeyTransRecipientId getKeyTransRecipientId(X509CertSelector certSelector) {
   try {
     if (certSelector.getSubjectKeyIdentifier() != null) {
       return new KeyTransRecipientId(
           X500Name.getInstance(certSelector.getIssuerAsBytes()),
           certSelector.getSerialNumber(),
           ASN1OctetString.getInstance(certSelector.getSubjectKeyIdentifier()).getOctets());
     } else {
       return new KeyTransRecipientId(
           X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber());
     }
   } catch (Exception e) {
     throw new IllegalArgumentException("conversion failed: " + e.toString());
   }
 }
Example #9
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());
    }
  }
Example #10
0
 private PBMParameter(ASN1Sequence seq) {
   salt = ASN1OctetString.getInstance(seq.getObjectAt(0));
   owf = AlgorithmIdentifier.getInstance(seq.getObjectAt(1));
   iterationCount = DERInteger.getInstance(seq.getObjectAt(2));
   mac = AlgorithmIdentifier.getInstance(seq.getObjectAt(3));
 }