Example usage for org.bouncycastle.util Arrays areEqual

List of usage examples for org.bouncycastle.util Arrays areEqual

Introduction

In this page you can find the example usage for org.bouncycastle.util Arrays areEqual.

Prototype

public static boolean areEqual(short[] a, short[] b) 

Source Link

Usage

From source file:org.ccnx.ccn.io.content.KeyDirectory.java

License:Open Source License

/**
 * Unwrap and return the key wrapped in a wrapping key specified by its digest.
 * Find a copy of the key block in this directory that we can unwrap (either the private
 * key wrapping key block or a wrapped raw symmetric key). Chase superseding keys if
 * we have to. This mechanism should be generic, and should work for node keys
 * as well as private key wrapping keys in directories following this structure.
 * @return/*from w w  w.j  a v  a  2 s  .  c om*/
 * @throws InvalidKeyException
 * @throws ContentDecodingException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public Key getUnwrappedKey(byte[] expectedKeyID)
        throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {

    byte[] retrievedKeyID;
    if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINEST)) {
        Log.finest(Log.FAC_ACCESSCONTROL, "getUnwrappedKey({0})", DataUtils.printHexBytes(expectedKeyID));
    }
    Key unwrappedKey = findUnwrappedKey(expectedKeyID);

    if (null != unwrappedKey) {
        _handle.keyManager().getSecureKeyCache().addKey(getName(), unwrappedKey);

        if (null != expectedKeyID) {
            retrievedKeyID = NodeKey.generateKeyID(unwrappedKey);
            if (!Arrays.areEqual(expectedKeyID, retrievedKeyID)) {
                if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
                    Log.warning(Log.FAC_ACCESSCONTROL,
                            "Retrieved and decrypted wrapped key, but it was the wrong key. We wanted "
                                    + DataUtils.printBytes(expectedKeyID) + ", we got "
                                    + DataUtils.printBytes(retrievedKeyID));
                }
            }
        }
    }
    return unwrappedKey;
}

From source file:org.ccnx.ccn.io.content.SerializableObjectTest.java

License:Open Source License

@Test
public void testSave() {
    Log.info(Log.FAC_TEST, "Starting testSave");

    SerializablePublicKey spk1 = new SerializablePublicKey(kp1.getPublic());
    SerializablePublicKey spk2 = new SerializablePublicKey(kp1.getPublic());
    SerializablePublicKey spk3 = new SerializablePublicKey(kp2.getPublic());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
    ByteArrayOutputStream baos3 = new ByteArrayOutputStream();

    try {/*from ww w  .j av  a  2s . co  m*/
        spk1.save(baos);
        spk2.save(baos2); // will this save? currently not, should it?
        Assert.assertArrayEquals("Serializing two versions of same content should produce same output",
                baos.toByteArray(), baos2.toByteArray());
        spk3.save(baos3);
        boolean be = Arrays.areEqual(baos.toByteArray(), baos3.toByteArray());
        Assert.assertFalse("Two different objects shouldn't have matching output.", be);
        System.out.println("Saved two public keys, lengths " + baos.toByteArray().length + " and "
                + baos3.toByteArray().length);
    } catch (IOException e) {
        fail("IOException! " + e.getMessage());
    }

    Log.info(Log.FAC_TEST, "Completed testSave");
}

From source file:org.ccnx.ccn.io.content.SerializableObjectTest.java

License:Open Source License

@Test
public void testUpdate() {
    Log.info(Log.FAC_TEST, "Starting testUpdate");

    boolean caught = false;
    SerializablePublicKey empty = new SerializablePublicKey();
    try {/*  www  . j  av a 2s  . co  m*/
        empty.publicKey();
    } catch (ContentNotReadyException iox) {
        // this is what we expect to happen
        caught = true;
    } catch (IOException ie) {
        Assert.fail("Unexpectd IOException!");
    }
    Assert.assertTrue("Failed to produce expected exception.", caught);

    SerializablePublicKey spk1 = new SerializablePublicKey(kp1.getPublic());
    SerializablePublicKey spk2 = new SerializablePublicKey();
    SerializablePublicKey spk3 = new SerializablePublicKey(kp2.getPublic());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ByteArrayOutputStream baos3 = new ByteArrayOutputStream();

    try {
        spk1.save(baos);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        spk2.update(bais); // will this save? currently not, should it?
        Assert.assertEquals("Writing content out and back in again should give matching object.", spk1, spk2);
        spk3.save(baos3);
        boolean be = Arrays.areEqual(baos.toByteArray(), baos3.toByteArray());
        Assert.assertFalse("Two different objects shouldn't have matching output.", be);
        System.out.println("Saved two public keys, lengths " + baos.toByteArray().length + " and "
                + baos3.toByteArray().length);
    } catch (IOException e) {
        fail("IOException! " + e.getMessage());
    }

    Log.info(Log.FAC_TEST, "Completed testUpdate");
}

From source file:org.ccnx.ccn.profiles.nameenum.EnumeratedNameList.java

License:Open Source License

/**
 * Returns true if we know the prefix has a child matching the given name component.
 *
 * @param childComponent name component to check for in the stored child names.
 * @return true if that child is in our list of known children
 *//*ww w. j  a v  a2s .co m*/
public boolean hasChild(byte[] childComponent) {
    for (ContentName child : _children) {
        if (Arrays.areEqual(childComponent, child.component(0))) {
            return true;
        }
    }
    return false;
}

From source file:org.ccnx.ccn.profiles.nameenum.EnumeratedNameListTestRepo.java

License:Open Source License

@Test
public void testEnumeratedName() throws Exception {
    Log.info(Log.FAC_TEST, "Starting testEnumeratedName");

    try {/*from w  w  w . j  a  v  a  2s .  c o m*/
        CCNHandle handle = CCNHandle.open();

        Assert.assertNotNull(directory);
        Assert.assertNotNull(name1);
        Assert.assertNotNull(name2);
        Assert.assertNotNull(name3);
        Assert.assertNotNull(brokenPrefix);

        Log.info(Log.FAC_TEST, "*****************Creating Enumerated Name List Object");
        //creates Enumerated Name List
        testList = new EnumeratedNameList(directory, putHandle);

        Log.info(Log.FAC_TEST, "*****************assert creation of handle and enumeratednamelist object");
        //verify that the class and handle is setup
        Assert.assertNotNull(putHandle);
        Assert.assertNotNull(testList);

        Log.info(Log.FAC_TEST, "*****************assert creation of prefix");
        //Verify that the object has been created with the right prefix
        ContentName prefixTest = testList.getName();
        Assert.assertNotNull(prefixTest);
        Log.info(Log.FAC_TEST, "***************** Prefix is " + prefixTest.toString());
        Assert.assertEquals(prefixTest, directory);
        Assert.assertFalse(brokenPrefix.equals(prefixTest));

        //run it on a name that isn't there and make sure it is empty
        // DKS -- this won't work -- it will wait forever. The point is not to enumerate,
        // the point is to wait for an answer that says something, potentially forever. No repo
        // currently NACKs -- answers "nothing there", so this will simply wait until something
        // appears.
        //testList.waitForData();

        Log.info(Log.FAC_TEST, "****************** adding name1 to repo");

        // adding content to repo
        ContentName latestName = addContentToRepo(name1, handle);
        testList.waitForChildren();
        Log.info(Log.FAC_TEST, "Added data to repo: " + latestName);

        //testing that the enumerator has new data
        Assert.assertTrue(testList.hasNewData());

        //Testing that hasNewData returns true
        Assert.assertTrue(testList.hasNewData());

        //gets new data
        SortedSet<ContentName> returnedBytes = testList.getNewData();

        Assert.assertNotNull(returnedBytes);
        Assert.assertFalse(returnedBytes.isEmpty());

        // getNewData gets *new* data -- you got the last new data, there won't be any more
        // until you add something else to the repo. i.e. this next call would block
        // until there was new data for getNewData to return, and it *wouldn't* match the previous set.
        // Assert.assertEquals(testList.getNewData(), returnedBytes.size());
        System.out.println("Got " + returnedBytes.size() + " children: " + returnedBytes);
        //only one thing has been added, so we can only expect one name
        //System.out.println("Predicted strings " + name1String + ", " + name2String + ", " + name3String);
        System.out.println("Predicted strings " + name1String);
        // DKS -- previous version of this was failing:
        // Assert.assertEquals(name1String.getBytes(UTF8), returnedBytes.get(0)));
        // this will fail, because byte [] does not define equals (it's a native type, not an object), so
        // you get Object.equals -- which tests if the two pointers are the same.
        // If we run this more than once on the same repo, will get all the data back -- so won't know which child
        // is first. Don't try to test on the content.
        //Assert.assertTrue(Arrays.areEqual(name1String.getBytes(UTF8), returnedBytes.first().component(0)));

        System.out.print("names in list:");
        for (ContentName n : returnedBytes)
            System.out.print(" " + n);
        System.out.println();

        //testing that children exist
        // DKS -- if you're testing a boolean, use assertTrue, not assertNotNull
        Assert.assertTrue(testList.hasChildren());

        //Testing that Name1 Exists
        // only true if run on clean repo -- if not clean repo and clean ccnd cache, might be in second response
        Assert.assertTrue(testList.hasChild(name1String));

        // Only definite if run on fresh repo
        //as long as the EnumeratedNameList object isn't starting a new interest, this is correct.  a repo
        //  wouldn't return old names after the last response
        Assert.assertFalse(testList.hasNewData());
        // Now add some more data

        System.out.println("adding name2: " + name2);
        addContentToRepo(name2, handle);
        System.out.println("adding name3: " + name3);
        addContentToRepo(name3, handle);

        //both of these actions could generate a new response since there is an outstanding interest on the data.
        //this means the response can come a few different ways
        //1 - an interest.last request gets there and sets the interest flag.  then a save will generate a response
        //2 - an interest.last request gets there after the save, generating a new response
        //3 - same thing happens for the second object as 1
        //4 - same thing happens for the second object as 2
        //5 - after both things are added an interest.last arrives from the CCNNameEnumerator.

        SortedSet<ContentName> returnedBytes2 = testList.getNewData(); // will block for new data
        Assert.assertNotNull(returnedBytes2);

        System.out.print("names in list after adding name2 and name3:");
        for (ContentName n : returnedBytes2)
            System.out.print(" " + n);
        System.out.println();

        System.out.print("names in testlist after adding name2 and name3:");
        for (ContentName n : testList.getChildren())
            System.out.print(" " + n);
        System.out.println();

        // Might have older stuff from previous runs, so don't insist we get back only what we put in.
        System.out.println("Got new data, second round size: " + returnedBytes2.size() + " first round "
                + returnedBytes.size());
        //this is new data...  so comparing new data from one save to another doesn't really make sense
        Assert.assertTrue(returnedBytes2.size() >= 1);
        //since we have a new response, the first name has to be in there...
        Assert.assertTrue(testList.hasChild(name2String));
        //we might not have a response since the second name...  need to check again if it isn't in there yet 
        if (!testList.hasChild(name3String)) {
            returnedBytes2 = testList.getNewData(); // will block for new data
            //now we have the third response...

            System.out.print("names in list after asking for new data again:");
            for (ContentName n : returnedBytes2)
                System.out.print(" " + n);
            System.out.println();
        }

        System.out.print("names in testlist after adding name2 and name3:");
        for (ContentName n : testList.getChildren())
            System.out.print(" " + n);
        System.out.println();

        Assert.assertTrue(testList.hasChild(name3String));

        // This will add new versions
        for (int i = 0; i < 5; ++i) {
            latestName = addContentToRepo(name1, handle);
            Log.info(Log.FAC_TEST, "Added data to repo: " + latestName);
        }

        EnumeratedNameList versionList = new EnumeratedNameList(name1, handle);
        versionList.waitForChildren();
        Assert.assertTrue(versionList.hasNewData());
        // Even though the addition of versions above is blocking and the new EnumeratedNameList
        // is not created to start enumerating names until after the versions have been written,
        // we don't have a guarantee that the repository will have fully processed the writes 
        // before it answers the name enumeration request.  (At some point when full repository 
        // commitment is obtained before returning from write this may change).  There is a timing 
        // race with the last content written and the first name enumeration result.  For this reason
        // we must be prepared to wait a second time.
        // It could be possible that only waiting one more time is not sufficient...  if the writes are very slow,
        // the timing could work out that there is a response per object.  adding loop to account for that

        for (int attempts = 1; attempts < 5; attempts++) {
            // 5 versions written just above plus 1 earlier addition under name1
            versionList.getNewData(); // ignore result, we want to look at entire set once available
            if (versionList.getChildren().size() >= 6)
                attempts = 5;
        }
        // Now we should have everything
        ContentName latestReturnName = versionList.getLatestVersionChildName();
        System.out.println("Got children: " + versionList.getChildren());
        System.out.println("Got latest name " + latestReturnName + " expected "
                + new ContentName(latestName.lastComponent()));
        Assert.assertTrue(Arrays.areEqual(latestName.lastComponent(), latestReturnName.lastComponent()));

    } catch (Exception e) {
        Log.logException(Log.FAC_TEST, Level.WARNING, "Failed test with exception " + e.getMessage(), e);
        Assert.fail("Failed test with exception " + e.getMessage());
    }

    Log.info(Log.FAC_TEST, "Completed testEnumeratedName");
}

From source file:org.ccnx.ccn.profiles.VersioningProfileTest.java

License:Open Source License

@Test
public void testUnpaddedVersions() throws Exception {
    Log.info(Log.FAC_TEST, "Starting testUnpaddedVersions");

    ContentName name = ContentName.fromNative("/testme");
    long v0 = 0x7FFFFF;
    byte[] b0 = { VersioningProfile.VERSION_MARKER, (byte) 0x7F, (byte) 0xFF, (byte) 0xFF };

    ContentName vn0 = VersioningProfile.addVersion(name, v0);
    byte[] x0 = VersioningProfile.getLastVersionComponent(vn0);
    System.out.println("From long name   : " + vn0.toString());
    Assert.assertTrue(Arrays.areEqual(b0, x0));

    // now do it as ccntime
    CCNTime t0 = CCNTime.fromBinaryTimeAsLong(v0);
    vn0 = new ContentName(name, t0);
    x0 = VersioningProfile.getLastVersionComponent(vn0);
    System.out.println("From ccntime name: " + vn0.toString());
    Assert.assertTrue(Arrays.areEqual(b0, x0));

    Log.info(Log.FAC_TEST, "Completed testUnpaddedVersions");
}

From source file:org.ccnx.ccn.profiles.VersioningProfileTest.java

License:Open Source License

@Test
public void testPaddedVersions() throws Exception {
    Log.info(Log.FAC_TEST, "Starting testPaddedVersions");

    ContentName name = ContentName.fromNative("/testme");
    long v0 = 0x80FFFF;
    byte[] b0 = { VersioningProfile.VERSION_MARKER, (byte) 0x80, (byte) 0xFF, (byte) 0xFF };

    ContentName vn0 = VersioningProfile.addVersion(name, v0);
    byte[] x0 = VersioningProfile.getLastVersionComponent(vn0);
    System.out.println("From long name   : " + vn0.toString());
    Assert.assertTrue(Arrays.areEqual(b0, x0));

    // now do it as ccntime
    CCNTime t0 = CCNTime.fromBinaryTimeAsLong(v0);
    vn0 = new ContentName(name, t0);
    x0 = VersioningProfile.getLastVersionComponent(vn0);
    System.out.println("From ccntime name: " + vn0.toString());
    Assert.assertTrue(Arrays.areEqual(b0, x0));

    Log.info(Log.FAC_TEST, "Completed testPaddedVersions");
}

From source file:org.ccnx.ccn.protocol.Component.java

License:Open Source License

@Override
public boolean equals(Object obj) {
    if (obj instanceof byte[])
        return Arrays.areEqual((byte[]) obj, this.getComponent());
    if (obj instanceof ComponentProvider)
        return Arrays.areEqual(((ComponentProvider) obj).getComponent(), this.getComponent());
    if (obj instanceof String)
        return Arrays.areEqual(((String) obj).getBytes(), this.getComponent());
    return super.equals(obj);
}

From source file:org.cryptoworkshop.ximix.client.verify.ECDecryptionChallengeVerifier.java

License:Apache License

/**
 * Verify that the decryption challenge transcript is valid, throwing an exception if an issue is found..
 *
 * @throws TranscriptVerificationException on verification failure.
 *//* ww w.  java2s.c  om*/
public void verify() throws TranscriptVerificationException {
    ASN1InputStream aIn = new ASN1InputStream(logStream);
    ASN1InputStream resultIn = new ASN1InputStream(resultStream);
    ASN1InputStream lastIn = new ASN1InputStream(lastStageStream);

    try {
        int messageIndex = -1;
        ECPair[] encPairs = null;

        ASN1Object obj;
        while ((obj = aIn.readObject()) != null) {
            ChallengeLogMessage logMessage = ChallengeLogMessage.getInstance(obj);

            ECPoint[] sourceMessage = logMessage.getSourceMessage();
            ECDecryptionProof[] proofs = logMessage.getProofs();

            ECPublicKeyParameters currentPubKey = (ECPublicKeyParameters) PublicKeyFactory
                    .createKey(logMessage.getKeyInfo());
            if (!isSameParameters(pubKey.getParameters(), currentPubKey.getParameters())) {
                throw new TranscriptVerificationException(
                        "Log message indicates inconsistent public key parameters.");
            }

            if (messageIndex != logMessage.getIndex()) {
                if (activePeers.length != 0) {
                    LagrangeWeightCalculator weightCalculator = new LagrangeWeightCalculator(maxSequenceNo + 1,
                            pubKey.getParameters().getN());

                    ECPoint accumulatedQ = null;

                    BigInteger[] weights = weightCalculator.computeWeights(activePeers);

                    // verify the partial public keys represent the one we have.
                    for (int i = 0; i != weights.length; i++) {
                        if (weights[i] != null) {
                            if (accumulatedQ == null) {
                                accumulatedQ = activePeers[i].getQ().multiply(weights[i]);
                            } else {
                                accumulatedQ = accumulatedQ.add(activePeers[i].getQ().multiply(weights[i]));
                            }
                        }
                    }

                    if (!pubKey.getQ().equals(accumulatedQ)) {
                        throw new TranscriptVerificationException(
                                "Log message indicates inconsistent public key.");
                    }

                    // verify the partial decrypts result in the final message

                    int len = activeMsgParts[0].length;
                    for (int i = 1; i != activeMsgParts.length; i++) {
                        if (activeMsgParts[i].length != len) {
                            throw new TranscriptVerificationException("Partial decrypt length mismatch");
                        }
                    }

                    int baseIndex = 0;
                    for (int i = 0; i != activeMsgParts.length; i++) {
                        if (activeMsgParts[i] != null) {
                            baseIndex = i;
                            break;
                        }
                    }

                    BigInteger baseWeight = weights[baseIndex];

                    ECPoint[] decryptions = reassemblePoints(activeMsgParts, encPairs, weights, baseIndex,
                            baseWeight);

                    ECPoint[] recordedDecrypts = PointSequence
                            .getInstance(pubKey.getParameters().getCurve(), resultIn.readObject())
                            .getECPoints();

                    if (!Arrays.areEqual(decryptions, recordedDecrypts)) {
                        throw new TranscriptVerificationException(
                                "Recorded decrypts do not match partial ones.");
                    }

                    // reset the peers array.
                    for (int i = 0; i != activePeers.length; i++) {
                        activePeers[i] = null;
                    }
                    for (int i = 0; i != activeMsgParts.length; i++) {
                        activeMsgParts[i] = null;
                    }
                } else if (messageIndex != -1) {
                    throw new TranscriptVerificationException("Nothing to verify!");
                }

                messageIndex = logMessage.getIndex();
                PostedMessage pM = PostedMessage.getInstance(lastIn.readObject());
                encPairs = PairSequence.getInstance(pubKey.getParameters().getCurve(), pM.getMessage())
                        .getECPairs();
            }

            addPeer(logMessage.getSequenceNo(), currentPubKey, sourceMessage);

            if (!logMessage.hasPassed()) {
                throw new TranscriptVerificationException("Log message indicates challenge did not pass.");
            }

            for (int i = 0; i != proofs.length; i++) {
                if (!proofs[i].isVerified(activePeers[logMessage.getSequenceNo()], encPairs[i].getX(),
                        sourceMessage[i])) {
                    throw new TranscriptVerificationException(
                            "Proof results do not match combined source message and cipher text.");
                }
            }
        }
    } catch (TranscriptVerificationException e) {
        throw e;
    } catch (Exception e) {
        throw new TranscriptVerificationException(
                "Exception validating decryption challenge transcript: " + e.getMessage(), e);
    }
}

From source file:org.ejbca.core.ejb.ca.crl.ValidationAuthorityTst.java

License:Open Source License

private static void testURI(PrintWriter pw, CrlSessionRemote createCrlSession, String sURI, String caSubjectDN,
        boolean isDelta) throws Exception {
    log.debug("URL: '" + sURI + "'.");
    final HttpURLConnection connection = (HttpURLConnection) new URI(sURI).toURL().openConnection();
    connection.connect();/*from w  ww  .j  av a 2 s .  co m*/
    final int responseCode = connection.getResponseCode();
    if (HttpURLConnection.HTTP_OK != responseCode) {
        if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
            pw.println(
                    "crlstore test not done because crlstore not enabled. To run the test set 'crlstore.enabled' in ./conf/crl.properties and then 'ant deploy' and restart appserver.");
            return;
        }
        pw.println(" Fetching CRL with '" + sURI + "' is not working. responseCode="
                + connection.getResponseCode());
        return;
    }

    final byte fromBean[] = createCrlSession.getLastCRL(admin, caSubjectDN, isDelta);
    final byte fromURL[] = new byte[connection.getContentLength()];
    connection.getInputStream().read(fromURL);
    if (!Arrays.areEqual(fromBean, fromURL)) {
        pw.println(" CRL from URL and bean are not equal for '" + sURI + "'.");
    }
}