1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.base; 6 7 import java.io.FileInputStream; 8 import java.io.IOException; 9 import java.security.SecureRandom; 10 11 /** 12 * This class contains code to initialize a SecureRandom generator securely on Android platforms 13 * <= 4.3. See 14 * {@link http://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html}. 15 */ 16 public class SecureRandomInitializer { 17 private static final int NUM_RANDOM_BYTES = 16; 18 19 private static byte[] sSeedBytes = new byte[NUM_RANDOM_BYTES]; 20 21 /** 22 * Safely initializes the random number generator, by seeding it with data from /dev/urandom. 23 */ initialize(SecureRandom generator)24 public static void initialize(SecureRandom generator) throws IOException { 25 FileInputStream fis = null; 26 try { 27 fis = new FileInputStream("/dev/urandom"); 28 if (fis.read(sSeedBytes) != sSeedBytes.length) { 29 throw new IOException("Failed to get enough random data."); 30 } 31 generator.setSeed(sSeedBytes); 32 } finally { 33 try { 34 if (fis != null) { 35 fis.close(); 36 } 37 } catch (IOException e) { 38 // Ignore exception closing the device. 39 } 40 } 41 } 42 } 43