DumpPublicKey.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /*
  2. * Compilation Instruction:
  3. * javac -cp bcprov-jdk15on-152.jar DumpPublicKey.java
  4. *
  5. * Run Instruction:
  6. * java -cp bcprov-jdk15on-152.jar:. DumpPublicKey PubKey.pem > source.c
  7. * java -cp bcprov-jdk15on-152.jar:. DumpPublicKey PubKey.pem OutKey.bin
  8. *
  9. */
  10. /*
  11. * Copyright (C) 2008 The Android Open Source Project
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License");
  14. * you may not use this file except in compliance with the License.
  15. * You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS,
  21. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. * See the License for the specific language governing permissions and
  23. * limitations under the License.
  24. */
  25. //package com.android.dumpkey;
  26. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  27. import java.io.FileInputStream;
  28. import java.math.BigInteger;
  29. import java.security.cert.CertificateFactory;
  30. import java.security.cert.X509Certificate;
  31. import java.security.KeyStore;
  32. import java.security.Key;
  33. import java.security.PublicKey;
  34. import java.security.Security;
  35. import java.security.interfaces.ECPublicKey;
  36. import java.security.interfaces.RSAPublicKey;
  37. import java.security.spec.ECPoint;
  38. import java.io.FileNotFoundException;
  39. import java.io.IOException;
  40. import java.security.KeyFactory;
  41. import java.security.NoSuchAlgorithmException;
  42. import java.security.NoSuchProviderException;
  43. import java.security.PrivateKey;
  44. import java.security.spec.InvalidKeySpecException;
  45. import java.security.spec.PKCS8EncodedKeySpec;
  46. import java.security.spec.X509EncodedKeySpec;
  47. import java.io.InputStreamReader;
  48. import org.bouncycastle.util.io.pem.PemObject;
  49. import org.bouncycastle.util.io.pem.PemReader;
  50. import java.io.FileOutputStream;
  51. import java.nio.ByteBuffer;
  52. import java.nio.ByteOrder;
  53. import java.nio.channels.FileChannel;
  54. class PemFile {
  55. private PemObject pemObject;
  56. public PemFile(String filename) throws FileNotFoundException, IOException {
  57. PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream(filename)));
  58. try {
  59. this.pemObject = pemReader.readPemObject();
  60. } finally {
  61. pemReader.close();
  62. }
  63. }
  64. public PemObject getPemObject() {
  65. return pemObject;
  66. }
  67. }
  68. class PemKey {
  69. protected KeyFactory factory;
  70. public PemKey() throws NoSuchAlgorithmException {
  71. factory = KeyFactory.getInstance("RSA");
  72. }
  73. public PrivateKey generatePrivateKey(String filename) throws InvalidKeySpecException, FileNotFoundException, IOException{
  74. PemFile pemFile = new PemFile(filename);
  75. byte[] content = pemFile.getPemObject().getContent();
  76. PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
  77. return factory.generatePrivate(privKeySpec);
  78. }
  79. public PublicKey generatePublicKey(String filename) throws InvalidKeySpecException, FileNotFoundException, IOException {
  80. PemFile pemFile = new PemFile(filename);
  81. byte[] content = pemFile.getPemObject().getContent();
  82. X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
  83. return factory.generatePublic(pubKeySpec);
  84. }
  85. }
  86. /**
  87. * Command line tool to extract RSA public keys from X.509 certificates
  88. * and output source code with data initializers for the keys.
  89. * @hide
  90. */
  91. class DumpPublicKey {
  92. /**
  93. * @param key to perform sanity checks on
  94. * @return version number of key. Supported versions are:
  95. * 1: 2048-bit RSA key with e=3 and SHA-1 hash
  96. * 2: 2048-bit RSA key with e=65537 and SHA-1 hash
  97. * 3: 2048-bit RSA key with e=3 and SHA-256 hash
  98. * 4: 2048-bit RSA key with e=65537 and SHA-256 hash
  99. * @throws Exception if the key has the wrong size or public exponent
  100. */
  101. static int checkRSA(RSAPublicKey key, boolean useSHA256) throws Exception {
  102. BigInteger pubexp = key.getPublicExponent();
  103. BigInteger modulus = key.getModulus();
  104. int version;
  105. if (pubexp.equals(BigInteger.valueOf(65537))) {
  106. version = useSHA256 ? 4 : 2;
  107. } else {
  108. throw new Exception("Public exponent should be 65537 but is " +
  109. pubexp.toString(10) + ".");
  110. }
  111. if (modulus.bitLength() != 2048) {
  112. throw new Exception("Modulus should be 2048 bits long but is " +
  113. modulus.bitLength() + " bits.");
  114. }
  115. return version;
  116. }
  117. /**
  118. * @param key to perform sanity checks on
  119. * @return version number of key. Supported versions are:
  120. * 5: 256-bit EC key with curve NIST P-256
  121. * @throws Exception if the key has the wrong size or public exponent
  122. */
  123. static int checkEC(ECPublicKey key) throws Exception {
  124. if (key.getParams().getCurve().getField().getFieldSize() != 256) {
  125. throw new Exception("Curve must be NIST P-256");
  126. }
  127. return 5;
  128. }
  129. /**
  130. * Perform sanity check on public key.
  131. */
  132. static int check(PublicKey key, boolean useSHA256) throws Exception {
  133. if (key instanceof RSAPublicKey) {
  134. return checkRSA((RSAPublicKey) key, useSHA256);
  135. } else if (key instanceof ECPublicKey) {
  136. if (!useSHA256) {
  137. throw new Exception("Must use SHA-256 with EC keys!");
  138. }
  139. return checkEC((ECPublicKey) key);
  140. } else {
  141. throw new Exception("Unsupported key class: " + key.getClass().getName());
  142. }
  143. }
  144. /**
  145. * @param key to output
  146. * @return a String representing this public key. If the key is a
  147. * version 1 key, the string will be a C initializer; this is
  148. * not true for newer key versions.
  149. */
  150. static String printRSA(RSAPublicKey key, boolean useSHA256, String binfile) throws Exception {
  151. int version = check(key, useSHA256);
  152. final String tabpos = " ";
  153. FileOutputStream os = null;
  154. ByteBuffer bbuf = null;
  155. if (binfile != null) {
  156. try {
  157. os = new FileOutputStream(binfile);
  158. bbuf = ByteBuffer.allocate(1024);
  159. bbuf.order(ByteOrder.LITTLE_ENDIAN);
  160. } catch (Exception e) {
  161. e.printStackTrace();
  162. System.exit(1);
  163. }
  164. }
  165. BigInteger N = key.getModulus();
  166. StringBuilder result = new StringBuilder();
  167. int nwords = N.bitLength() / 32; // # of 32 bit integers in modulus
  168. BigInteger B = BigInteger.valueOf(0x100000000L); // 2^32
  169. BigInteger N0inv = B.subtract(N.modInverse(B)); // -1 / N[0] mod 2^32
  170. result.append("{\n");
  171. result.append(tabpos);
  172. result.append("0x");
  173. result.append(N0inv.toString(16));
  174. if (bbuf != null) {
  175. bbuf.putInt(N0inv.intValue());
  176. }
  177. result.append(",\n");
  178. BigInteger R = BigInteger.valueOf(2).pow(N.bitLength());
  179. BigInteger RR = R.multiply(R).mod(N); // 2^4096 mod N
  180. // Write out modulus as little endian array of integers.
  181. result.append(tabpos);
  182. result.append("{\n");
  183. result.append(tabpos);
  184. result.append(tabpos);
  185. for (int i = 0; i < nwords; ++i) {
  186. long n = N.mod(B).longValue();
  187. result.append(String.format("0x%08x, ", n));
  188. if (bbuf != null) {
  189. bbuf.putInt((int)n);
  190. }
  191. if ((i + 1) % 4 == 0) {
  192. result.append("\n");
  193. if (i + 1 != nwords) {
  194. result.append(tabpos);
  195. result.append(tabpos);
  196. }
  197. }
  198. N = N.divide(B);
  199. }
  200. result.append(tabpos);
  201. result.append("},\n");
  202. // Write R^2 as little endian array of integers.
  203. result.append(tabpos);
  204. result.append("{\n");
  205. result.append(tabpos);
  206. result.append(tabpos);
  207. for (int i = 0; i < nwords; ++i) {
  208. long rr = RR.mod(B).longValue();
  209. result.append(String.format("0x%08x, ", rr));
  210. if (bbuf != null) {
  211. bbuf.putInt((int)rr);
  212. }
  213. if ((i + 1) % 4 == 0) {
  214. result.append("\n");
  215. if (i + 1 != nwords) {
  216. result.append(tabpos);
  217. result.append(tabpos);
  218. }
  219. }
  220. RR = RR.divide(B);
  221. }
  222. if (os != null) {
  223. bbuf.flip();
  224. FileChannel out = os.getChannel();
  225. out.write(bbuf);
  226. out.close();
  227. }
  228. result.append(tabpos);
  229. result.append("},\n");
  230. result.append("},\n");
  231. return result.toString();
  232. }
  233. /**
  234. * @param key to output
  235. * @return a String representing this public key. If the key is a
  236. * version 1 key, the string will be a C initializer; this is
  237. * not true for newer key versions.
  238. */
  239. static String printEC(ECPublicKey key) throws Exception {
  240. int version = checkEC(key);
  241. StringBuilder result = new StringBuilder();
  242. result.append("v");
  243. result.append(Integer.toString(version));
  244. result.append(" ");
  245. BigInteger X = key.getW().getAffineX();
  246. BigInteger Y = key.getW().getAffineY();
  247. int nbytes = key.getParams().getCurve().getField().getFieldSize() / 8; // # of 32 bit integers in X coordinate
  248. result.append("{");
  249. result.append(nbytes);
  250. BigInteger B = BigInteger.valueOf(0x100L); // 2^8
  251. // Write out Y coordinate as array of characters.
  252. result.append(",{");
  253. for (int i = 0; i < nbytes; ++i) {
  254. long n = X.mod(B).longValue();
  255. result.append(n);
  256. if (i != nbytes - 1) {
  257. result.append(",");
  258. }
  259. X = X.divide(B);
  260. }
  261. result.append("}");
  262. // Write out Y coordinate as array of characters.
  263. result.append(",{");
  264. for (int i = 0; i < nbytes; ++i) {
  265. long n = Y.mod(B).longValue();
  266. result.append(n);
  267. if (i != nbytes - 1) {
  268. result.append(",");
  269. }
  270. Y = Y.divide(B);
  271. }
  272. result.append("}");
  273. result.append("}");
  274. return result.toString();
  275. }
  276. static String print(PublicKey key, boolean useSHA256, String binfile) throws Exception {
  277. if (key instanceof RSAPublicKey) {
  278. return printRSA((RSAPublicKey) key, useSHA256, binfile);
  279. } else if (key instanceof ECPublicKey) {
  280. return printEC((ECPublicKey) key);
  281. } else {
  282. throw new Exception("Unsupported key class: " + key.getClass().getName());
  283. }
  284. }
  285. public static void main(String[] args) {
  286. if (args.length != 1 && args.length != 2) {
  287. System.err.println("Usage:");
  288. System.err.println("\tDumpPublicKey PubKey.pem [OutKey.bin] > source.c");
  289. System.exit(1);
  290. }
  291. Security.addProvider(new BouncyCastleProvider());
  292. try {
  293. PemKey pem = new PemKey();
  294. PublicKey key = pem.generatePublicKey(args[0]);
  295. check(key, true);
  296. if (args.length == 1) {
  297. System.out.print(print(key, true, null));
  298. } else {
  299. System.out.print(print(key, true, args[1]));
  300. }
  301. } catch (Exception e) {
  302. e.printStackTrace();
  303. System.exit(1);
  304. }
  305. System.exit(0);
  306. }
  307. }