|
| 1 | +/* |
| 2 | + * Copyright 2002-2015 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.util; |
| 18 | + |
| 19 | +import java.math.BigInteger; |
| 20 | +import java.security.SecureRandom; |
| 21 | +import java.util.Random; |
| 22 | +import java.util.UUID; |
| 23 | + |
| 24 | +/** |
| 25 | + * An {@link IdGenerator} that uses {@link SecureRandom} for the initial seed and |
| 26 | + * {@link Random} thereafter, instead of calling {@link UUID#randomUUID()} every |
| 27 | + * time as {@link org.springframework.util.JdkIdGenerator JdkIdGenerator} does. |
| 28 | + * This provides a better balance between securely random ids and performance. |
| 29 | + * |
| 30 | + * @author Rossen Stoyanchev |
| 31 | + * @author Rob Winch |
| 32 | + * @since 4.0 |
| 33 | + */ |
| 34 | +public class AlternativeJdkIdGenerator implements IdGenerator { |
| 35 | + |
| 36 | + private final Random random; |
| 37 | + |
| 38 | + |
| 39 | + public AlternativeJdkIdGenerator() { |
| 40 | + SecureRandom secureRandom = new SecureRandom(); |
| 41 | + byte[] seed = new byte[8]; |
| 42 | + secureRandom.nextBytes(seed); |
| 43 | + this.random = new Random(new BigInteger(seed).longValue()); |
| 44 | + } |
| 45 | + |
| 46 | + |
| 47 | + @Override |
| 48 | + public UUID generateId() { |
| 49 | + byte[] randomBytes = new byte[16]; |
| 50 | + this.random.nextBytes(randomBytes); |
| 51 | + |
| 52 | + long mostSigBits = 0; |
| 53 | + for (int i = 0; i < 8; i++) { |
| 54 | + mostSigBits = (mostSigBits << 8) | (randomBytes[i] & 0xff); |
| 55 | + } |
| 56 | + |
| 57 | + long leastSigBits = 0; |
| 58 | + for (int i = 8; i < 16; i++) { |
| 59 | + leastSigBits = (leastSigBits << 8) | (randomBytes[i] & 0xff); |
| 60 | + } |
| 61 | + |
| 62 | + return new UUID(mostSigBits, leastSigBits); |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments