Exemplo n.º 1
0
  private void tryKeyTransWithDigest(ASN1ObjectIdentifier macAlg) throws Exception {
    byte[] data = "Eric H. Echidna".getBytes();

    CMSAuthenticatedDataGenerator adGen = new CMSAuthenticatedDataGenerator();
    DigestCalculatorProvider calcProvider =
        new JcaDigestCalculatorProviderBuilder().setProvider(BC).build();

    adGen.addRecipientInfoGenerator(
        new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC));

    CMSAuthenticatedData ad =
        adGen.generate(
            new CMSProcessableByteArray(data),
            new JceCMSMacCalculatorBuilder(macAlg).setProvider(BC).build(),
            calcProvider.get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)));

    RecipientInformationStore recipients = ad.getRecipientInfos();

    assertEquals(ad.getMacAlgOID(), macAlg.getId());

    Collection c = recipients.getRecipients();

    assertEquals(1, c.size());

    Iterator it = c.iterator();

    while (it.hasNext()) {
      RecipientInformation recipient = (RecipientInformation) it.next();

      assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId());

      byte[] recData =
          recipient.getContent(
              new JceKeyTransAuthenticatedRecipient(_reciKP.getPrivate()).setProvider(BC));

      assertTrue(Arrays.equals(data, recData));
      assertTrue(Arrays.equals(ad.getMac(), recipient.getMac()));
      assertTrue(Arrays.equals(ad.getContentDigest(), recipient.getContentDigest()));
    }
  }
Exemplo n.º 2
0
  private void tryKekAlgorithmWithDigest(SecretKey kek, ASN1ObjectIdentifier algOid)
      throws NoSuchAlgorithmException, NoSuchProviderException, CMSException,
          OperatorCreationException {
    byte[] data = "Eric H. Echidna".getBytes();

    CMSAuthenticatedDataGenerator adGen = new CMSAuthenticatedDataGenerator();
    DigestCalculatorProvider calcProvider =
        new JcaDigestCalculatorProviderBuilder().setProvider(BC).build();

    byte[] kekId = new byte[] {1, 2, 3, 4, 5};

    adGen.addRecipientInfoGenerator(new JceKEKRecipientInfoGenerator(kekId, kek).setProvider(BC));

    CMSAuthenticatedData ad =
        adGen.generate(
            new CMSProcessableByteArray(data),
            new JceCMSMacCalculatorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build(),
            calcProvider.get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)));

    RecipientInformationStore recipients = ad.getRecipientInfos();

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    assertEquals(ad.getMacAlgOID(), CMSAuthenticatedDataGenerator.DES_EDE3_CBC);

    if (it.hasNext()) {
      RecipientInformation recipient = (RecipientInformation) it.next();

      assertEquals(recipient.getKeyEncryptionAlgOID(), algOid.getId());

      byte[] recData = recipient.getContent(new JceKEKAuthenticatedRecipient(kek).setProvider(BC));

      assertTrue(Arrays.equals(data, recData));
      assertTrue(Arrays.equals(ad.getMac(), recipient.getMac()));
      assertTrue(Arrays.equals(ad.getContentDigest(), recipient.getContentDigest()));
    } else {
      fail("no recipient found");
    }
  }
Exemplo n.º 3
0
  public boolean verify(DigestCalculatorProvider calculatorProvider) throws CMSException {
    try {
      ContentInfo content = digestedData.getEncapContentInfo();
      DigestCalculator calc = calculatorProvider.get(digestedData.getDigestAlgorithm());

      OutputStream dOut = calc.getOutputStream();

      dOut.write(((ASN1OctetString) content.getContent()).getOctets());

      return Arrays.areEqual(digestedData.getDigest(), calc.getDigest());
    } catch (OperatorCreationException e) {
      throw new CMSException("unable to create digest calculator: " + e.getMessage(), e);
    } catch (IOException e) {
      throw new CMSException("unable process content: " + e.getMessage(), e);
    }
  }
Exemplo n.º 4
0
  public boolean isVerified(
      X509CertificateHolder certHolder, DigestCalculatorProvider digesterProvider)
      throws CMPException {
    AlgorithmIdentifier digAlg =
        digestAlgFinder.find(certHolder.toASN1Structure().getSignatureAlgorithm());
    if (digAlg == null) {
      throw new CMPException("cannot find algorithm for digest from signature");
    }

    DigestCalculator digester;

    try {
      digester = digesterProvider.get(digAlg);
    } catch (OperatorCreationException e) {
      throw new CMPException("unable to create digester: " + e.getMessage(), e);
    }

    CMPUtil.derEncodeToStream(certHolder.toASN1Structure(), digester.getOutputStream());

    return Arrays.areEqual(certStatus.getCertHash().getOctets(), digester.getDigest());
  }
Exemplo n.º 5
0
  public void testCMSAlgorithmProtection() throws Exception {
    byte[] data = "Eric H. Echidna".getBytes();

    CMSAuthenticatedDataGenerator adGen = new CMSAuthenticatedDataGenerator();
    DigestCalculatorProvider calcProvider =
        new JcaDigestCalculatorProviderBuilder().setProvider(BC).build();

    byte[] kekId = new byte[] {1, 2, 3, 4, 5};
    SecretKey kek = CMSTestUtil.makeDesede192Key();

    adGen.addRecipientInfoGenerator(new JceKEKRecipientInfoGenerator(kekId, kek).setProvider(BC));

    CMSAuthenticatedData ad =
        adGen.generate(
            new CMSProcessableByteArray(data),
            new JceCMSMacCalculatorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build(),
            calcProvider.get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)));

    checkData(data, kek, ad);

    ContentInfo adInfo = ad.toASN1Structure();
    AuthenticatedData iAd =
        AuthenticatedData.getInstance(adInfo.getContent().toASN1Primitive().getEncoded());

    try {
      new CMSAuthenticatedData(
          new ContentInfo(
              CMSObjectIdentifiers.authenticatedData,
              new AuthenticatedData(
                  iAd.getOriginatorInfo(),
                  iAd.getRecipientInfos(),
                  iAd.getMacAlgorithm(),
                  new AlgorithmIdentifier(TeleTrusTObjectIdentifiers.ripemd160, DERNull.INSTANCE),
                  iAd.getEncapsulatedContentInfo(),
                  iAd.getAuthAttrs(),
                  iAd.getMac(),
                  iAd.getUnauthAttrs())),
          calcProvider);
    } catch (CMSException e) {
      Assert.assertEquals(
          e.getMessage(), "CMS Algorithm Identifier Protection check failed for digestAlgorithm");
    }

    AlgorithmIdentifier newDigAlgId =
        new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE);
    Assert.assertFalse(iAd.getDigestAlgorithm().equals(newDigAlgId));
    checkData(
        data,
        kek,
        new CMSAuthenticatedData(
            new ContentInfo(
                CMSObjectIdentifiers.authenticatedData,
                new AuthenticatedData(
                    iAd.getOriginatorInfo(),
                    iAd.getRecipientInfos(),
                    iAd.getMacAlgorithm(),
                    newDigAlgId,
                    iAd.getEncapsulatedContentInfo(),
                    iAd.getAuthAttrs(),
                    iAd.getMac(),
                    iAd.getUnauthAttrs())),
            calcProvider));

    try {
      new CMSAuthenticatedData(
          new ContentInfo(
              CMSObjectIdentifiers.authenticatedData,
              new AuthenticatedData(
                  iAd.getOriginatorInfo(),
                  iAd.getRecipientInfos(),
                  new AlgorithmIdentifier(CMSAlgorithm.AES192_CBC),
                  iAd.getDigestAlgorithm(),
                  iAd.getEncapsulatedContentInfo(),
                  iAd.getAuthAttrs(),
                  iAd.getMac(),
                  iAd.getUnauthAttrs())),
          calcProvider);
    } catch (CMSException e) {
      Assert.assertEquals(
          e.getMessage(), "CMS Algorithm Identifier Protection check failed for macAlgorithm");
    }

    try {
      AlgorithmIdentifier newMacAlgId = new AlgorithmIdentifier(CMSAlgorithm.DES_EDE3_CBC);
      Assert.assertFalse(iAd.getMacAlgorithm().equals(newMacAlgId));
      new CMSAuthenticatedData(
          new ContentInfo(
              CMSObjectIdentifiers.authenticatedData,
              new AuthenticatedData(
                  iAd.getOriginatorInfo(),
                  iAd.getRecipientInfos(),
                  newMacAlgId,
                  iAd.getDigestAlgorithm(),
                  iAd.getEncapsulatedContentInfo(),
                  iAd.getAuthAttrs(),
                  iAd.getMac(),
                  iAd.getUnauthAttrs())),
          calcProvider);
    } catch (CMSException e) {
      Assert.assertEquals(
          e.getMessage(), "CMS Algorithm Identifier Protection check failed for macAlgorithm");
    }
  }
Exemplo n.º 6
0
  public void performTest() throws Exception {
    String signDN = "O=Bouncy Castle, C=AU";
    KeyPair signKP = OCSPTestUtil.makeKeyPair();
    X509CertificateHolder testCert =
        new JcaX509CertificateHolder(OCSPTestUtil.makeCertificate(signKP, signDN, signKP, signDN));

    String origDN = "CN=Eric H. Echidna, [email protected], O=Bouncy Castle, C=AU";
    GeneralName origName = new GeneralName(new X509Name(origDN));
    DigestCalculatorProvider digCalcProv =
        new JcaDigestCalculatorProviderBuilder().setProvider(BC).build();

    //
    // general id value for our test issuer cert and a serial number.
    //
    CertificateID id =
        new CertificateID(
            digCalcProv.get(CertificateID.HASH_SHA1), testCert, BigInteger.valueOf(1));

    //
    // basic request generation
    //
    OCSPReqBuilder gen = new OCSPReqBuilder();

    gen.addRequest(
        new CertificateID(
            digCalcProv.get(CertificateID.HASH_SHA1), testCert, BigInteger.valueOf(1)));

    OCSPReq req = gen.build();

    if (req.isSigned()) {
      fail("signed but shouldn't be");
    }

    X509CertificateHolder[] certs = req.getCerts();

    if (certs.length != 0) {
      fail("0 certs expected, but not found");
    }

    Req[] requests = req.getRequestList();

    if (!requests[0].getCertID().equals(id)) {
      fail("Failed isFor test");
    }

    //
    // request generation with signing
    //
    X509CertificateHolder[] chain = new X509CertificateHolder[1];

    gen = new OCSPReqBuilder();

    gen.setRequestorName(new GeneralName(GeneralName.directoryName, new X509Principal("CN=fred")));

    gen.addRequest(
        new CertificateID(
            digCalcProv.get(CertificateID.HASH_SHA1), testCert, BigInteger.valueOf(1)));

    chain[0] = testCert;

    req =
        gen.build(
            new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(signKP.getPrivate()),
            chain);

    if (!req.isSigned()) {
      fail("not signed but should be");
    }

    if (!req.isSignatureValid(
        new JcaContentVerifierProviderBuilder().setProvider(BC).build(signKP.getPublic()))) {
      fail("signature failed to verify");
    }

    requests = req.getRequestList();

    if (!requests[0].getCertID().equals(id)) {
      fail("Failed isFor test");
    }

    certs = req.getCerts();

    if (certs == null) {
      fail("null certs found");
    }

    if (certs.length != 1 || !certs[0].equals(testCert)) {
      fail("incorrect certs found in request");
    }

    //
    // encoding test
    //
    byte[] reqEnc = req.getEncoded();

    OCSPReq newReq = new OCSPReq(reqEnc);

    if (!newReq.isSignatureValid(
        new JcaContentVerifierProviderBuilder().setProvider(BC).build(signKP.getPublic()))) {
      fail("newReq signature failed to verify");
    }

    //
    // request generation with signing and nonce
    //
    chain = new X509CertificateHolder[1];

    gen = new OCSPReqBuilder();

    Vector oids = new Vector();
    Vector values = new Vector();
    byte[] sampleNonce = new byte[16];
    Random rand = new Random();

    rand.nextBytes(sampleNonce);

    gen.setRequestorName(new GeneralName(GeneralName.directoryName, new X509Principal("CN=fred")));

    oids.addElement(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
    values.addElement(
        new X509Extension(false, new DEROctetString(new DEROctetString(sampleNonce))));

    gen.setRequestExtensions(new X509Extensions(oids, values));

    gen.addRequest(
        new CertificateID(
            digCalcProv.get(CertificateID.HASH_SHA1), testCert, BigInteger.valueOf(1)));

    chain[0] = testCert;

    req =
        gen.build(
            new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(signKP.getPrivate()),
            chain);

    if (!req.isSigned()) {
      fail("not signed but should be");
    }

    if (!req.isSignatureValid(
        new JcaContentVerifierProviderBuilder().setProvider(BC).build(signKP.getPublic()))) {
      fail("signature failed to verify");
    }

    //
    // extension check.
    //
    Set extOids = req.getCriticalExtensionOIDs();

    if (extOids.size() != 0) {
      fail("wrong number of critical extensions in OCSP request.");
    }

    extOids = req.getNonCriticalExtensionOIDs();

    if (extOids.size() != 1) {
      fail("wrong number of non-critical extensions in OCSP request.");
    }

    X509Extension ext = req.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);

    ASN1Encodable extObj = ext.getParsedValue();

    if (!(extObj instanceof ASN1OctetString)) {
      fail("wrong extension type found.");
    }

    if (!areEqual(((ASN1OctetString) extObj).getOctets(), sampleNonce)) {
      fail("wrong extension value found.");
    }

    //
    // request list check
    //
    requests = req.getRequestList();

    if (!requests[0].getCertID().equals(id)) {
      fail("Failed isFor test");
    }

    //
    // response parsing - test 1
    //
    OCSPResp response = new OCSPResp(testResp1);

    if (response.getStatus() != 0) {
      fail("response status not zero.");
    }

    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    chain = brep.getCerts();

    if (!brep.isSignatureValid(
        new JcaContentVerifierProviderBuilder().setProvider(BC).build(chain[0]))) {
      fail("response 1 failed to verify.");
    }

    //
    // test 2
    //
    SingleResp[] singleResp = brep.getResponses();

    response = new OCSPResp(testResp2);

    if (response.getStatus() != 0) {
      fail("response status not zero.");
    }

    brep = (BasicOCSPResp) response.getResponseObject();
    chain = brep.getCerts();

    if (!brep.isSignatureValid(
        new JcaContentVerifierProviderBuilder().setProvider(BC).build(chain[0]))) {
      fail("response 2 failed to verify.");
    }

    singleResp = brep.getResponses();

    //
    // simple response generation
    //
    OCSPRespBuilder respGen = new OCSPRespBuilder();
    OCSPResp resp = respGen.build(OCSPRespBuilder.SUCCESSFUL, response.getResponseObject());

    if (!resp.getResponseObject().equals(response.getResponseObject())) {
      fail("response fails to match");
    }

    testECDSA();
    testRSA();
    testIrregularVersionReq();
  }
 public DigestCalculator getDigestCalculator(AlgorithmIdentifier algorithmIdentifier)
     throws OperatorCreationException {
   return digestProvider.get(algorithmIdentifier);
 }
Exemplo n.º 8
0
 /**
  * Creates a new digest calculator with the specified algorithm identifier.
  *
  * @param algorithm the algorithm identifier
  * @return a new digest calculator instance
  * @throws OperatorCreationException if the calculator cannot be created
  */
 public static DigestCalculator createDigestCalculator(AlgorithmIdentifier algorithm)
     throws OperatorCreationException {
   return DIGEST_PROVIDER.get(algorithm);
 }