01: /*_############################################################################
02: _##
03: _## SNMP4J - Salt.java
04: _##
05: _## Copyright (C) 2003-2008 Frank Fock and Jochen Katz (SNMP4J.org)
06: _##
07: _## Licensed under the Apache License, Version 2.0 (the "License");
08: _## you may not use this file except in compliance with the License.
09: _## You may obtain a copy of the License at
10: _##
11: _## http://www.apache.org/licenses/LICENSE-2.0
12: _##
13: _## Unless required by applicable law or agreed to in writing, software
14: _## distributed under the License is distributed on an "AS IS" BASIS,
15: _## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16: _## See the License for the specific language governing permissions and
17: _## limitations under the License.
18: _##
19: _##########################################################################*/
20:
21: package org.snmp4j.security;
22:
23: import java.util.Random;
24: import java.security.SecureRandom;
25: import java.security.NoSuchAlgorithmException;
26: import org.snmp4j.log.*;
27:
28: /**
29: * Class that holds a 64 bit salt value for crypto operations.
30: *
31: * This class tries to use the SecureRandom class to initialize
32: * the salt value. If SecureRandom is not available the class Random
33: * is used.
34: *
35: * @author Jochen Katz
36: * @version 1.0
37: */
38: class Salt {
39: private long salt;
40:
41: private static Salt instance = null;
42: private static final LogAdapter logger = LogFactory
43: .getLogger(Salt.class);
44:
45: /**
46: * Default constructor, initializes the salt to a random value.
47: */
48: protected Salt() {
49: byte[] rnd = new byte[8];
50:
51: try {
52: SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
53: sr.nextBytes(rnd);
54: } catch (NoSuchAlgorithmException nsae) {
55: logger
56: .warn("Could not use SecureRandom. Using Random instead.");
57: Random r = new Random();
58: r.nextBytes(rnd);
59: }
60:
61: salt = rnd[0];
62:
63: for (int i = 0; i < 7; i++) {
64: salt = (salt * 256) + ((int) rnd[i]) + 128;
65: }
66: if (logger.isDebugEnabled() == true) {
67: logger.debug("Initialized Salt to "
68: + Long.toHexString(salt) + ".");
69: }
70: }
71:
72: /**
73: * Get a initialized Salt object.
74: *
75: * @return the Salt object
76: */
77: public static Salt getInstance() {
78: if (instance == null) {
79: instance = new Salt();
80: }
81: return instance;
82: }
83:
84: /**
85: * Get the next value of the salt.
86: *
87: * @return
88: * previous value increased by one.
89: */
90: public synchronized long getNext() {
91: return salt++;
92: }
93: }
|