PasswordAuthenticatedEntry.java 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /* PasswordAuthenticatedEntry.java --
  2. Copyright (C) 2003, 2006 Free Software Foundation, Inc.
  3. This file is a part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or (at
  7. your option) any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; if not, write to the Free Software
  14. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
  15. USA
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package gnu.javax.crypto.keyring;
  32. import gnu.java.security.Configuration;
  33. import gnu.java.security.Registry;
  34. import gnu.java.security.prng.IRandom;
  35. import gnu.java.security.prng.LimitReachedException;
  36. import gnu.java.security.util.PRNG;
  37. import gnu.java.security.util.Util;
  38. import gnu.javax.crypto.mac.IMac;
  39. import gnu.javax.crypto.mac.MacFactory;
  40. import gnu.javax.crypto.mac.MacInputStream;
  41. import gnu.javax.crypto.mac.MacOutputStream;
  42. import gnu.javax.crypto.prng.IPBE;
  43. import gnu.javax.crypto.prng.PRNGFactory;
  44. import java.io.ByteArrayInputStream;
  45. import java.io.ByteArrayOutputStream;
  46. import java.io.DataInputStream;
  47. import java.io.DataOutputStream;
  48. import java.io.IOException;
  49. import java.security.InvalidKeyException;
  50. import java.util.Arrays;
  51. import java.util.HashMap;
  52. import java.util.Iterator;
  53. import java.util.logging.Logger;
  54. /**
  55. * An entry authenticated with a password-based MAC.
  56. */
  57. public final class PasswordAuthenticatedEntry
  58. extends MaskableEnvelopeEntry
  59. implements PasswordProtectedEntry, Registry
  60. {
  61. private static final Logger log = Logger.getLogger(PasswordAuthenticatedEntry.class.getName());
  62. public static final int TYPE = 3;
  63. public PasswordAuthenticatedEntry(String mac, int maclen,
  64. Properties properties)
  65. {
  66. super(TYPE, properties);
  67. if (mac == null || mac.length() == 0)
  68. throw new IllegalArgumentException("no MAC specified");
  69. this.properties.put("mac", mac);
  70. this.properties.put("maclen", String.valueOf(maclen));
  71. setMasked(false);
  72. }
  73. private PasswordAuthenticatedEntry()
  74. {
  75. super(TYPE);
  76. setMasked(true);
  77. }
  78. public static PasswordAuthenticatedEntry decode(DataInputStream in,
  79. char[] password)
  80. throws IOException
  81. {
  82. PasswordAuthenticatedEntry entry = new PasswordAuthenticatedEntry();
  83. entry.properties.decode(in);
  84. IMac mac = entry.getMac(password);
  85. int len = in.readInt() - mac.macSize();
  86. MeteredInputStream min = new MeteredInputStream(in, len);
  87. MacInputStream macin = new MacInputStream(min, mac);
  88. DataInputStream in2 = new DataInputStream(macin);
  89. entry.setMasked(false);
  90. entry.decodeEnvelope(in2);
  91. byte[] macValue = new byte[mac.macSize()];
  92. in.readFully(macValue);
  93. if (! Arrays.equals(macValue, mac.digest()))
  94. throw new MalformedKeyringException("MAC verification failed");
  95. return entry;
  96. }
  97. public static PasswordAuthenticatedEntry decode(DataInputStream in)
  98. throws IOException
  99. {
  100. PasswordAuthenticatedEntry entry = new PasswordAuthenticatedEntry();
  101. entry.defaultDecode(in);
  102. if (! entry.properties.containsKey("mac"))
  103. throw new MalformedKeyringException("no MAC");
  104. if (! entry.properties.containsKey("maclen"))
  105. throw new MalformedKeyringException("no MAC length");
  106. if (! entry.properties.containsKey("salt"))
  107. throw new MalformedKeyringException("no salt");
  108. return entry;
  109. }
  110. public void verify(char[] password)
  111. {
  112. if (Configuration.DEBUG)
  113. log.entering(this.getClass().getName(), "verify");
  114. if (isMasked() && payload != null)
  115. {
  116. if (Configuration.DEBUG)
  117. log.fine("payload to verify: " + Util.dumpString(payload));
  118. long tt = -System.currentTimeMillis();
  119. IMac m = null;
  120. try
  121. {
  122. m = getMac(password);
  123. }
  124. catch (Exception x)
  125. {
  126. throw new IllegalArgumentException(x.toString(), x);
  127. }
  128. int limit = payload.length - m.macSize();
  129. m.update(payload, 0, limit);
  130. byte[] macValue = new byte[m.macSize()];
  131. System.arraycopy(payload, payload.length - macValue.length, macValue,
  132. 0, macValue.length);
  133. if (! Arrays.equals(macValue, m.digest()))
  134. throw new IllegalArgumentException("MAC verification failed");
  135. setMasked(false);
  136. ByteArrayInputStream bais;
  137. try
  138. {
  139. bais = new ByteArrayInputStream(payload, 0, limit);
  140. DataInputStream in = new DataInputStream(bais);
  141. decodeEnvelope(in);
  142. }
  143. catch (IOException ioe)
  144. {
  145. throw new IllegalArgumentException("malformed keyring fragment");
  146. }
  147. tt += System.currentTimeMillis();
  148. if (Configuration.DEBUG)
  149. log.fine("Verified in " + tt + "ms.");
  150. }
  151. else if (Configuration.DEBUG)
  152. log.fine("Skip verification; "
  153. + (isMasked() ? "null payload" : "unmasked"));
  154. if (Configuration.DEBUG)
  155. log.exiting(this.getClass().getName(), "verify");
  156. }
  157. public void authenticate(char[] password) throws IOException
  158. {
  159. if (Configuration.DEBUG)
  160. log.entering(this.getClass().getName(), "authenticate");
  161. long tt = -System.currentTimeMillis();
  162. long t1 = -System.currentTimeMillis();
  163. if (isMasked())
  164. throw new IllegalStateException("entry is masked");
  165. byte[] salt = new byte[8];
  166. PRNG.getInstance().nextBytes(salt);
  167. t1 += System.currentTimeMillis();
  168. if (Configuration.DEBUG)
  169. log.fine("-- Generated salt in " + t1 + "ms.");
  170. properties.put("salt", Util.toString(salt));
  171. IMac m = getMac(password);
  172. ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
  173. MacOutputStream macout = new MacOutputStream(bout, m);
  174. DataOutputStream out2 = new DataOutputStream(macout);
  175. for (Iterator it = entries.iterator(); it.hasNext();)
  176. {
  177. Entry entry = (Entry) it.next();
  178. if (Configuration.DEBUG)
  179. log.fine("-- About to authenticate one " + entry);
  180. t1 = -System.currentTimeMillis();
  181. entry.encode(out2);
  182. t1 += System.currentTimeMillis();
  183. if (Configuration.DEBUG)
  184. log.fine("-- Authenticated an Entry in " + t1 + "ms.");
  185. }
  186. bout.write(m.digest());
  187. payload = bout.toByteArray();
  188. if (Configuration.DEBUG)
  189. log.fine("authenticated payload: " + Util.dumpString(payload));
  190. setMasked(true);
  191. tt += System.currentTimeMillis();
  192. if (Configuration.DEBUG)
  193. {
  194. log.fine("Authenticated in " + tt + "ms.");
  195. log.exiting(this.getClass().getName(), "authenticate");
  196. }
  197. }
  198. public void encode(DataOutputStream out, char[] password) throws IOException
  199. {
  200. authenticate(password);
  201. encode(out);
  202. }
  203. protected void encodePayload(DataOutputStream out) throws IOException
  204. {
  205. if (payload == null)
  206. {
  207. log.fine("Null payload: " + this);
  208. throw new IllegalStateException("mac not computed");
  209. }
  210. }
  211. private IMac getMac(char[] password) throws MalformedKeyringException
  212. {
  213. if (Configuration.DEBUG)
  214. log.entering(this.getClass().getName(), "getMac");
  215. String saltString = properties.get("salt");
  216. if (saltString == null)
  217. throw new MalformedKeyringException("no salt");
  218. byte[] salt = Util.toBytesFromString(saltString);
  219. String macAlgorithm = properties.get("mac");
  220. IMac mac = MacFactory.getInstance(macAlgorithm);
  221. if (mac == null)
  222. throw new MalformedKeyringException("no such mac: " + macAlgorithm);
  223. String macLenString = properties.get("maclen");
  224. if (macLenString == null)
  225. throw new MalformedKeyringException("no MAC length");
  226. int maclen;
  227. try
  228. {
  229. maclen = Integer.parseInt(macLenString);
  230. }
  231. catch (NumberFormatException nfe)
  232. {
  233. throw new MalformedKeyringException("bad MAC length");
  234. }
  235. HashMap pbAttr = new HashMap();
  236. pbAttr.put(IPBE.PASSWORD, password);
  237. pbAttr.put(IPBE.SALT, salt);
  238. pbAttr.put(IPBE.ITERATION_COUNT, ITERATION_COUNT);
  239. IRandom kdf = PRNGFactory.getInstance("PBKDF2-HMAC-SHA");
  240. kdf.init(pbAttr);
  241. int keylen = mac.macSize();
  242. byte[] dk = new byte[keylen];
  243. try
  244. {
  245. kdf.nextBytes(dk, 0, keylen);
  246. }
  247. catch (LimitReachedException shouldNotHappen)
  248. {
  249. throw new Error(shouldNotHappen.toString());
  250. }
  251. HashMap macAttr = new HashMap();
  252. macAttr.put(IMac.MAC_KEY_MATERIAL, dk);
  253. macAttr.put(IMac.TRUNCATED_SIZE, Integer.valueOf(maclen));
  254. try
  255. {
  256. mac.init(macAttr);
  257. }
  258. catch (InvalidKeyException shouldNotHappen)
  259. {
  260. throw new Error(shouldNotHappen.toString());
  261. }
  262. if (Configuration.DEBUG)
  263. log.exiting(this.getClass().getName(), "getMac");
  264. return mac;
  265. }
  266. }