Classes in this File | Line Coverage | Branch Coverage | Complexity | ||||
TokenGenerator |
|
| 1.3333333333333333;1.333 |
1 | /* | |
2 | * Licensed to the Apache Software Foundation (ASF) under one | |
3 | * or more contributor license agreements. See the NOTICE file | |
4 | * distributed with this work for additional information | |
5 | * regarding copyright ownership. The ASF licenses this file | |
6 | * to you under the Apache License, Version 2.0 (the | |
7 | * "License"); you may not use this file except in compliance | |
8 | * with the License. You may obtain a copy of the License at | |
9 | * | |
10 | * http://www.apache.org/licenses/LICENSE-2.0 | |
11 | * | |
12 | * Unless required by applicable law or agreed to in writing, | |
13 | * software distributed under the License is distributed on an | |
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
15 | * KIND, either express or implied. See the License for the | |
16 | * specific language governing permissions and limitations | |
17 | * under the License. | |
18 | */ | |
19 | package org.apache.myfaces.lifecycle; | |
20 | ||
21 | import java.math.BigInteger; | |
22 | import java.security.NoSuchAlgorithmException; | |
23 | import java.security.SecureRandom; | |
24 | import java.util.concurrent.atomic.AtomicLong; | |
25 | ||
26 | /** | |
27 | * | |
28 | * @author lu4242 | |
29 | */ | |
30 | class TokenGenerator | |
31 | { | |
32 | private final AtomicLong _count; | |
33 | ||
34 | public TokenGenerator() | |
35 | 0 | { |
36 | 0 | _count = new AtomicLong(_getSeed()); |
37 | 0 | } |
38 | ||
39 | private static long _getSeed() | |
40 | { | |
41 | SecureRandom rng; | |
42 | try | |
43 | { | |
44 | // try SHA1 first | |
45 | 0 | rng = SecureRandom.getInstance("SHA1PRNG"); |
46 | } | |
47 | 0 | catch (NoSuchAlgorithmException e) |
48 | { | |
49 | // SHA1 not present, so try the default (which could potentially not be | |
50 | // cryptographically secure) | |
51 | 0 | rng = new SecureRandom(); |
52 | 0 | } |
53 | ||
54 | // use 48 bits for strength and fill them in | |
55 | 0 | byte[] randomBytes = new byte[6]; |
56 | 0 | rng.nextBytes(randomBytes); |
57 | ||
58 | // convert to a long | |
59 | 0 | return new BigInteger(randomBytes).longValue(); |
60 | } | |
61 | ||
62 | /** | |
63 | * Get the next token to be assigned to this request | |
64 | * | |
65 | * @return | |
66 | */ | |
67 | String _getNextToken() | |
68 | { | |
69 | // atomically increment the value | |
70 | 0 | long nextToken = _count.incrementAndGet(); |
71 | ||
72 | // convert using base 36 because it is a fast efficient subset of base-64 | |
73 | 0 | return Long.toString(nextToken, 36); |
74 | } | |
75 | } |