Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: gnu/javax/crypto/prng/PBKDF2.java


1   /* PBKDF2.java -- 
2      Copyright (C) 2003, 2006 Free Software Foundation, Inc.
3   
4   This file is a part of GNU Classpath.
5   
6   GNU Classpath is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2 of the License, or (at
9   your option) any later version.
10  
11  GNU Classpath is distributed in the hope that it will be useful, but
12  WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  General Public License for more details.
15  
16  You should have received a copy of the GNU General Public License
17  along with GNU Classpath; if not, write to the Free Software
18  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19  USA
20  
21  Linking this library statically or dynamically with other modules is
22  making a combined work based on this library.  Thus, the terms and
23  conditions of the GNU General Public License cover the whole
24  combination.
25  
26  As a special exception, the copyright holders of this library give you
27  permission to link this library with independent modules to produce an
28  executable, regardless of the license terms of these independent
29  modules, and to copy and distribute the resulting executable under
30  terms of your choice, provided that you also meet, for each linked
31  independent module, the terms and conditions of the license of that
32  module.  An independent module is a module which is not derived from
33  or based on this library.  If you modify this library, you may extend
34  this exception to your version of the library, but you are not
35  obligated to do so.  If you do not wish to do so, delete this
36  exception statement from your version.  */
37  
38  
39  package gnu.javax.crypto.prng;
40  
41  import gnu.java.security.prng.BasePRNG;
42  import gnu.java.security.prng.LimitReachedException;
43  import gnu.javax.crypto.mac.HMac;
44  import gnu.javax.crypto.mac.IMac;
45  
46  import java.io.UnsupportedEncodingException;
47  import java.util.Arrays;
48  import java.util.HashMap;
49  import java.util.Map;
50  
51  /**
52   * <p>An implementation of the <i>key derivation function</i> KDF2 from PKCS #5:
53   * Password-Based Cryptography (<b>PBE</b>). This KDF is essentially a way to
54   * transform a password and a salt into a stream of random bytes, which may then
55   * be used to initialize a cipher or a MAC.</p>
56   *
57   * <p>This version uses a MAC as its pseudo-random function, and the password is
58   * used as the key.</p>
59   *
60   * <p>References:</p>
61   * <ol>
62   *    <li>B. Kaliski, <a href="http://www.ietf.org/rfc/rfc2898.txt">RFC 2898:
63   *    Password-Based Cryptography Specification, Version 2.0</a></li>
64   * </ol>
65   */
66  public class PBKDF2 extends BasePRNG implements Cloneable
67  {
68  
69    // Contstants and variables
70    // -------------------------------------------------------------------------
71  
72    /**
73     * The bytes fed into the MAC. This is initially the concatenation of the
74     * salt and the block number.
75     */
76    private byte[] in;
77  
78    /** The iteration count. */
79    private int iterationCount;
80  
81    /** The salt. */
82    private byte[] salt;
83  
84    /** The MAC (the pseudo-random function we use). */
85    private IMac mac;
86  
87    /** The number of hLen-sized blocks generated. */
88    private long count;
89  
90    // Constructor(s)
91    // -------------------------------------------------------------------------
92  
93    /**
94     * <p>Creates a new PBKDF2 object. The argument is the MAC that will serve as
95     * the pseudo-random function. The MAC does not need to be initialized.</p>
96     *
97     * @param mac The pseudo-random function.
98     */
99    public PBKDF2(IMac mac)
100   {
101     super("PBKDF2-" + mac.name());
102     this.mac = mac;
103     iterationCount = -1;
104   }
105 
106   // Class methods
107   // -------------------------------------------------------------------------
108 
109   // Instance methods
110   // -------------------------------------------------------------------------
111 
112   public void setup(Map attributes)
113   {
114     Map macAttrib = new HashMap();
115     macAttrib.put(HMac.USE_WITH_PKCS5_V2, Boolean.TRUE);
116 
117     byte[] s = (byte[]) attributes.get(IPBE.SALT);
118     if (s == null)
119       {
120         if (salt == null)
121           {
122             throw new IllegalArgumentException("no salt specified");
123           } // Otherwise re-use.
124       }
125     else
126       {
127         salt = s;
128       }
129 
130     byte[] macKeyMaterial;
131     char[] password = (char[]) attributes.get(IPBE.PASSWORD);
132     if (password != null)
133       {
134         String encoding = (String) attributes.get(IPBE.PASSWORD_ENCODING);
135         if (encoding == null || encoding.trim().length() == 0)
136           encoding = IPBE.DEFAULT_PASSWORD_ENCODING;
137         else
138           encoding = encoding.trim();
139 
140         try
141           {
142             macKeyMaterial = new String(password).getBytes(encoding);
143           }
144         catch (UnsupportedEncodingException uee)
145           {
146             throw new IllegalArgumentException("Unknown or unsupported encoding: "
147                                                + encoding, uee);
148           }
149       }
150     else
151       macKeyMaterial = (byte[]) attributes.get(IMac.MAC_KEY_MATERIAL);
152 
153     if (macKeyMaterial != null)
154       macAttrib.put(IMac.MAC_KEY_MATERIAL, macKeyMaterial);
155     else if (!initialised)
156       throw new IllegalArgumentException("Neither password nor key-material were specified");
157     // otherwise re-use previous password/key-material
158 
159     try
160       {
161         mac.init(macAttrib);
162       }
163     catch (Exception x)
164       {
165         throw new IllegalArgumentException(x.getMessage());
166       }
167 
168     Integer ic = (Integer) attributes.get(IPBE.ITERATION_COUNT);
169     if (ic != null)
170       {
171         iterationCount = ic.intValue();
172       }
173     if (iterationCount <= 0)
174       {
175         throw new IllegalArgumentException("bad iteration count");
176       }
177 
178     count = 0L;
179     buffer = new byte[mac.macSize()];
180     try
181       {
182         fillBlock();
183         //      } catch (Exception x) {
184       }
185     catch (LimitReachedException x)
186       {
187         //         x.printStackTrace(System.err);
188         throw new Error(x.getMessage());
189       }
190   }
191 
192   public void fillBlock() throws LimitReachedException
193   {
194     if (++count > ((1L << 32) - 1))
195       {
196         throw new LimitReachedException();
197       }
198     //      for (int i = 0; i < buffer.length; i++) {
199     //         buffer[i] = 0;
200     //      }
201     Arrays.fill(buffer, (byte) 0x00);
202     int limit = salt.length;
203     //      in = new byte[salt.length + 4];
204     in = new byte[limit + 4];
205     System.arraycopy(salt, 0, in, 0, salt.length);
206     //      in[salt.length  ] = (byte)(count >>> 24);
207     //      in[salt.length+1] = (byte)(count >>> 16);
208     //      in[salt.length+2] = (byte)(count >>>  8);
209     //      in[salt.length+3] = (byte) count;
210     in[limit++] = (byte) (count >>> 24);
211     in[limit++] = (byte) (count >>> 16);
212     in[limit++] = (byte) (count >>> 8);
213     in[limit] = (byte) count;
214     for (int i = 0; i < iterationCount; i++)
215       {
216         mac.reset();
217         mac.update(in, 0, in.length);
218         in = mac.digest();
219         for (int j = 0; j < buffer.length; j++)
220           {
221             buffer[j] ^= in[j];
222           }
223       }
224   }
225 }