Export Private Key from a keystore


/ Published in: Java
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /**
  2. * A Base64 encoder/decoder.
  3. *
  4. * <p>
  5. * This class is used to encode and decode data in Base64 format as described in RFC 1521.
  6. *
  7. * <p>
  8. * Project home page: <a href="http://www.source-code.biz/base64coder/java/">www.source-code.biz/base64coder/java</a><br>
  9. * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
  10. * Multi-licensed: EPL / LGPL / GPL / AL / BSD.
  11. */
  12. public class Base64Coder {
  13.  
  14. // The line separator string of the operating system.
  15. private static final String systemLineSeparator = System.getProperty("line.separator");
  16.  
  17. // Mapping table from 6-bit nibbles to Base64 characters.
  18. private static char[] map1 = new char[64];
  19. static {
  20. int i=0;
  21. for (char c='A'; c<='Z'; c++) map1[i++] = c;
  22. for (char c='a'; c<='z'; c++) map1[i++] = c;
  23. for (char c='0'; c<='9'; c++) map1[i++] = c;
  24. map1[i++] = '+'; map1[i++] = '/'; }
  25.  
  26. // Mapping table from Base64 characters to 6-bit nibbles.
  27. private static byte[] map2 = new byte[128];
  28. static {
  29. for (int i=0; i<map2.length; i++) map2[i] = -1;
  30. for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; }
  31.  
  32. /**
  33. * Encodes a string into Base64 format.
  34. * No blanks or line breaks are inserted.
  35. * @param s A String to be encoded.
  36. * @return A String containing the Base64 encoded data.
  37. */
  38. public static String encodeString (String s) {
  39. return new String(encode(s.getBytes())); }
  40.  
  41. /**
  42. * Encodes a byte array into Base 64 format and breaks the output into lines of 76 characters.
  43. * This method is compatible with <code>sun.misc.BASE64Encoder.encodeBuffer(byte[])</code>.
  44. * @param in An array containing the data bytes to be encoded.
  45. * @return A String containing the Base64 encoded data, broken into lines.
  46. */
  47. public static String encodeLines (byte[] in) {
  48. return encodeLines(in, 0, in.length, 76, systemLineSeparator); }
  49.  
  50. /**
  51. * Encodes a byte array into Base 64 format and breaks the output into lines.
  52. * @param in An array containing the data bytes to be encoded.
  53. * @param iOff Offset of the first byte in <code>in</code> to be processed.
  54. * @param iLen Number of bytes to be processed in <code>in</code>, starting at <code>iOff</code>.
  55. * @param lineLen Line length for the output data. Should be a multiple of 4.
  56. * @param lineSeparator The line separator to be used to separate the output lines.
  57. * @return A String containing the Base64 encoded data, broken into lines.
  58. */
  59. public static String encodeLines (byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) {
  60. int blockLen = (lineLen*3) / 4;
  61. if (blockLen <= 0) throw new IllegalArgumentException();
  62. int lines = (iLen+blockLen-1) / blockLen;
  63. int bufLen = ((iLen+2)/3)*4 + lines*lineSeparator.length();
  64. StringBuilder buf = new StringBuilder(bufLen);
  65. int ip = 0;
  66. while (ip < iLen) {
  67. int l = Math.min(iLen-ip, blockLen);
  68. buf.append (encode(in, iOff+ip, l));
  69. buf.append (lineSeparator);
  70. ip += l; }
  71. return buf.toString(); }
  72.  
  73. /**
  74. * Encodes a byte array into Base64 format.
  75. * No blanks or line breaks are inserted in the output.
  76. * @param in An array containing the data bytes to be encoded.
  77. * @return A character array containing the Base64 encoded data.
  78. */
  79. public static char[] encode (byte[] in) {
  80. return encode(in, 0, in.length); }
  81.  
  82. /**
  83. * Encodes a byte array into Base64 format.
  84. * No blanks or line breaks are inserted in the output.
  85. * @param in An array containing the data bytes to be encoded.
  86. * @param iLen Number of bytes to process in <code>in</code>.
  87. * @return A character array containing the Base64 encoded data.
  88. */
  89. public static char[] encode (byte[] in, int iLen) {
  90. return encode(in, 0, iLen); }
  91.  
  92. /**
  93. * Encodes a byte array into Base64 format.
  94. * No blanks or line breaks are inserted in the output.
  95. * @param in An array containing the data bytes to be encoded.
  96. * @param iOff Offset of the first byte in <code>in</code> to be processed.
  97. * @param iLen Number of bytes to process in <code>in</code>, starting at <code>iOff</code>.
  98. * @return A character array containing the Base64 encoded data.
  99. */
  100. public static char[] encode (byte[] in, int iOff, int iLen) {
  101. int oDataLen = (iLen*4+2)/3; // output length without padding
  102. int oLen = ((iLen+2)/3)*4; // output length including padding
  103. char[] out = new char[oLen];
  104. int ip = iOff;
  105. int iEnd = iOff + iLen;
  106. int op = 0;
  107. while (ip < iEnd) {
  108. int i0 = in[ip++] & 0xff;
  109. int i1 = ip < iEnd ? in[ip++] & 0xff : 0;
  110. int i2 = ip < iEnd ? in[ip++] & 0xff : 0;
  111. int o0 = i0 >>> 2;
  112. int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
  113. int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
  114. int o3 = i2 & 0x3F;
  115. out[op++] = map1[o0];
  116. out[op++] = map1[o1];
  117. out[op] = op < oDataLen ? map1[o2] : '='; op++;
  118. out[op] = op < oDataLen ? map1[o3] : '='; op++; }
  119. return out; }
  120.  
  121. /**
  122. * Decodes a string from Base64 format.
  123. * No blanks or line breaks are allowed within the Base64 encoded input data.
  124. * @param s A Base64 String to be decoded.
  125. * @return A String containing the decoded data.
  126. * @throws IllegalArgumentException If the input is not valid Base64 encoded data.
  127. */
  128. public static String decodeString (String s) {
  129. return new String(decode(s)); }
  130.  
  131. /**
  132. * Decodes a byte array from Base64 format and ignores line separators, tabs and blanks.
  133. * CR, LF, Tab and Space characters are ignored in the input data.
  134. * This method is compatible with <code>sun.misc.BASE64Decoder.decodeBuffer(String)</code>.
  135. * @param s A Base64 String to be decoded.
  136. * @return An array containing the decoded data bytes.
  137. * @throws IllegalArgumentException If the input is not valid Base64 encoded data.
  138. */
  139. public static byte[] decodeLines (String s) {
  140. char[] buf = new char[s.length()];
  141. int p = 0;
  142. for (int ip = 0; ip < s.length(); ip++) {
  143. char c = s.charAt(ip);
  144. if (c != ' ' && c != '\r' && c != '\n' && c != '\t')
  145. buf[p++] = c; }
  146. return decode(buf, 0, p); }
  147.  
  148. /**
  149. * Decodes a byte array from Base64 format.
  150. * No blanks or line breaks are allowed within the Base64 encoded input data.
  151. * @param s A Base64 String to be decoded.
  152. * @return An array containing the decoded data bytes.
  153. * @throws IllegalArgumentException If the input is not valid Base64 encoded data.
  154. */
  155. public static byte[] decode (String s) {
  156. return decode(s.toCharArray()); }
  157.  
  158. /**
  159. * Decodes a byte array from Base64 format.
  160. * No blanks or line breaks are allowed within the Base64 encoded input data.
  161. * @param in A character array containing the Base64 encoded data.
  162. * @return An array containing the decoded data bytes.
  163. * @throws IllegalArgumentException If the input is not valid Base64 encoded data.
  164. */
  165. public static byte[] decode (char[] in) {
  166. return decode(in, 0, in.length); }
  167.  
  168. /**
  169. * Decodes a byte array from Base64 format.
  170. * No blanks or line breaks are allowed within the Base64 encoded input data.
  171. * @param in A character array containing the Base64 encoded data.
  172. * @param iOff Offset of the first character in <code>in</code> to be processed.
  173. * @param iLen Number of characters to process in <code>in</code>, starting at <code>iOff</code>.
  174. * @return An array containing the decoded data bytes.
  175. * @throws IllegalArgumentException If the input is not valid Base64 encoded data.
  176. */
  177. public static byte[] decode (char[] in, int iOff, int iLen) {
  178. if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4.");
  179. while (iLen > 0 && in[iOff+iLen-1] == '=') iLen--;
  180. int oLen = (iLen*3) / 4;
  181. byte[] out = new byte[oLen];
  182. int ip = iOff;
  183. int iEnd = iOff + iLen;
  184. int op = 0;
  185. while (ip < iEnd) {
  186. int i0 = in[ip++];
  187. int i1 = in[ip++];
  188. int i2 = ip < iEnd ? in[ip++] : 'A';
  189. int i3 = ip < iEnd ? in[ip++] : 'A';
  190. if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
  191. throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
  192. int b0 = map2[i0];
  193. int b1 = map2[i1];
  194. int b2 = map2[i2];
  195. int b3 = map2[i3];
  196. if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
  197. throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
  198. int o0 = ( b0 <<2) | (b1>>>4);
  199. int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
  200. int o2 = ((b2 & 3)<<6) | b3;
  201. out[op++] = (byte)o0;
  202. if (op<oLen) out[op++] = (byte)o1;
  203. if (op<oLen) out[op++] = (byte)o2; }
  204. return out; }
  205.  
  206. // Dummy constructor.
  207. private Base64Coder() {}
  208.  
  209. } // end class Base64Coder
  210.  
  211.  
  212.  
  213. // How to export the private key from keystore?
  214. // Does keytool not have an option to do so?
  215. // This example use the "testkeys" file that comes with JSSE 1.0.3
  216. // Alexey Zilber: Ported to work with Base64Coder: http://www.source-code.biz/snippets/java/2.htm
  217.  
  218. import java.security.cert.Certificate;
  219. import java.security.*;
  220. import java.io.File;
  221. import java.io.FileInputStream;
  222.  
  223. class ExportPriv {
  224. public static void main(String args[]) throws Exception {
  225. if (args.length != 4) {
  226. // Yes I know this sucks (the password is visible to other users via
  227. // ps
  228. // but this was a quick-n-dirty fix to export from a keystore to
  229. // pkcs12
  230. // someday I may fix, but for now it'll have to do.
  231. System.err
  232. .println("Usage: java ExportPriv <keystore> <alias> <store-password> <key-password>");
  233. System.exit(1);
  234. }
  235. ExportPriv myep = new ExportPriv();
  236. myep.doit(args[0], args[1], args[2], args[3]);
  237. }
  238.  
  239. public void doit(String fileName, String aliasName, String storepassword,
  240. String keyPassword) throws Exception {
  241.  
  242. KeyStore ks = KeyStore.getInstance("JKS");
  243.  
  244. char[] storePwdPhrase = storepassword.toCharArray();
  245. char[] keyPasswordPhrase = keyPassword.toCharArray();
  246. // BASE64Encoder myB64 = new BASE64Encoder();
  247.  
  248. File certificateFile = new File(fileName);
  249. ks.load(new FileInputStream(certificateFile), storePwdPhrase);
  250.  
  251. KeyPair kp = getPrivateKey(ks, aliasName, keyPasswordPhrase);
  252.  
  253. PrivateKey privKey = kp.getPrivate();
  254.  
  255. char[] b64 = Base64Coder.encode(privKey.getEncoded());
  256.  
  257. System.out.println("-----BEGIN PRIVATE KEY-----");
  258. System.out.println(b64);
  259. System.out.println("-----END PRIVATE KEY-----");
  260.  
  261. }
  262.  
  263. // From http://javaalmanac.com/egs/java.security/GetKeyFromKs.html
  264.  
  265. public KeyPair getPrivateKey(KeyStore keystore, String alias,
  266. char[] password) {
  267. try {
  268. // Get private key
  269. Key key = keystore.getKey(alias, password);
  270. if (key instanceof PrivateKey) {
  271. // Get certificate of public key
  272. Certificate cert = keystore.getCertificate(alias);
  273.  
  274. // Get public key
  275. PublicKey publicKey = cert.getPublicKey();
  276.  
  277. // Return a key pair
  278. return new KeyPair(publicKey, (PrivateKey) key);
  279. }
  280. } catch (KeyStoreException e) {
  281. }
  282. return null;
  283. }
  284.  
  285. }
  286.  
  287.  
  288. ExportPriv <keystore> <alias> <store-password> <key-password>

URL: http://conshell.net/wiki/index.php/Keytool_to_OpenSSL_Conversion_tips

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.