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.hyperledger.common.MasterPublicKey.java

License:Apache License

@Override
public boolean equals(Object obj) {
    if (obj instanceof MasterPublicKey) {
        return master.equals(((MasterPublicKey) obj).master)
                && Arrays.areEqual(chainCode, ((MasterPublicKey) obj).chainCode)
                && depth == ((MasterPublicKey) obj).depth && parent == ((MasterPublicKey) obj).parent
                && sequence == ((MasterPublicKey) obj).sequence;
    }/*from   w ww .  j a va  2 s .com*/
    return false;
}

From source file:org.hyperledger.common.PublicKey.java

License:Apache License

@Override
public boolean equals(Object obj) {
    if (obj instanceof PublicKey) {
        return Arrays.areEqual(pub, ((PublicKey) obj).pub) && compressed == ((PublicKey) obj).compressed;
    }/* w  ww.j av  a 2s  .  c  o  m*/
    return false;
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

License:Open Source License

public byte[] eciesDecrypt(KeyPair keyPair, byte[] data) throws CryptoException {
    try {/*from   w  w  w .  j ava  2s.  c om*/
        int ek_len = (int) (Math.floor((this.securityLevel + 7) / 8) * 2 + 1);
        int mk_len = this.securityLevel >> 3;
        int em_len = data.length - ek_len - mk_len;

        byte[] ephemeralPublicKeyBytes = Arrays.copyOfRange(data, 0, ek_len);
        byte[] encryptedMessage = Arrays.copyOfRange(data, ek_len, ek_len + em_len);
        byte[] tag = Arrays.copyOfRange(data, ek_len + em_len, data.length);

        // Parsing public key.
        ECParameterSpec asymmetricKeyParams = generateECParameterSpec();
        KeyFactory asymmetricKeyFactory = KeyFactory.getInstance(ASYMMETRIC_KEY_TYPE, SECURITY_PROVIDER);

        PublicKey ephemeralPublicKey = asymmetricKeyFactory.generatePublic(new ECPublicKeySpec(
                asymmetricKeyParams.getCurve().decodePoint(ephemeralPublicKeyBytes), asymmetricKeyParams));

        // Deriving shared secret.
        KeyAgreement keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_ALGORITHM, SECURITY_PROVIDER);
        keyAgreement.init(keyPair.getPrivate());
        keyAgreement.doPhase(ephemeralPublicKey, true);
        byte[] sharedSecret = keyAgreement.generateSecret();

        // Deriving encryption and mac keys.
        HKDFBytesGenerator hkdfBytesGenerator = new HKDFBytesGenerator(getHashDigest());

        hkdfBytesGenerator.init(new HKDFParameters(sharedSecret, null, null));
        byte[] encryptionKey = new byte[SYMMETRIC_KEY_BYTE_COUNT];
        hkdfBytesGenerator.generateBytes(encryptionKey, 0, SYMMETRIC_KEY_BYTE_COUNT);

        byte[] macKey = new byte[MAC_KEY_BYTE_COUNT];
        hkdfBytesGenerator.generateBytes(macKey, 0, MAC_KEY_BYTE_COUNT);

        // Verifying Message Authentication Code (aka mac/tag)
        byte[] expectedTag = calculateMac(macKey, encryptedMessage);
        if (!Arrays.areEqual(tag, expectedTag)) {
            throw new RuntimeException("Bad Message Authentication Code!");
        }

        // Decrypting the message.
        byte[] iv = Arrays.copyOfRange(encryptedMessage, 0, 16);
        byte[] encrypted = Arrays.copyOfRange(encryptedMessage, 16, encryptedMessage.length);
        byte[] output = aesDecrypt(encryptionKey, iv, encrypted);

        return output;

    } catch (Exception e) {
        throw new CryptoException("Could not decrypt the message", e);
    }

}

From source file:org.jafer.conf.Config.java

License:Open Source License

public static boolean isSyntaxEqual(int[] syntaxA, int[] syntaxB) {

    return Arrays.areEqual(syntaxA, syntaxB);
}

From source file:org.jenkinsci.plugins.changeassemblyversion.ReplacementsTest.java

License:Open Source License

@Test
public void testBOMFileNotModified() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject project = j.createFreeStyleProject();
    final byte[] originFileBinary = ("using System.Reflection;\n" + "\n" + "[assembly: AssemblyTitle(\"\")]\n"
            + "[assembly: AssemblyDescription(\"\")]\n" + "[assembly: AssemblyCompany(\"\")]\n"
            + "[assembly: AssemblyProduct(\"\")]\n" + "[assembly: AssemblyCopyright(\"\")]\n"
            + "[assembly: AssemblyTrademark(\"\")]\n" + "[assembly: AssemblyCulture(\"\")]\n"
            + "[assembly: AssemblyVersion(\"13.1.1.976\")]").getBytes();
    project.getBuildersList().add(new TestBuilder() {
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
                throws InterruptedException, IOException {
            OutputStream outputStream = build.getWorkspace().child("AssemblyVersion.cs").write();
            try {
                outputStream.write(originFileBinary);
            } finally {
                outputStream.close();/*from  ww  w.  j a  va  2 s  .  com*/
            }

            return true;
        }
    });

    ChangeAssemblyVersion builder = new ChangeAssemblyVersion("");
    project.getBuildersList().add(builder);
    FreeStyleBuild build = project.scheduleBuild2(0).get();

    //String s = FileUtils.readFileToString(build.getLogFile());
    InputStream readStream = build.getWorkspace().child("AssemblyVersion.cs").read();

    byte[] binaryAfterChange = IOUtils.toByteArray(readStream);
    String content = new String(binaryAfterChange, "UTF-8");

    // the replaced file should have the same BOM as the origin.
    assertTrue(Arrays.areEqual(originFileBinary, binaryAfterChange));
}

From source file:org.jenkinsci.plugins.changeassemblyversion.ReplacementsTest.java

License:Open Source License

@Test
public void testBOMFileNotModified2() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject project = j.createFreeStyleProject();
    ByteOrderMark bom = ByteOrderMark.UTF_8;
    byte[] bomBinary = bom.getBytes();
    final byte[] originFileContentBinary = ("using System.Reflection;\n" + "\n"
            + "[assembly: AssemblyTitle(\"\")]\n" + "[assembly: AssemblyDescription(\"\")]\n"
            + "[assembly: AssemblyCompany(\"\")]\n" + "[assembly: AssemblyProduct(\"\")]\n"
            + "[assembly: AssemblyCopyright(\"\")]\n" + "[assembly: AssemblyTrademark(\"\")]\n"
            + "[assembly: AssemblyCulture(\"\")]\n" + "[assembly: AssemblyVersion(\"13.1.1.976\")]").getBytes();
    final byte[] originFileBinary = Bytes.concat(bomBinary, originFileContentBinary);
    project.getBuildersList().add(new TestBuilder() {
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
                throws InterruptedException, IOException {
            OutputStream outputStream = build.getWorkspace().child("AssemblyVersion.cs").write();
            try {
                outputStream.write(originFileBinary);
            } finally {
                outputStream.close();/*  ww  w  .  ja v a 2s  . com*/
            }

            return true;
        }
    });

    ChangeAssemblyVersion builder = new ChangeAssemblyVersion("");
    project.getBuildersList().add(builder);
    FreeStyleBuild build = project.scheduleBuild2(0).get();

    //String s = FileUtils.readFileToString(build.getLogFile());
    InputStream readStream = build.getWorkspace().child("AssemblyVersion.cs").read();
    byte[] binaryAfterChange = IOUtils.toByteArray(readStream);
    readStream.close();

    // the replaced file should have the same BOM as the origin.
    assertTrue(Arrays.areEqual(originFileBinary, binaryAfterChange));
}

From source file:org.kercoin.magrit.sshd.auth.GitPublickeyAuthenticator.java

License:Open Source License

boolean areEqual(PublicKey ref, PublicKey candidate) {
    return Arrays.areEqual(ref.getEncoded(), candidate.getEncoded());
}

From source file:org.ndnx.ndn.profiles.nameenum.EnumeratedNameListTestRepo.java

License:Open Source License

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

    try {/*from  www .j  a v a2 s . c o m*/
        NDNHandle handle = NDNHandle.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 ndnd 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 NDNNameEnumerator.

        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.ndnx.ndn.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 ndntime
    NDNTime t0 = NDNTime.fromBinaryTimeAsLong(v0);
    vn0 = new ContentName(name, t0);
    x0 = VersioningProfile.getLastVersionComponent(vn0);
    System.out.println("From ndntime name: " + vn0.toString());
    Assert.assertTrue(Arrays.areEqual(b0, x0));

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

From source file:org.ndnx.ndn.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 ndntime
    NDNTime t0 = NDNTime.fromBinaryTimeAsLong(v0);
    vn0 = new ContentName(name, t0);
    x0 = VersioningProfile.getLastVersionComponent(vn0);
    System.out.println("From ndntime name: " + vn0.toString());
    Assert.assertTrue(Arrays.areEqual(b0, x0));

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