List of usage examples for java.util Random nextBytes
public void nextBytes(byte[] bytes)
From source file:org.opendaylight.aaa.encrypt.AAAEncryptionServiceImpl.java
public AAAEncryptionServiceImpl(AaaEncryptServiceConfig encrySrvConfig, final DataBroker dataBroker) { SecretKey tempKey = null;//from w ww. j a v a 2 s . c o m IvParameterSpec tempIvSpec = null; if (encrySrvConfig.getEncryptSalt() == null) { throw new IllegalArgumentException( "null encryptSalt in AaaEncryptServiceConfig: " + encrySrvConfig.toString()); } if (encrySrvConfig.getEncryptKey() != null && encrySrvConfig.getEncryptKey().isEmpty()) { LOG.debug("Set the Encryption service password and encrypt salt"); String newPwd = RandomStringUtils.random(encrySrvConfig.getPasswordLength(), true, true); final Random random = new SecureRandom(); byte[] salt = new byte[16]; random.nextBytes(salt); String encodedSalt = Base64.getEncoder().encodeToString(salt); encrySrvConfig = new AaaEncryptServiceConfigBuilder(encrySrvConfig).setEncryptKey(newPwd) .setEncryptSalt(encodedSalt).build(); updateEncrySrvConfig(newPwd, encodedSalt); initializeConfigDataTree(encrySrvConfig, dataBroker); } final byte[] enryptionKeySalt = Base64.getDecoder().decode(encrySrvConfig.getEncryptSalt()); try { final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encrySrvConfig.getEncryptMethod()); final KeySpec spec = new PBEKeySpec(encrySrvConfig.getEncryptKey().toCharArray(), enryptionKeySalt, encrySrvConfig.getEncryptIterationCount(), encrySrvConfig.getEncryptKeyLength()); tempKey = keyFactory.generateSecret(spec); tempKey = new SecretKeySpec(tempKey.getEncoded(), encrySrvConfig.getEncryptType()); tempIvSpec = new IvParameterSpec(enryptionKeySalt); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { LOG.error("Failed to initialize secret key", e); } key = tempKey; ivspec = tempIvSpec; Cipher cipher = null; try { cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms()); cipher.init(Cipher.ENCRYPT_MODE, key, ivspec); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { LOG.error("Failed to create encrypt cipher.", e); } this.encryptCipher = cipher; cipher = null; try { cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms()); cipher.init(Cipher.DECRYPT_MODE, key, ivspec); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { LOG.error("Failed to create decrypt cipher.", e); } this.decryptCipher = cipher; }
From source file:org.apache.hadoop.io.TestArrayOutputStream.java
private void runComparison(ArrayOutputStream aos, DataOutputStream dos, ByteArrayOutputStream bos) throws IOException { Random r = new Random(); // byte/*w w w. j a va2 s . c o m*/ int b = r.nextInt(128); aos.write(b); dos.write(b); // byte[] byte[] bytes = new byte[10]; r.nextBytes(bytes); aos.write(bytes, 0, 10); dos.write(bytes, 0, 10); // Byte aos.writeByte(b); dos.writeByte(b); // boolean boolean bool = r.nextBoolean(); aos.writeBoolean(bool); dos.writeBoolean(bool); // short short s = (short) r.nextInt(); aos.writeShort(s); dos.writeShort(s); // char int c = r.nextInt(); aos.writeChar(c); dos.writeChar(c); // int int i = r.nextInt(); aos.writeInt(i); dos.writeInt(i); // long long l = r.nextLong(); aos.writeLong(l); dos.writeLong(l); // float float f = r.nextFloat(); aos.writeFloat(f); dos.writeFloat(f); // double double d = r.nextDouble(); aos.writeDouble(d); dos.writeDouble(d); // strings String str = RandomStringUtils.random(20); aos.writeBytes(str); aos.writeChars(str); aos.writeUTF(str); dos.writeBytes(str); dos.writeChars(str); dos.writeUTF(str); byte[] expected = bos.toByteArray(); assertEquals(expected.length, aos.size()); byte[] actual = new byte[aos.size()]; System.arraycopy(aos.getBytes(), 0, actual, 0, actual.length); // serialized bytes should be the same assertTrue(Arrays.equals(expected, actual)); }
From source file:org.opcfoundation.ua.examples.BigCertificateExample.java
@Override public void onCreateSession(EndpointServiceRequest<CreateSessionRequest, CreateSessionResponse> msgExchange) throws ServiceFaultException { CreateSessionRequest req = msgExchange.getRequest(); CreateSessionResponse res = new CreateSessionResponse(); byte[] token = new byte[32]; byte[] nonce = new byte[32]; Random r = new Random(); r.nextBytes(nonce); r.nextBytes(token);//from w w w . j a v a 2s .c o m SignatureData signatureData = new SignatureData(); //signatureData.setAlgorithm(Algorithm) res.setAuthenticationToken(new NodeId(0, token)); EndpointConfiguration endpointConfiguration = EndpointConfiguration.defaults(); res.setMaxRequestMessageSize(UnsignedInteger.valueOf( Math.max(endpointConfiguration.getMaxMessageSize(), req.getMaxResponseMessageSize().longValue()))); res.setRevisedSessionTimeout(Math.max(req.getRequestedSessionTimeout(), 60 * 1000)); res.setServerCertificate( getApplication().getApplicationInstanceCertificates()[0].getCertificate().encodedCertificate); res.setServerEndpoints(this.getEndpointDescriptions()); res.setServerNonce(nonce); res.setServerSignature(signatureData); res.setServerSoftwareCertificates(getApplication().getSoftwareCertificates()); res.setSessionId(new NodeId(0, "Client")); msgExchange.sendResponse(res); }
From source file:com.microsoft.azure.storage.queue.CloudQueueEncryptionTests.java
@Test public void testQueueMessageValidateEncryption() throws StorageException, JsonProcessingException, IOException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InterruptedException, ExecutionException { // Create the Key to be used for wrapping. SymmetricKey aesKey = TestHelper.getSymmetricKey(); byte[] messageBytes = new byte[100]; Random rand = new Random(); rand.nextBytes(messageBytes); String inputMessage = Base64.encode(messageBytes); CloudQueueMessage message = new CloudQueueMessage(inputMessage); this.queue.setShouldEncodeMessage(false); QueueRequestOptions options = new QueueRequestOptions(); options.setEncryptionPolicy(new QueueEncryptionPolicy(aesKey, null)); // add message this.queue.addMessage(message, 0, 0, options, null); // Retrieve message without decrypting CloudQueueMessage retrMessage = this.queue.retrieveMessage(); // Decrypt locally CloudQueueMessage decryptedMessage;/* www . jav a 2 s . co m*/ CloudQueueEncryptedMessage encryptedMessage = CloudQueueEncryptedMessage .deserialize(retrMessage.getMessageContentAsString()); EncryptionData encryptionData = encryptedMessage.getEncryptionData(); byte[] contentEncryptionKey = aesKey.unwrapKeyAsync(encryptionData.getWrappedContentKey().getEncryptedKey(), encryptionData.getWrappedContentKey().getAlgorithm()).get(); SecretKey keySpec = new SecretKeySpec(contentEncryptionKey, 0, contentEncryptionKey.length, "AES"); Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding"); myAes.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(encryptionData.getContentEncryptionIV())); byte[] src = Base64.decode(encryptedMessage.getEncryptedMessageContents()); decryptedMessage = new CloudQueueMessage(myAes.doFinal(src, 0, src.length)); assertArrayEquals(message.getMessageContentAsByte(), decryptedMessage.getMessageContentAsByte()); }
From source file:org.daxplore.presenter.shared.Base64Test.java
/** * Test Base64Coder against Apache Commons Base64 Encoder/Decoder with * random data.//from w w w . j a v a 2 s . c o m * * @throws IOException * Thrown by the Apache decoder. */ @Test public void testBase64Random() throws IOException { final int maxLineLen = 100; final int maxDataBlockLen = (maxLineLen * 3) / 4; org.apache.commons.codec.binary.Base64 apacheCoder = new org.apache.commons.codec.binary.Base64(); Random rnd = new Random(0x538afb92); for (int i = 0; i < 1000; i++) { int len = rnd.nextInt(maxDataBlockLen + 1); byte[] b0 = new byte[len]; rnd.nextBytes(b0); String e1 = new String(Base64.encode(b0)); String e2 = new String(apacheCoder.encode(b0), "UTF-8"); assertEquals(e2, e1); byte[] b1 = Base64.decode(e1); byte[] b2 = apacheCoder.decode(e2.getBytes("UTF-8")); assertArrayEquals(b0, b1); assertArrayEquals(b0, b2); } }
From source file:com.ephesoft.dcma.encryption.core.EncryptorDecryptor.java
private byte[] generateSalt(int saltLength) { Random random = new Random(); random.setSeed(System.currentTimeMillis()); byte[] randomBytes = new byte[saltLength]; random.nextBytes(randomBytes); return randomBytes; }
From source file:org.apache.cassandra.io.compress.CompressedSequentialWriterTest.java
private void testWrite(File f, int bytesToTest) throws IOException { final String filename = f.getAbsolutePath(); final ChannelProxy channel = new ChannelProxy(f); try {//w w w. ja v a 2 s . co m MetadataCollector sstableMetadataCollector = new MetadataCollector( new SimpleDenseCellNameType(BytesType.instance)).replayPosition(null); byte[] dataPre = new byte[bytesToTest]; byte[] rawPost = new byte[bytesToTest]; try (CompressedSequentialWriter writer = new CompressedSequentialWriter(f, filename + ".metadata", new CompressionParameters(compressor), sstableMetadataCollector);) { Random r = new Random(); // Test both write with byte[] and ByteBuffer r.nextBytes(dataPre); r.nextBytes(rawPost); ByteBuffer dataPost = makeBB(bytesToTest); dataPost.put(rawPost); dataPost.flip(); writer.write(dataPre); FileMark mark = writer.mark(); // Write enough garbage to transition chunk for (int i = 0; i < CompressionParameters.DEFAULT_CHUNK_LENGTH; i++) { writer.write((byte) i); } writer.resetAndTruncate(mark); writer.write(dataPost); writer.finish(); } assert f.exists(); RandomAccessReader reader = CompressedRandomAccessReader.open(channel, new CompressionMetadata(filename + ".metadata", f.length())); assertEquals(dataPre.length + rawPost.length, reader.length()); byte[] result = new byte[(int) reader.length()]; reader.readFully(result); assert (reader.isEOF()); reader.close(); byte[] fullInput = new byte[bytesToTest * 2]; System.arraycopy(dataPre, 0, fullInput, 0, dataPre.length); System.arraycopy(rawPost, 0, fullInput, bytesToTest, rawPost.length); assert Arrays.equals(result, fullInput); } finally { // cleanup channel.close(); if (f.exists()) f.delete(); File metadata = new File(f + ".metadata"); if (metadata.exists()) metadata.delete(); } }
From source file:org.daxplore.presenter.shared.Base64Test.java
/** * Test Base64Coder line encoding/decoding against * Apache Commons Base64 Encoder/Decoder with random data. * //from w w w .j ava 2s . c om * @throws IOException * Thrown by the Sun decoder */ @Test public void testBase64LinesRandom() throws IOException { final int maxDataBlockLen = 512; final int lineLength = 76; org.apache.commons.codec.binary.Base64 apacheCoder = new org.apache.commons.codec.binary.Base64(); Random rnd = new Random(0x39ac7d6e); for (int i = 0; i < 1000; i++) { int len = rnd.nextInt(maxDataBlockLen + 1); byte[] b0 = new byte[len]; rnd.nextBytes(b0); String e1 = Base64.encodeLines(b0); String e2 = new String(apacheCoder.encode(b0), "UTF-8"); StringBuilder e2Lines = new StringBuilder(); for (int j = 0; j < e2.length(); j += lineLength) { e2Lines.append(e2.substring(j, Math.min(j + lineLength, e2.length()))); e2Lines.append("\n"); } e2 = e2Lines.toString(); assertEquals(e2, e1); byte[] b1 = Base64.decodeLines(e1); byte[] b2 = apacheCoder.decode(e2.replace("\n", "").getBytes("UTF-8")); assertArrayEquals(b0, b1); assertArrayEquals(b0, b2); } }
From source file:org.apache.flink.hdfstests.FileStateBackendTest.java
@Test public void testStateOutputStream() { URI basePath = randomHdfsFileUri(); try {/*from w w w . j a v a 2s . c o m*/ FsStateBackend backend = CommonTestUtils.createCopySerializable(new FsStateBackend(basePath, 15)); JobID jobId = new JobID(); CheckpointStreamFactory streamFactory = backend.createStreamFactory(jobId, "test_op"); // we know how FsCheckpointStreamFactory is implemented so we know where it // will store checkpoints Path checkpointPath = new Path(new Path(basePath), jobId.toString()); byte[] state1 = new byte[1274673]; byte[] state2 = new byte[1]; byte[] state3 = new byte[0]; byte[] state4 = new byte[177]; Random rnd = new Random(); rnd.nextBytes(state1); rnd.nextBytes(state2); rnd.nextBytes(state3); rnd.nextBytes(state4); long checkpointId = 97231523452L; CheckpointStreamFactory.CheckpointStateOutputStream stream1 = streamFactory .createCheckpointStateOutputStream(checkpointId, System.currentTimeMillis()); CheckpointStreamFactory.CheckpointStateOutputStream stream2 = streamFactory .createCheckpointStateOutputStream(checkpointId, System.currentTimeMillis()); CheckpointStreamFactory.CheckpointStateOutputStream stream3 = streamFactory .createCheckpointStateOutputStream(checkpointId, System.currentTimeMillis()); stream1.write(state1); stream2.write(state2); stream3.write(state3); FileStateHandle handle1 = (FileStateHandle) stream1.closeAndGetHandle(); ByteStreamStateHandle handle2 = (ByteStreamStateHandle) stream2.closeAndGetHandle(); ByteStreamStateHandle handle3 = (ByteStreamStateHandle) stream3.closeAndGetHandle(); // use with try-with-resources FileStateHandle handle4; try (CheckpointStreamFactory.CheckpointStateOutputStream stream4 = streamFactory .createCheckpointStateOutputStream(checkpointId, System.currentTimeMillis())) { stream4.write(state4); handle4 = (FileStateHandle) stream4.closeAndGetHandle(); } // close before accessing handle CheckpointStreamFactory.CheckpointStateOutputStream stream5 = streamFactory .createCheckpointStateOutputStream(checkpointId, System.currentTimeMillis()); stream5.write(state4); stream5.close(); try { stream5.closeAndGetHandle(); fail(); } catch (IOException e) { // uh-huh } validateBytesInStream(handle1.openInputStream(), state1); handle1.discardState(); assertFalse(isDirectoryEmpty(checkpointPath)); ensureFileDeleted(handle1.getFilePath()); validateBytesInStream(handle2.openInputStream(), state2); handle2.discardState(); // stream 3 has zero bytes, so it should not return anything assertNull(handle3); validateBytesInStream(handle4.openInputStream(), state4); handle4.discardState(); assertTrue(isDirectoryEmpty(checkpointPath)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:org.apache.hadoop.dfs.TestReplication.java
private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException { // create and write a file that contains three blocks of data FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize); byte[] buffer = new byte[fileSize]; Random rand = new Random(seed); rand.nextBytes(buffer); stm.write(buffer);// w w w .j a v a2 s . c om stm.close(); }