KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snmp4j > security > Salt


1 /*_############################################################################
2   _##
3   _## SNMP4J - Salt.java
4   _##
5   _## Copyright 2003-2007 Frank Fock and Jochen Katz (SNMP4J.org)
6   _##
7   _## Licensed under the Apache License, Version 2.0 (the "License");
8   _## you may not use this file except in compliance with the License.
9   _## 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
22
23
24 package org.snmp4j.security;
25
26 import java.util.Random JavaDoc;
27 import java.security.SecureRandom JavaDoc;
28 import java.security.NoSuchAlgorithmException JavaDoc;
29 import org.snmp4j.log.*;
30
31 /**
32  * Class that holds a 64 bit salt value for crypto operations.
33  *
34  * This class tries to use the SecureRandom class to initialize
35  * the salt value. If SecureRandom is not available the class Random
36  * is used.
37  *
38  * @author Jochen Katz
39  * @version 1.0
40  */

41 class Salt {
42   private long salt;
43
44   private static Salt instance = null;
45   private static final LogAdapter logger = LogFactory.getLogger(Salt.class);
46
47   /**
48    * Default constructor, initializes the salt to a random value.
49    */

50   protected Salt() {
51     byte[] rnd = new byte[8];
52
53     try {
54       SecureRandom JavaDoc sr = SecureRandom.getInstance("SHA1PRNG");
55       sr.nextBytes(rnd);
56     }
57     catch (NoSuchAlgorithmException JavaDoc nsae) {
58       logger.warn("Could not use SecureRandom. Using Random instead.");
59       Random JavaDoc r = new Random JavaDoc();
60       r.nextBytes(rnd);
61     }
62
63     salt = rnd[0];
64
65     for (int i = 0; i < 7; i++) {
66       salt = (salt * 256) + ((int)rnd[i]) + 128;
67     }
68     if (logger.isDebugEnabled() == true) {
69       logger.debug("Initialized Salt to " + Long.toHexString(salt) + ".");
70     }
71   }
72
73   /**
74    * Get a initialized Salt object.
75    *
76    * @return the Salt object
77    */

78   public static Salt getInstance() {
79     if (instance == null) {
80       instance = new Salt();
81     }
82     return instance;
83   }
84
85   /**
86    * Get the next value of the salt.
87    *
88    * @return
89    * previous value increased by one.
90    */

91   public synchronized long getNext() {
92     return salt++;
93   }
94 }
95
Popular Tags