Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / content / public / android / java / src / org / chromium / content / browser / crypto / ByteArrayGenerator.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.content.browser.crypto;
6
7 import java.io.FileInputStream;
8 import java.io.IOException;
9 import java.security.GeneralSecurityException;
10
11 /**
12  * Generates byte arrays for use in crypto algorithms. Defaults to pulling random data
13  * from /dev/urandom, but can be overwritten for other generation methods.
14  */
15 public class ByteArrayGenerator {
16     /**
17      * Polls random data to generate the array.
18      * @param numBytes Length of the array to generate.
19      * @return byte[] containing randomly generated data.
20      */
21     public byte[] getBytes(int numBytes) throws IOException, GeneralSecurityException {
22         FileInputStream fis = null;
23         try {
24             fis = new FileInputStream("/dev/urandom");
25             byte[] bytes = new byte[numBytes];
26             if (bytes.length != fis.read(bytes)) {
27                 throw new GeneralSecurityException("Not enough random data available");
28             }
29             return bytes;
30         } finally {
31             if (fis != null) {
32                 fis.close();
33             }
34         }
35     }
36 }