|
| 1 | +/* |
| 2 | + * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except |
| 5 | + * in compliance with the License. A copy of the License is located at |
| 6 | + * |
| 7 | + * http://aws.amazon.com/apache2.0 |
| 8 | + * |
| 9 | + * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, |
| 10 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 11 | + * specific language governing permissions and limitations under the License. |
| 12 | + */ |
| 13 | + |
| 14 | +package com.amazonaws.encryptionsdk.internal; |
| 15 | + |
| 16 | +import java.security.SecureRandom; |
| 17 | + |
| 18 | +public class RandomBytesGenerator { |
| 19 | + private static final SecureRandom RND = new SecureRandom(); |
| 20 | + |
| 21 | + /* Some Providers (such as the FIPS certified Bouncy Castle) enforce a |
| 22 | + * maximum number of bytes that may be requested from SecureRandom. If |
| 23 | + * the requested len is larger than this value, the Secure Random will |
| 24 | + * be called multiple times to achieve the requested total length. */ |
| 25 | + private static final int MAX_BYTES = 1 << 15; |
| 26 | + |
| 27 | + /** |
| 28 | + * Generates a byte array of random data of the given length. |
| 29 | + * |
| 30 | + * @param len The length of the byte array. |
| 31 | + * @return The byte array. |
| 32 | + */ |
| 33 | + public static byte[] generate(final int len) { |
| 34 | + final byte[] result = new byte[len]; |
| 35 | + int bytesGenerated = 0; |
| 36 | + |
| 37 | + while (bytesGenerated < len) { |
| 38 | + final int requestSize = Math.min(MAX_BYTES, len - bytesGenerated); |
| 39 | + final byte[] request = new byte[requestSize]; |
| 40 | + RND.nextBytes(request); |
| 41 | + System.arraycopy(request, 0, result, bytesGenerated, requestSize); |
| 42 | + bytesGenerated += requestSize; |
| 43 | + } |
| 44 | + |
| 45 | + return result; |
| 46 | + } |
| 47 | + |
| 48 | +} |
0 commit comments