PrivateCredentials.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. /* PrivateCredentials.java -- private key/certificate pairs.
  2. Copyright (C) 2006, 2007 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.net.ssl;
  32. import gnu.java.lang.CPStringBuilder;
  33. import java.io.EOFException;
  34. import java.io.InputStream;
  35. import java.io.IOException;
  36. import java.math.BigInteger;
  37. import java.security.InvalidKeyException;
  38. import java.security.KeyFactory;
  39. import java.security.NoSuchAlgorithmException;
  40. import java.security.PrivateKey;
  41. import java.security.Security;
  42. import java.security.cert.Certificate;
  43. import java.security.cert.CertificateException;
  44. import java.security.cert.CertificateFactory;
  45. import java.security.cert.X509Certificate;
  46. import java.security.spec.DSAPrivateKeySpec;
  47. import java.security.spec.InvalidKeySpecException;
  48. import java.security.spec.KeySpec;
  49. import java.security.spec.RSAPrivateCrtKeySpec;
  50. import java.util.Collection;
  51. import java.util.HashMap;
  52. import java.util.LinkedList;
  53. import java.util.List;
  54. import javax.net.ssl.ManagerFactoryParameters;
  55. import javax.security.auth.callback.Callback;
  56. import javax.security.auth.callback.CallbackHandler;
  57. import javax.security.auth.callback.PasswordCallback;
  58. import javax.security.auth.callback.UnsupportedCallbackException;
  59. import gnu.javax.security.auth.callback.ConsoleCallbackHandler;
  60. import gnu.java.security.hash.HashFactory;
  61. import gnu.java.security.hash.IMessageDigest;
  62. import gnu.javax.crypto.mode.IMode;
  63. import gnu.javax.crypto.mode.ModeFactory;
  64. import gnu.javax.crypto.pad.WrongPaddingException;
  65. import gnu.java.security.der.DER;
  66. import gnu.java.security.der.DERReader;
  67. import gnu.java.util.Base64;
  68. /**
  69. * An instance of a manager factory parameters for holding a single
  70. * certificate/private key pair, encoded in PEM format.
  71. */
  72. public class PrivateCredentials implements ManagerFactoryParameters
  73. {
  74. // Fields.
  75. // -------------------------------------------------------------------------
  76. public static final String BEGIN_DSA = "-----BEGIN DSA PRIVATE KEY";
  77. public static final String END_DSA = "-----END DSA PRIVATE KEY";
  78. public static final String BEGIN_RSA = "-----BEGIN RSA PRIVATE KEY";
  79. public static final String END_RSA = "-----END RSA PRIVATE KEY";
  80. private List<PrivateKey> privateKeys;
  81. private List<X509Certificate[]> certChains;
  82. // Constructor.
  83. // -------------------------------------------------------------------------
  84. public PrivateCredentials()
  85. {
  86. privateKeys = new LinkedList<PrivateKey>();
  87. certChains = new LinkedList<X509Certificate[]>();
  88. }
  89. // Instance methods.
  90. // -------------------------------------------------------------------------
  91. public void add(InputStream certChain, InputStream privateKey)
  92. throws CertificateException, InvalidKeyException, InvalidKeySpecException,
  93. IOException, NoSuchAlgorithmException, WrongPaddingException
  94. {
  95. CertificateFactory cf = CertificateFactory.getInstance("X.509");
  96. Collection<? extends Certificate> certs = cf.generateCertificates(certChain);
  97. X509Certificate[] chain = (X509Certificate[]) certs.toArray(new X509Certificate[0]);
  98. String alg = null;
  99. String line = readLine(privateKey);
  100. String finalLine = null;
  101. if (line.startsWith(BEGIN_DSA))
  102. {
  103. alg = "DSA";
  104. finalLine = END_DSA;
  105. }
  106. else if (line.startsWith(BEGIN_RSA))
  107. {
  108. alg = "RSA";
  109. finalLine = END_RSA;
  110. }
  111. else
  112. throw new IOException("Unknown private key type.");
  113. boolean encrypted = false;
  114. String cipher = null;
  115. String salt = null;
  116. CPStringBuilder base64 = new CPStringBuilder();
  117. while (true)
  118. {
  119. line = readLine(privateKey);
  120. if (line == null)
  121. throw new EOFException("premature end-of-file");
  122. else if (line.startsWith("Proc-Type: 4,ENCRYPTED"))
  123. encrypted = true;
  124. else if (line.startsWith("DEK-Info: "))
  125. {
  126. int i = line.indexOf(',');
  127. if (i < 0)
  128. cipher = line.substring(10).trim();
  129. else
  130. {
  131. cipher = line.substring(10, i).trim();
  132. salt = line.substring(i + 1).trim();
  133. }
  134. }
  135. else if (line.startsWith(finalLine))
  136. break;
  137. else if (line.length() > 0)
  138. {
  139. base64.append(line);
  140. base64.append(System.getProperty("line.separator"));
  141. }
  142. }
  143. byte[] enckey = Base64.decode(base64.toString());
  144. if (encrypted)
  145. {
  146. enckey = decryptKey(enckey, cipher, toByteArray(salt));
  147. }
  148. DERReader der = new DERReader(enckey);
  149. if (der.read().getTag() != DER.SEQUENCE)
  150. throw new IOException("malformed DER sequence");
  151. der.read(); // version
  152. KeyFactory kf = KeyFactory.getInstance(alg);
  153. KeySpec spec = null;
  154. if (alg.equals("DSA"))
  155. {
  156. BigInteger p = (BigInteger) der.read().getValue();
  157. BigInteger q = (BigInteger) der.read().getValue();
  158. BigInteger g = (BigInteger) der.read().getValue();
  159. der.read(); // y
  160. BigInteger x = (BigInteger) der.read().getValue();
  161. spec = new DSAPrivateKeySpec(x, p, q, g);
  162. }
  163. else
  164. {
  165. spec = new RSAPrivateCrtKeySpec(
  166. (BigInteger) der.read().getValue(), // modulus
  167. (BigInteger) der.read().getValue(), // pub exponent
  168. (BigInteger) der.read().getValue(), // priv expenent
  169. (BigInteger) der.read().getValue(), // prime p
  170. (BigInteger) der.read().getValue(), // prime q
  171. (BigInteger) der.read().getValue(), // d mod (p-1)
  172. (BigInteger) der.read().getValue(), // d mod (q-1)
  173. (BigInteger) der.read().getValue()); // coefficient
  174. }
  175. privateKeys.add(kf.generatePrivate(spec));
  176. certChains.add(chain);
  177. }
  178. public List<PrivateKey> getPrivateKeys()
  179. {
  180. if (isDestroyed())
  181. {
  182. throw new IllegalStateException("this object is destroyed");
  183. }
  184. return privateKeys;
  185. }
  186. public List<X509Certificate[]> getCertChains()
  187. {
  188. return certChains;
  189. }
  190. public void destroy()
  191. {
  192. privateKeys.clear();
  193. privateKeys = null;
  194. }
  195. public boolean isDestroyed()
  196. {
  197. return (privateKeys == null);
  198. }
  199. // Own methods.
  200. // -------------------------------------------------------------------------
  201. private String readLine(InputStream in) throws IOException
  202. {
  203. boolean eol_is_cr = System.getProperty("line.separator").equals("\r");
  204. CPStringBuilder str = new CPStringBuilder();
  205. while (true)
  206. {
  207. int i = in.read();
  208. if (i == -1)
  209. {
  210. if (str.length() > 0)
  211. break;
  212. else
  213. return null;
  214. }
  215. else if (i == '\r')
  216. {
  217. if (eol_is_cr)
  218. break;
  219. }
  220. else if (i == '\n')
  221. break;
  222. else
  223. str.append((char) i);
  224. }
  225. return str.toString();
  226. }
  227. private byte[] decryptKey(byte[] ct, String cipher, byte[] salt)
  228. throws IOException, InvalidKeyException, WrongPaddingException
  229. {
  230. byte[] pt = new byte[ct.length];
  231. IMode mode = null;
  232. if (cipher.equals("DES-EDE3-CBC"))
  233. {
  234. mode = ModeFactory.getInstance("CBC", "TripleDES", 8);
  235. HashMap attr = new HashMap();
  236. attr.put(IMode.KEY_MATERIAL, deriveKey(salt, 24));
  237. attr.put(IMode.IV, salt);
  238. attr.put(IMode.STATE, new Integer(IMode.DECRYPTION));
  239. mode.init(attr);
  240. }
  241. else if (cipher.equals("DES-CBC"))
  242. {
  243. mode = ModeFactory.getInstance("CBC", "DES", 8);
  244. HashMap attr = new HashMap();
  245. attr.put(IMode.KEY_MATERIAL, deriveKey(salt, 8));
  246. attr.put(IMode.IV, salt);
  247. attr.put(IMode.STATE, new Integer(IMode.DECRYPTION));
  248. mode.init(attr);
  249. }
  250. else
  251. throw new IllegalArgumentException("unknown cipher: " + cipher);
  252. for (int i = 0; i < ct.length; i += 8)
  253. mode.update(ct, i, pt, i);
  254. int pad = pt[pt.length-1];
  255. if (pad < 1 || pad > 8)
  256. throw new WrongPaddingException();
  257. for (int i = pt.length - pad; i < pt.length; i++)
  258. {
  259. if (pt[i] != pad)
  260. throw new WrongPaddingException();
  261. }
  262. byte[] result = new byte[pt.length - pad];
  263. System.arraycopy(pt, 0, result, 0, result.length);
  264. return result;
  265. }
  266. private byte[] deriveKey(byte[] salt, int keylen)
  267. throws IOException
  268. {
  269. CallbackHandler passwordHandler = new ConsoleCallbackHandler();
  270. try
  271. {
  272. Class c = Class.forName(Security.getProperty("jessie.password.handler"));
  273. passwordHandler = (CallbackHandler) c.newInstance();
  274. }
  275. catch (Exception x) { }
  276. PasswordCallback passwdCallback =
  277. new PasswordCallback("Enter PEM passphrase: ", false);
  278. try
  279. {
  280. passwordHandler.handle(new Callback[] { passwdCallback });
  281. }
  282. catch (UnsupportedCallbackException uce)
  283. {
  284. throw new IOException("specified handler cannot handle passwords");
  285. }
  286. char[] passwd = passwdCallback.getPassword();
  287. IMessageDigest md5 = HashFactory.getInstance("MD5");
  288. byte[] key = new byte[keylen];
  289. int count = 0;
  290. while (count < keylen)
  291. {
  292. for (int i = 0; i < passwd.length; i++)
  293. md5.update((byte) passwd[i]);
  294. md5.update(salt, 0, salt.length);
  295. byte[] digest = md5.digest();
  296. int len = Math.min(digest.length, keylen - count);
  297. System.arraycopy(digest, 0, key, count, len);
  298. count += len;
  299. if (count >= keylen)
  300. break;
  301. md5.reset();
  302. md5.update(digest, 0, digest.length);
  303. }
  304. passwdCallback.clearPassword();
  305. return key;
  306. }
  307. private byte[] toByteArray(String hex)
  308. {
  309. hex = hex.toLowerCase();
  310. byte[] buf = new byte[hex.length() / 2];
  311. int j = 0;
  312. for (int i = 0; i < buf.length; i++)
  313. {
  314. buf[i] = (byte) ((Character.digit(hex.charAt(j++), 16) << 4) |
  315. Character.digit(hex.charAt(j++), 16));
  316. }
  317. return buf;
  318. }
  319. }