Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / remoting / android / java / src / org / chromium / chromoting / SecureRandomInitializer.java
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.chromoting;
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     /**
20      * Safely initializes the random number generator, by seeding it with data from /dev/urandom.
21      */
22     public static void initialize(SecureRandom generator) throws IOException {
23         FileInputStream fis = null;
24         try {
25             fis = new FileInputStream("/dev/urandom");
26             byte[] bytes = new byte[NUM_RANDOM_BYTES];
27             if (bytes.length != fis.read(bytes)) {
28                 throw new IOException("Failed to get enough random data.");
29             }
30             generator.setSeed(bytes);
31         } finally {
32             try {
33                 if (fis != null) {
34                     fis.close();
35                 }
36             } catch (IOException e) {
37                 // Ignore exception closing the device.
38             }
39         }
40     }
41 }