1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 package org.apache.commons.crypto.examples; 19 20 import java.io.IOException; 21 import java.security.GeneralSecurityException; 22 import java.util.Arrays; 23 import java.util.Properties; 24 25 import org.apache.commons.crypto.random.CryptoRandom; 26 import org.apache.commons.crypto.random.CryptoRandomFactory; 27 28 /** 29 * Example showing use of the CryptoRandom API 30 */ 31 public class RandomExample { 32 33 public static void main(final String []args) throws GeneralSecurityException, IOException { 34 // Constructs a byte array to store random data. 35 final byte[] key = new byte[16]; 36 final byte[] iv = new byte[32]; 37 38 final Properties properties = new Properties(); 39 properties.put(CryptoRandomFactory.CLASSES_KEY, 40 CryptoRandomFactory.RandomProvider.OPENSSL.getClassName()); 41 42 // Gets the 'CryptoRandom' instance. 43 try (CryptoRandom random = CryptoRandomFactory.getCryptoRandom(properties)) { 44 45 // Show the actual class (may be different from the one requested) 46 System.out.println(random.getClass().getCanonicalName()); 47 48 // Generate random bytes and places them into the byte arrays. 49 random.nextBytes(key); 50 random.nextBytes(iv); 51 52 } 53 54 // Show the generated output 55 System.out.println(Arrays.toString(key)); 56 System.out.println(Arrays.toString(iv)); 57 } 58 }