Example usage for org.bouncycastle.util Arrays fill

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

Introduction

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

Prototype

public static void fill(short[] a, short val) 

Source Link

Usage

From source file:com.distrimind.util.crypto.BCKeyAgreement.java

License:Open Source License

@Override
public SymmetricSecretKey generateSecretKey(short keySize) throws IllegalStateException {
    byte[] secret = generateSecret();
    if (type.useKDF()) {
        byte[] keyBytes = new byte[keySize];

        FipsKDF.AgreementKDFParameters params = kdfAlgorithm.using(secret).withIV(paramskeymaterial);

        FipsKDF.AgreementOperatorFactory kdfOperatorFactory = new FipsKDF.AgreementOperatorFactory();

        KDFCalculator<AgreementKDFParameters> kdf = kdfOperatorFactory.createKDFCalculator(params);

        kdf.generateBytes(keyBytes, 0, keyBytes.length);

        Arrays.fill(secret, (byte) 0);

        secret = keyBytes;/*from w w  w .  j av  a 2 s  .  c  o m*/
    } else {
        byte[] key = new byte[keySize];

        System.arraycopy(secret, 0, key, 0, key.length);

        Arrays.fill(secret, (byte) 0);

        secret = key;
    }

    if (encryptionType == null)
        return new SymmetricSecretKey(signatureType, new org.bouncycastle.crypto.SymmetricSecretKey(
                signatureType.getBouncyCastleAlgorithm(), secret), (short) (keySize * 8));
    else
        return new SymmetricSecretKey(encryptionType, new org.bouncycastle.crypto.SymmetricSecretKey(
                encryptionType.getBouncyCastleAlgorithm(), secret), (short) (keySize * 8));
}

From source file:freenet.crypt.OCBBlockCipher_v149.java

License:Open Source License

protected void clear(byte[] bs) {
    if (bs != null) {
        Arrays.fill(bs, (byte) 0);
    }
}

From source file:hr.weekOfCode30.CandyReplenshingRobotTest.java

License:Apache License

@Test
public void testBoundaryConditions() {
    int n = 100;//from   w  w w.j  a v  a  2s  .c o  m
    int t = 100;
    int[] c = new int[100];
    Arrays.fill(c, n);
    int refillCount = CandyReplenshingRobot.getCandiesToAdd(n, t, c);
    Assert.assertEquals(9900, refillCount);

    n = 1;
    t = 1;
    c = new int[100];
    Arrays.fill(c, n);
    refillCount = CandyReplenshingRobot.getCandiesToAdd(n, t, c);
    Assert.assertEquals(0, refillCount);
}

From source file:me.noip.ksmigrod.giif.crypto.signencrypt.SwingCallbackHandler.java

License:Apache License

@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (Callback callback : callbacks) {
        if (callback instanceof TextOutputCallback) {
            TextOutputCallback cb = (TextOutputCallback) callback;
            log.info("TextOutputCallback");
            System.out.println("" + cb.getMessageType() + " " + cb.getMessage());
        } else if (callback instanceof NameCallback) {
            NameCallback cb = (NameCallback) callback;
            log.info("NameCallback");
            System.out.println("" + cb.getPrompt());
        } else if (callback instanceof PasswordCallback) {
            log.info("PasswordCallback");
            // prompt the user for sensitive information
            PasswordCallback pc = (PasswordCallback) callback;
            // I don't want to call password callback methods through thread
            // boundary, therefore StringBuilder use.
            final StringBuilder storedPassword = new StringBuilder();
            try {
                SwingUtilities.invokeAndWait(new Runnable() {

                    @Override/*from ww  w  . ja  v  a 2s .co  m*/
                    public void run() {
                        JPasswordField jpf = new JPasswordField();
                        JLabel label = new JLabel("Podaj pin karty");
                        JOptionPane.showConfirmDialog(null, new Object[] { label, jpf }, "PIN Password",
                                JOptionPane.OK_CANCEL_OPTION);
                        char[] password = jpf.getPassword();
                        storedPassword.append(password);
                        // Overwrite password in GUI element.
                        Arrays.fill(password, '\u0000');
                    }
                });
            } catch (InterruptedException ex) {
                log.error("PIN dialog was interrupted.", ex);
                if (Msg.exceptionDialog("PIN dialog fas interrupted.", ex)) {
                    System.exit(-1);
                }
            } catch (InvocationTargetException ex) {
                log.error("Error in PIN dialog.", ex);
                if (Msg.exceptionDialog("PIN dialog problem", ex)) {
                    System.exit(-1);
                }
            }
            pc.setPassword(storedPassword.toString().toCharArray());
            for (int i = 0; i < storedPassword.length(); i++) {
                storedPassword.setCharAt(i, '\u0000');
            }
        } else {
            throw new UnsupportedCallbackException(callback, "Unrecognized Callback");
        }
    }
}

From source file:org.apache.accumulo.test.replication.GarbageCollectorCommunicatesWithTServersIT.java

License:Apache License

@Test
public void testUnreferencedWalInTserverIsClosed() throws Exception {
    final String[] names = getUniqueNames(2);
    // `table` will be replicated, `otherTable` is only used to roll the WAL on the tserver
    final String table = names[0], otherTable = names[1];
    final Connector conn = getConnector();

    // Bring the replication table online first and foremost
    ReplicationTable.setOnline(conn);//from  w  w  w  .  j  a  va  2  s  . c o m

    log.info("Creating {}", table);
    conn.tableOperations().create(table);

    conn.tableOperations().setProperty(table, Property.TABLE_REPLICATION.getKey(), "true");

    log.info("Writing a few mutations to the table");

    BatchWriter bw = conn.createBatchWriter(table, null);

    byte[] empty = new byte[0];
    for (int i = 0; i < 5; i++) {
        Mutation m = new Mutation(Integer.toString(i));
        m.put(empty, empty, empty);
        bw.addMutation(m);
    }

    log.info("Flushing mutations to the server");
    bw.close();

    log.info("Checking that metadata only has one WAL recorded for this table");

    Set<String> wals = getWalsForTable(table);
    Assert.assertEquals("Expected to only find one WAL for the table", 1, wals.size());

    log.info("Compacting the table which will remove all WALs from the tablets");

    // Flush our test table to remove the WAL references in it
    conn.tableOperations().flush(table, null, null, true);
    // Flush the metadata table too because it will have a reference to the WAL
    conn.tableOperations().flush(MetadataTable.NAME, null, null, true);

    log.info("Fetching replication statuses from metadata table");

    Map<String, Status> fileToStatus = getMetadataStatusForTable(table);

    Assert.assertEquals("Expected to only find one replication status message", 1, fileToStatus.size());

    String walName = fileToStatus.keySet().iterator().next();
    Assert.assertEquals("Expected log file name from tablet to equal replication entry", wals.iterator().next(),
            walName);

    Status status = fileToStatus.get(walName);

    Assert.assertEquals("Expected Status for file to not be closed", false, status.getClosed());

    log.info("Checking to see that log entries are removed from tablet section after MinC");
    // After compaction, the log column should be gone from the tablet
    Set<String> walsAfterMinc = getWalsForTable(table);
    Assert.assertEquals("Expected to find no WALs for tablet", 0, walsAfterMinc.size());

    Set<String> filesForTable = getFilesForTable(table);
    Assert.assertEquals("Expected to only find one rfile for table", 1, filesForTable.size());
    log.info("Files for table before MajC: {}", filesForTable);

    // Issue a MajC to roll a new file in HDFS
    conn.tableOperations().compact(table, null, null, false, true);

    Set<String> filesForTableAfterCompaction = getFilesForTable(table);

    log.info("Files for table after MajC: {}", filesForTableAfterCompaction);

    Assert.assertEquals("Expected to only find one rfile for table", 1, filesForTableAfterCompaction.size());
    Assert.assertNotEquals("Expected the files before and after compaction to differ",
            filesForTableAfterCompaction, filesForTable);

    // Use the rfile which was just replaced by the MajC to determine when the GC has ran
    Path fileToBeDeleted = new Path(filesForTable.iterator().next());
    FileSystem fs = fileToBeDeleted.getFileSystem(new Configuration());

    boolean fileExists = fs.exists(fileToBeDeleted);
    while (fileExists) {
        log.info("File which should get deleted still exists: {}", fileToBeDeleted);
        Thread.sleep(2000);
        fileExists = fs.exists(fileToBeDeleted);
    }

    // At this point in time, we *know* that the GarbageCollector has run which means that the Status
    // for our WAL should not be altered.

    log.info("Re-checking that WALs are still not referenced for our table");

    Set<String> walsAfterMajc = getWalsForTable(table);
    Assert.assertEquals("Expected to find no WALs in tablets section: " + walsAfterMajc, 0,
            walsAfterMajc.size());

    Map<String, Status> fileToStatusAfterMinc = getMetadataStatusForTable(table);
    Assert.assertEquals("Expected to still find only one replication status message: " + fileToStatusAfterMinc,
            1, fileToStatusAfterMinc.size());

    Assert.assertEquals("Status before and after MinC should be identical", fileToStatus,
            fileToStatusAfterMinc);

    /*
     * To verify that the WALs is still getting closed, we have to force the tserver to close the existing WAL and open a new one instead. The easiest way to do
     * this is to write a load of data that will exceed the 1.33% full threshold that the logger keeps track of
     */

    conn.tableOperations().create(otherTable);
    bw = conn.createBatchWriter(otherTable, null);
    // 500k
    byte[] bigValue = new byte[1024 * 500];
    Arrays.fill(bigValue, (byte) 1);
    // 500k * 50
    for (int i = 0; i < 50; i++) {
        Mutation m = new Mutation(Integer.toString(i));
        m.put(empty, empty, bigValue);
        bw.addMutation(m);
        if (i % 10 == 0) {
            bw.flush();
        }
    }

    bw.close();

    conn.tableOperations().flush(otherTable, null, null, true);

    // Get the tservers which the master deems as active
    final ClientContext context = new ClientContext(conn.getInstance(),
            new Credentials("root", new PasswordToken(ConfigurableMacIT.ROOT_PASSWORD)), getClientConfig());
    List<String> tservers = MasterClient.execute(context,
            new ClientExecReturn<List<String>, MasterClientService.Client>() {
                @Override
                public List<String> execute(MasterClientService.Client client) throws Exception {
                    return client.getActiveTservers(Tracer.traceInfo(), context.rpcCreds());
                }
            });

    Assert.assertEquals("Expected only one active tservers", 1, tservers.size());

    HostAndPort tserver = HostAndPort.fromString(tservers.get(0));

    // Get the active WALs from that server
    log.info("Fetching active WALs from {}", tserver);

    Client client = ThriftUtil.getTServerClient(tserver, context);
    List<String> activeWalsForTserver = client.getActiveLogs(Tracer.traceInfo(), context.rpcCreds());

    log.info("Active wals: {}", activeWalsForTserver);

    Assert.assertEquals("Expected to find only one active WAL", 1, activeWalsForTserver.size());

    String activeWal = new Path(activeWalsForTserver.get(0)).toString();

    Assert.assertNotEquals("Current active WAL on tserver should not be the original WAL we saw", walName,
            activeWal);

    log.info("Ensuring that replication status does get closed after WAL is no longer in use by Tserver");

    do {
        Map<String, Status> replicationStatuses = getMetadataStatusForTable(table);

        log.info("Got replication status messages {}", replicationStatuses);
        Assert.assertEquals("Did not expect to find additional status records", 1, replicationStatuses.size());

        status = replicationStatuses.values().iterator().next();
        log.info("Current status: {}", ProtobufUtil.toString(status));

        if (status.getClosed()) {
            return;
        }

        log.info("Status is not yet closed, waiting for garbage collector to close it");

        Thread.sleep(2000);
    } while (true);
}

From source file:org.apache.drill.test.rowSet.test.TestVariableWidthWriter.java

License:Apache License

/**
 * Test resize monitoring. Add a listener to an Varchar writer,
 * capture each resize, and refuse a resize when the s
 * of the vector exceeds 1 MB. This will trigger an overflow,
 * which will throw an exception which we then check for.
 *//*from   w ww  . j  a v  a  2s  .c  o  m*/

@Test
public void testSizeLimit() {
    try (VarCharVector vector = allocVector(1000)) {
        TestIndex index = new TestIndex();
        VarCharColumnWriter writer = makeWriter(vector, index);
        writer.bindListener(new ColumnWriterListener() {
            // Because assumed array size is 10, so 10 * 1000 = 10,000
            // rounded to 16K
            int totalAlloc = 16384;

            @Override
            public void overflowed(ScalarWriter writer) {
                throw new IllegalStateException("overflow called");
            }

            @Override
            public boolean canExpand(ScalarWriter writer, int delta) {
                totalAlloc += delta;
                return totalAlloc < 1024 * 1024;
            }
        });
        writer.startWrite();

        byte value[] = new byte[423];
        Arrays.fill(value, (byte) 'X');
        try {
            for (int i = 0;; i++) {
                index.index = i;
                writer.startRow();
                writer.setBytes(value, value.length);
                writer.saveRow();
            }
        } catch (IllegalStateException e) {
            assertTrue(e.getMessage().contains("overflow called"));
        }
    }
}

From source file:org.apache.drill.vector.TestToNullable.java

License:Apache License

@SuppressWarnings("resource")
@Test//from  w  w w. ja v a  2s . c o m
public void testVariableWidth() {
    MaterializedField nonNullableSchema = SchemaBuilder.columnSchema("a", MinorType.VARCHAR, DataMode.REQUIRED);
    VarCharVector nonNullableVector = new VarCharVector(nonNullableSchema, fixture.allocator());
    VarCharVector.Mutator mutator = nonNullableVector.getMutator();
    nonNullableVector.allocateNew(100, 20);
    byte value[] = new byte[20];
    for (int i = 0; i < 100; i++) {
        Arrays.fill(value, (byte) ('A' + i % 26));
        mutator.setSafe(i, value);
    }
    mutator.setValueCount(100);

    MaterializedField nullableVarCharSchema = SchemaBuilder.columnSchema("a", MinorType.VARCHAR,
            DataMode.OPTIONAL);
    NullableVarCharVector nullableVector = new NullableVarCharVector(nullableVarCharSchema,
            fixture.allocator());

    nonNullableVector.toNullable(nullableVector);

    assertEquals(0, nonNullableVector.getAccessor().getValueCount());
    NullableVarCharVector.Accessor nullableAccessor = nullableVector.getAccessor();
    assertEquals(100, nullableAccessor.getValueCount());
    for (int i = 0; i < 100; i++) {
        assertFalse(nullableAccessor.isNull(i));
        Arrays.fill(value, (byte) ('A' + i % 26));
        assertTrue(Arrays.areEqual(value, nullableAccessor.get(i)));
    }

    nullableVector.clear();

    // Don't clear the nonNullableVector, it should be empty.
    // If it is not, the test will fail with a memory leak error.
}

From source file:org.apache.drill.vector.TestVectorLimits.java

License:Apache License

/**
 * Baseline test for a variable-width vector using <tt>setSafe</tt> and
 * loading the vector up to the maximum size. Doing so will cause the vector
 * to have a buffer that exceeds the maximum size, demonstrating the
 * need for <tt>setScalar()</tt>.
 *//*from w w  w  .  j a v  a  2  s .co m*/

@Test
public void variableVectorBaseline() {

    // Create a non-nullable VarChar vector: a typical variable-size vector

    @SuppressWarnings("resource")
    VarCharVector vector = new VarCharVector(makeField(MinorType.VARCHAR, DataMode.REQUIRED),
            fixture.allocator());
    vector.allocateNew();

    // A 16 MB value can hold 64K values of up to 256 bytes each.
    // To force a size overflow, write values much larger.
    // Write the maximum number of values which will silently
    // allow the vector to grow beyond the critical size of 16 MB.
    // Doing this in production would lead to memory fragmentation.
    // So, this is what the setScalar() method assures we don't do.

    byte dummyValue[] = new byte[512];
    Arrays.fill(dummyValue, (byte) 'X');
    VarCharVector.Mutator mutator = vector.getMutator();
    for (int i = 0; i < 2 * ValueVector.MAX_ROW_COUNT; i++) {
        mutator.setSafe(i, dummyValue, 0, dummyValue.length);
    }

    // The vector should be above the allocation limit.
    // This is why code must migrate to the setScalar() call
    // away from the setSafe() call.

    assertTrue(ValueVector.MAX_BUFFER_SIZE < vector.getBuffer().getActualMemoryConsumed());
    vector.close();
}

From source file:org.apache.drill.vector.TestVectorLimits.java

License:Apache License

private byte[] makeVarCharValue(int n) {
    byte dummyValue[] = new byte[n];
    Arrays.fill(dummyValue, (byte) 'X');
    return dummyValue;
}

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

License:Open Source License

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    Log.info(Log.FAC_TEST, "Setting up CCNNetworkObjectTest, prefix {0}", testHelper.getClassNamespace());

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

    ns = new ContentName[NUM_LINKS];
    for (int i = 0; i < NUM_LINKS; ++i) {
        ns[i] = new ContentName(testHelper.getClassNamespace(), "Links", prefix + Integer.toString(i));
    }
    Arrays.fill(publisherid1, (byte) 6);
    Arrays.fill(publisherid2, (byte) 3);

    pubID1 = new PublisherID(publisherid1, PublisherType.KEY);
    pubID2 = new PublisherID(publisherid2, PublisherType.ISSUER_KEY);

    las[0] = new LinkAuthenticator(pubID1);
    las[1] = null;
    las[2] = new LinkAuthenticator(pubID2, null, null, SignedInfo.ContentType.DATA, contenthash1);
    las[3] = new LinkAuthenticator(pubID1, null, CCNTime.now(), null, contenthash1);

    for (int j = 4; j < NUM_LINKS; ++j) {
        las[j] = new LinkAuthenticator(pubID2, null, CCNTime.now(), null, null);
    }

    lrs = new Link[NUM_LINKS];
    for (int i = 0; i < lrs.length; ++i) {
        lrs[i] = new Link(ns[i], las[i]);
    }

    empty = new Collection();
    small1 = new Collection();
    small2 = new Collection();
    for (int i = 0; i < 5; ++i) {
        small1.add(lrs[i]);
        small2.add(lrs[i + 5]);
    }
    big = new Collection();
    for (int i = 0; i < NUM_LINKS; ++i) {
        big.add(lrs[i]);
    }

    flosser = new Flosser();
    Log.info(Log.FAC_TEST, "Finished setting up CCNNetworkObjectTest, prefix is: {0}.",
            testHelper.getClassNamespace());
}