PasswordEncryptedEntry.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /* PasswordEncryptedEntry.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.cipher.CipherFactory;
  39. import gnu.javax.crypto.cipher.IBlockCipher;
  40. import gnu.javax.crypto.mode.IMode;
  41. import gnu.javax.crypto.mode.ModeFactory;
  42. import gnu.javax.crypto.pad.IPad;
  43. import gnu.javax.crypto.pad.PadFactory;
  44. import gnu.javax.crypto.pad.WrongPaddingException;
  45. import gnu.javax.crypto.prng.IPBE;
  46. import gnu.javax.crypto.prng.PRNGFactory;
  47. import java.io.ByteArrayInputStream;
  48. import java.io.ByteArrayOutputStream;
  49. import java.io.DataInputStream;
  50. import java.io.DataOutputStream;
  51. import java.io.IOException;
  52. import java.security.InvalidKeyException;
  53. import java.util.HashMap;
  54. import java.util.Iterator;
  55. import java.util.logging.Logger;
  56. /**
  57. * An envelope that is encrypted with a password-derived key.
  58. */
  59. public class PasswordEncryptedEntry
  60. extends MaskableEnvelopeEntry
  61. implements PasswordProtectedEntry, Registry
  62. {
  63. private static final Logger log = Logger.getLogger(PasswordEncryptedEntry.class.getName());
  64. public static final int TYPE = 1;
  65. public PasswordEncryptedEntry(String cipher, String mode, int keylen,
  66. Properties properties)
  67. {
  68. super(TYPE, properties);
  69. if ((cipher == null || cipher.length() == 0)
  70. || (mode == null || mode.length() == 0))
  71. throw new IllegalArgumentException("cipher nor mode can be empty");
  72. this.properties.put("cipher", cipher);
  73. this.properties.put("mode", mode);
  74. this.properties.put("keylen", String.valueOf(keylen));
  75. setMasked(false);
  76. }
  77. private PasswordEncryptedEntry()
  78. {
  79. super(TYPE);
  80. setMasked(true);
  81. }
  82. public static PasswordEncryptedEntry decode(DataInputStream in,
  83. char[] password)
  84. throws IOException
  85. {
  86. PasswordEncryptedEntry entry = decode(in);
  87. try
  88. {
  89. entry.decrypt(password);
  90. }
  91. catch (WrongPaddingException wpe)
  92. {
  93. throw new MalformedKeyringException("wrong padding in decrypted data");
  94. }
  95. return entry;
  96. }
  97. public static PasswordEncryptedEntry decode(DataInputStream in)
  98. throws IOException
  99. {
  100. PasswordEncryptedEntry entry = new PasswordEncryptedEntry();
  101. entry.defaultDecode(in);
  102. return entry;
  103. }
  104. public void decrypt(char[] password) throws IllegalArgumentException,
  105. WrongPaddingException
  106. {
  107. if (Configuration.DEBUG)
  108. log.entering(this.getClass().getName(), "decrypt");
  109. if (isMasked() && payload != null)
  110. {
  111. long tt = -System.currentTimeMillis();
  112. IMode mode = getMode(password, IMode.DECRYPTION);
  113. IPad padding = PadFactory.getInstance("PKCS7");
  114. padding.init(mode.currentBlockSize());
  115. byte[] buf = new byte[payload.length];
  116. int count = 0;
  117. while (count + mode.currentBlockSize() <= payload.length)
  118. {
  119. mode.update(payload, count, buf, count);
  120. count += mode.currentBlockSize();
  121. }
  122. int padlen = padding.unpad(buf, 0, buf.length);
  123. setMasked(false);
  124. int len = buf.length - padlen;
  125. ByteArrayInputStream baos = new ByteArrayInputStream(buf, 0, len);
  126. DataInputStream in = new DataInputStream(baos);
  127. try
  128. {
  129. decodeEnvelope(in);
  130. }
  131. catch (IOException ioe)
  132. {
  133. throw new IllegalArgumentException("decryption failed");
  134. }
  135. tt += System.currentTimeMillis();
  136. log.fine("Decrypted in " + tt + "ms.");
  137. }
  138. else if (Configuration.DEBUG)
  139. log.fine("Skip decryption; " + (isMasked() ? "null payload" : "unmasked"));
  140. if (Configuration.DEBUG)
  141. log.exiting(this.getClass().getName(), "decrypt");
  142. }
  143. public void encrypt(char[] password) throws IOException
  144. {
  145. if (Configuration.DEBUG)
  146. log.entering(this.getClass().getName(), "encrypt", String.valueOf(password));
  147. long tt = -System.currentTimeMillis();
  148. long t1 = -System.currentTimeMillis();
  149. byte[] salt = new byte[8];
  150. PRNG.getInstance().nextBytes(salt);
  151. t1 += System.currentTimeMillis();
  152. if (Configuration.DEBUG)
  153. log.fine("-- Generated salt in " + t1 + "ms.");
  154. properties.put("salt", Util.toString(salt));
  155. IMode mode = getMode(password, IMode.ENCRYPTION);
  156. IPad pad = PadFactory.getInstance("PKCS7");
  157. pad.init(mode.currentBlockSize());
  158. ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
  159. DataOutputStream out2 = new DataOutputStream(bout);
  160. for (Iterator it = entries.iterator(); it.hasNext();)
  161. {
  162. Entry entry = (Entry) it.next();
  163. if (Configuration.DEBUG)
  164. log.fine("-- About to encode one " + entry);
  165. t1 = -System.currentTimeMillis();
  166. entry.encode(out2);
  167. t1 += System.currentTimeMillis();
  168. if (Configuration.DEBUG)
  169. log.fine("-- Encoded an Entry in " + t1 + "ms.");
  170. }
  171. byte[] plaintext = bout.toByteArray();
  172. byte[] padding = pad.pad(plaintext, 0, plaintext.length);
  173. payload = new byte[plaintext.length + padding.length];
  174. byte[] lastBlock = new byte[mode.currentBlockSize()];
  175. int l = mode.currentBlockSize() - padding.length;
  176. System.arraycopy(plaintext, plaintext.length - l, lastBlock, 0, l);
  177. System.arraycopy(padding, 0, lastBlock, l, padding.length);
  178. int count = 0;
  179. while (count + mode.currentBlockSize() < plaintext.length)
  180. {
  181. mode.update(plaintext, count, payload, count);
  182. count += mode.currentBlockSize();
  183. }
  184. mode.update(lastBlock, 0, payload, count);
  185. setMasked(true);
  186. tt += System.currentTimeMillis();
  187. if (Configuration.DEBUG)
  188. {
  189. log.fine("Encrypted in " + tt + "ms.");
  190. log.exiting(this.getClass().getName(), "encrypt");
  191. }
  192. }
  193. public void encode(DataOutputStream out, char[] password) throws IOException
  194. {
  195. encrypt(password);
  196. encode(out);
  197. }
  198. protected void encodePayload() throws IOException
  199. {
  200. if (payload == null)
  201. {
  202. if (Configuration.DEBUG)
  203. log.fine("Null payload: " + this);
  204. throw new IllegalStateException("not encrypted");
  205. }
  206. }
  207. private IMode getMode(char[] password, int state)
  208. {
  209. String s = properties.get("salt");
  210. if (s == null)
  211. throw new IllegalArgumentException("no salt");
  212. byte[] salt = Util.toBytesFromString(s);
  213. IBlockCipher cipher = CipherFactory.getInstance(properties.get("cipher"));
  214. if (cipher == null)
  215. throw new IllegalArgumentException("no such cipher: "
  216. + properties.get("cipher"));
  217. int blockSize = cipher.defaultBlockSize();
  218. if (properties.containsKey("block-size"))
  219. try
  220. {
  221. blockSize = Integer.parseInt(properties.get("block-size"));
  222. }
  223. catch (NumberFormatException nfe)
  224. {
  225. throw new IllegalArgumentException("bad block size: "
  226. + nfe.getMessage());
  227. }
  228. String modeName = properties.get("mode");
  229. IMode mode = ModeFactory.getInstance(modeName, cipher, blockSize);
  230. if (mode == null)
  231. throw new IllegalArgumentException("no such mode: " + modeName);
  232. HashMap pbAttr = new HashMap();
  233. pbAttr.put(IPBE.PASSWORD, password);
  234. pbAttr.put(IPBE.SALT, salt);
  235. pbAttr.put(IPBE.ITERATION_COUNT, ITERATION_COUNT);
  236. IRandom kdf = PRNGFactory.getInstance("PBKDF2-HMAC-SHA");
  237. kdf.init(pbAttr);
  238. int keylen = 0;
  239. if (! properties.containsKey("keylen"))
  240. throw new IllegalArgumentException("no key length");
  241. try
  242. {
  243. keylen = Integer.parseInt(properties.get("keylen"));
  244. }
  245. catch (NumberFormatException nfe)
  246. {
  247. }
  248. byte[] dk = new byte[keylen];
  249. byte[] iv = new byte[blockSize];
  250. try
  251. {
  252. kdf.nextBytes(dk, 0, keylen);
  253. kdf.nextBytes(iv, 0, blockSize);
  254. }
  255. catch (LimitReachedException shouldNotHappen)
  256. {
  257. throw new Error(shouldNotHappen.toString());
  258. }
  259. HashMap modeAttr = new HashMap();
  260. modeAttr.put(IMode.KEY_MATERIAL, dk);
  261. modeAttr.put(IMode.STATE, Integer.valueOf(state));
  262. modeAttr.put(IMode.IV, iv);
  263. try
  264. {
  265. mode.init(modeAttr);
  266. }
  267. catch (InvalidKeyException ike)
  268. {
  269. throw new IllegalArgumentException(ike.toString());
  270. }
  271. return mode;
  272. }
  273. }