You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BouncyCastleGpgKeyLocator.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. /*
  2. * Copyright (C) 2018, 2021 Salesforce and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.gpg.bc.internal;
  11. import static java.nio.file.Files.exists;
  12. import static java.nio.file.Files.newInputStream;
  13. import java.io.BufferedInputStream;
  14. import java.io.File;
  15. import java.io.FileNotFoundException;
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.net.URISyntaxException;
  19. import java.nio.file.DirectoryStream;
  20. import java.nio.file.Files;
  21. import java.nio.file.InvalidPathException;
  22. import java.nio.file.NoSuchFileException;
  23. import java.nio.file.Path;
  24. import java.nio.file.Paths;
  25. import java.security.NoSuchAlgorithmException;
  26. import java.security.NoSuchProviderException;
  27. import java.text.MessageFormat;
  28. import java.util.Iterator;
  29. import java.util.Locale;
  30. import org.bouncycastle.gpg.keybox.BlobType;
  31. import org.bouncycastle.gpg.keybox.KeyBlob;
  32. import org.bouncycastle.gpg.keybox.KeyBox;
  33. import org.bouncycastle.gpg.keybox.KeyInformation;
  34. import org.bouncycastle.gpg.keybox.PublicKeyRingBlob;
  35. import org.bouncycastle.gpg.keybox.UserID;
  36. import org.bouncycastle.gpg.keybox.jcajce.JcaKeyBoxBuilder;
  37. import org.bouncycastle.openpgp.PGPException;
  38. import org.bouncycastle.openpgp.PGPKeyFlags;
  39. import org.bouncycastle.openpgp.PGPPublicKey;
  40. import org.bouncycastle.openpgp.PGPPublicKeyRing;
  41. import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
  42. import org.bouncycastle.openpgp.PGPSecretKey;
  43. import org.bouncycastle.openpgp.PGPSecretKeyRing;
  44. import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
  45. import org.bouncycastle.openpgp.PGPSignature;
  46. import org.bouncycastle.openpgp.PGPUtil;
  47. import org.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider;
  48. import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator;
  49. import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder;
  50. import org.bouncycastle.util.encoders.Hex;
  51. import org.eclipse.jgit.annotations.NonNull;
  52. import org.eclipse.jgit.api.errors.CanceledException;
  53. import org.eclipse.jgit.errors.UnsupportedCredentialItem;
  54. import org.eclipse.jgit.gpg.bc.internal.keys.KeyGrip;
  55. import org.eclipse.jgit.gpg.bc.internal.keys.SecretKeys;
  56. import org.eclipse.jgit.util.FS;
  57. import org.eclipse.jgit.util.StringUtils;
  58. import org.eclipse.jgit.util.SystemReader;
  59. import org.slf4j.Logger;
  60. import org.slf4j.LoggerFactory;
  61. /**
  62. * Locates GPG keys from either <code>~/.gnupg/private-keys-v1.d</code> or
  63. * <code>~/.gnupg/secring.gpg</code>
  64. */
  65. public class BouncyCastleGpgKeyLocator {
  66. /** Thrown if a keybox file exists but doesn't contain an OpenPGP key. */
  67. private static class NoOpenPgpKeyException extends Exception {
  68. private static final long serialVersionUID = 1L;
  69. }
  70. private static final Logger log = LoggerFactory
  71. .getLogger(BouncyCastleGpgKeyLocator.class);
  72. static final Path GPG_DIRECTORY = findGpgDirectory();
  73. private static final Path USER_KEYBOX_PATH = GPG_DIRECTORY
  74. .resolve("pubring.kbx"); //$NON-NLS-1$
  75. private static final Path USER_SECRET_KEY_DIR = GPG_DIRECTORY
  76. .resolve("private-keys-v1.d"); //$NON-NLS-1$
  77. private static final Path USER_PGP_PUBRING_FILE = GPG_DIRECTORY
  78. .resolve("pubring.gpg"); //$NON-NLS-1$
  79. private static final Path USER_PGP_LEGACY_SECRING_FILE = GPG_DIRECTORY
  80. .resolve("secring.gpg"); //$NON-NLS-1$
  81. private final String signingKey;
  82. private BouncyCastleGpgKeyPassphrasePrompt passphrasePrompt;
  83. private static Path findGpgDirectory() {
  84. SystemReader system = SystemReader.getInstance();
  85. if (system.isWindows()) {
  86. // On Windows prefer %APPDATA%\gnupg if it exists, even if Cygwin is
  87. // used.
  88. String appData = system.getenv("APPDATA"); //$NON-NLS-1$
  89. if (appData != null && !appData.isEmpty()) {
  90. try {
  91. Path directory = Paths.get(appData).resolve("gnupg"); //$NON-NLS-1$
  92. if (Files.isDirectory(directory)) {
  93. return directory;
  94. }
  95. } catch (SecurityException | InvalidPathException e) {
  96. // Ignore and return the default location below.
  97. }
  98. }
  99. }
  100. // All systems, including Cygwin and even Windows if
  101. // %APPDATA%\gnupg doesn't exist: ~/.gnupg
  102. File home = FS.DETECTED.userHome();
  103. if (home == null) {
  104. // Oops. What now?
  105. home = new File(".").getAbsoluteFile(); //$NON-NLS-1$
  106. }
  107. return home.toPath().resolve(".gnupg"); //$NON-NLS-1$
  108. }
  109. /**
  110. * Create a new key locator for the specified signing key.
  111. * <p>
  112. * The signing key must either be a hex representation of a specific key or
  113. * a user identity substring (eg., email address). All keys in the KeyBox
  114. * will be looked up in the order as returned by the KeyBox. A key id will
  115. * be searched before attempting to find a key by user id.
  116. * </p>
  117. *
  118. * @param signingKey
  119. * the signing key to search for
  120. * @param passphrasePrompt
  121. * the provider to use when asking for key passphrase
  122. */
  123. public BouncyCastleGpgKeyLocator(String signingKey,
  124. @NonNull BouncyCastleGpgKeyPassphrasePrompt passphrasePrompt) {
  125. this.signingKey = signingKey;
  126. this.passphrasePrompt = passphrasePrompt;
  127. }
  128. private PGPSecretKey attemptParseSecretKey(Path keyFile,
  129. PGPDigestCalculatorProvider calculatorProvider,
  130. SecretKeys.PassphraseSupplier passphraseSupplier,
  131. PGPPublicKey publicKey)
  132. throws IOException, PGPException, CanceledException,
  133. UnsupportedCredentialItem, URISyntaxException {
  134. try (InputStream in = newInputStream(keyFile)) {
  135. return SecretKeys.readSecretKey(in, calculatorProvider,
  136. passphraseSupplier, publicKey);
  137. }
  138. }
  139. /**
  140. * Checks whether a given OpenPGP {@code userId} matches a given
  141. * {@code signingKeySpec}, which is supposed to have one of the formats
  142. * defined by GPG.
  143. * <p>
  144. * Not all formats are supported; only formats starting with '=', '&lt;',
  145. * '@', and '*' are handled. Any other format results in a case-insensitive
  146. * substring match.
  147. * </p>
  148. *
  149. * @param userId
  150. * of a key
  151. * @param signingKeySpec
  152. * GPG key identification
  153. * @return whether the {@code userId} matches
  154. * @see <a href=
  155. * "https://www.gnupg.org/documentation/manuals/gnupg/Specify-a-User-ID.html">GPG
  156. * Documentation: How to Specify a User ID</a>
  157. */
  158. static boolean containsSigningKey(String userId, String signingKeySpec) {
  159. if (StringUtils.isEmptyOrNull(userId)
  160. || StringUtils.isEmptyOrNull(signingKeySpec)) {
  161. return false;
  162. }
  163. String toMatch = signingKeySpec;
  164. if (toMatch.startsWith("0x") && toMatch.trim().length() > 2) { //$NON-NLS-1$
  165. return false; // Explicit fingerprint
  166. }
  167. int command = toMatch.charAt(0);
  168. switch (command) {
  169. case '=':
  170. case '<':
  171. case '@':
  172. case '*':
  173. toMatch = toMatch.substring(1);
  174. if (toMatch.isEmpty()) {
  175. return false;
  176. }
  177. break;
  178. default:
  179. break;
  180. }
  181. switch (command) {
  182. case '=':
  183. return userId.equals(toMatch);
  184. case '<': {
  185. int begin = userId.indexOf('<');
  186. int end = userId.indexOf('>', begin + 1);
  187. int stop = toMatch.indexOf('>');
  188. return begin >= 0 && end > begin + 1 && stop > 0
  189. && userId.substring(begin + 1, end)
  190. .equalsIgnoreCase(toMatch.substring(0, stop));
  191. }
  192. case '@': {
  193. int begin = userId.indexOf('<');
  194. int end = userId.indexOf('>', begin + 1);
  195. return begin >= 0 && end > begin + 1
  196. && containsIgnoreCase(userId.substring(begin + 1, end),
  197. toMatch);
  198. }
  199. default:
  200. if (toMatch.trim().isEmpty()) {
  201. return false;
  202. }
  203. return containsIgnoreCase(userId, toMatch);
  204. }
  205. }
  206. private static boolean containsIgnoreCase(String a, String b) {
  207. int alength = a.length();
  208. int blength = b.length();
  209. for (int i = 0; i + blength <= alength; i++) {
  210. if (a.regionMatches(true, i, b, 0, blength)) {
  211. return true;
  212. }
  213. }
  214. return false;
  215. }
  216. private static String toFingerprint(String keyId) {
  217. if (keyId.startsWith("0x")) { //$NON-NLS-1$
  218. return keyId.substring(2);
  219. }
  220. return keyId;
  221. }
  222. static PGPPublicKey findPublicKey(String fingerprint, String keySpec)
  223. throws IOException, PGPException {
  224. PGPPublicKey result = findPublicKeyInPubring(USER_PGP_PUBRING_FILE,
  225. fingerprint, keySpec);
  226. if (result == null && exists(USER_KEYBOX_PATH)) {
  227. try {
  228. result = findPublicKeyInKeyBox(USER_KEYBOX_PATH, fingerprint,
  229. keySpec);
  230. } catch (NoSuchAlgorithmException | NoSuchProviderException
  231. | IOException | NoOpenPgpKeyException e) {
  232. log.error(e.getMessage(), e);
  233. }
  234. }
  235. return result;
  236. }
  237. private static PGPPublicKey findPublicKeyByKeyId(KeyBlob keyBlob,
  238. String keyId)
  239. throws IOException {
  240. if (keyId.isEmpty()) {
  241. return null;
  242. }
  243. for (KeyInformation keyInfo : keyBlob.getKeyInformation()) {
  244. String fingerprint = Hex.toHexString(keyInfo.getFingerprint())
  245. .toLowerCase(Locale.ROOT);
  246. if (fingerprint.endsWith(keyId)) {
  247. return getPublicKey(keyBlob, keyInfo.getFingerprint());
  248. }
  249. }
  250. return null;
  251. }
  252. private static PGPPublicKey findPublicKeyByUserId(KeyBlob keyBlob,
  253. String keySpec)
  254. throws IOException {
  255. for (UserID userID : keyBlob.getUserIds()) {
  256. if (containsSigningKey(userID.getUserIDAsString(), keySpec)) {
  257. return getSigningPublicKey(keyBlob);
  258. }
  259. }
  260. return null;
  261. }
  262. /**
  263. * Finds a public key associated with the signing key.
  264. *
  265. * @param keyboxFile
  266. * the KeyBox file
  267. * @param keyId
  268. * to look for, may be null
  269. * @param keySpec
  270. * to look for
  271. * @return publicKey the public key (maybe <code>null</code>)
  272. * @throws IOException
  273. * in case of problems reading the file
  274. * @throws NoSuchAlgorithmException
  275. * @throws NoSuchProviderException
  276. * @throws NoOpenPgpKeyException
  277. * if the file does not contain any OpenPGP key
  278. */
  279. private static PGPPublicKey findPublicKeyInKeyBox(Path keyboxFile,
  280. String keyId, String keySpec)
  281. throws IOException, NoSuchAlgorithmException,
  282. NoSuchProviderException, NoOpenPgpKeyException {
  283. KeyBox keyBox = readKeyBoxFile(keyboxFile);
  284. String id = keyId != null ? keyId
  285. : toFingerprint(keySpec).toLowerCase(Locale.ROOT);
  286. boolean hasOpenPgpKey = false;
  287. for (KeyBlob keyBlob : keyBox.getKeyBlobs()) {
  288. if (keyBlob.getType() == BlobType.OPEN_PGP_BLOB) {
  289. hasOpenPgpKey = true;
  290. PGPPublicKey key = findPublicKeyByKeyId(keyBlob, id);
  291. if (key != null) {
  292. return key;
  293. }
  294. key = findPublicKeyByUserId(keyBlob, keySpec);
  295. if (key != null) {
  296. return key;
  297. }
  298. }
  299. }
  300. if (!hasOpenPgpKey) {
  301. throw new NoOpenPgpKeyException();
  302. }
  303. return null;
  304. }
  305. /**
  306. * If there is a private key directory containing keys, use pubring.kbx or
  307. * pubring.gpg to find the public key; then try to find the secret key in
  308. * the directory.
  309. * <p>
  310. * If there is no private key directory (or it doesn't contain any keys),
  311. * try to find the key in secring.gpg directly.
  312. * </p>
  313. *
  314. * @return the secret key
  315. * @throws IOException
  316. * in case of issues reading key files
  317. * @throws NoSuchAlgorithmException
  318. * @throws NoSuchProviderException
  319. * @throws PGPException
  320. * in case of issues finding a key, including no key found
  321. * @throws CanceledException
  322. * @throws URISyntaxException
  323. * @throws UnsupportedCredentialItem
  324. */
  325. @NonNull
  326. public BouncyCastleGpgKey findSecretKey() throws IOException,
  327. NoSuchAlgorithmException, NoSuchProviderException, PGPException,
  328. CanceledException, UnsupportedCredentialItem, URISyntaxException {
  329. BouncyCastleGpgKey key;
  330. PGPPublicKey publicKey = null;
  331. if (hasKeyFiles(USER_SECRET_KEY_DIR)) {
  332. // Use pubring.kbx or pubring.gpg to find the public key, then try
  333. // the key files in the directory. If the public key was found in
  334. // pubring.gpg also try secring.gpg to find the secret key.
  335. if (exists(USER_KEYBOX_PATH)) {
  336. try {
  337. publicKey = findPublicKeyInKeyBox(USER_KEYBOX_PATH, null,
  338. signingKey);
  339. if (publicKey != null) {
  340. key = findSecretKeyForKeyBoxPublicKey(publicKey,
  341. USER_KEYBOX_PATH);
  342. if (key != null) {
  343. return key;
  344. }
  345. throw new PGPException(MessageFormat.format(
  346. BCText.get().gpgNoSecretKeyForPublicKey,
  347. Long.toHexString(publicKey.getKeyID())));
  348. }
  349. throw new PGPException(MessageFormat.format(
  350. BCText.get().gpgNoPublicKeyFound, signingKey));
  351. } catch (NoOpenPgpKeyException e) {
  352. // There are no OpenPGP keys in the keybox at all: try the
  353. // pubring.gpg, if it exists.
  354. if (log.isDebugEnabled()) {
  355. log.debug("{} does not contain any OpenPGP keys", //$NON-NLS-1$
  356. USER_KEYBOX_PATH);
  357. }
  358. }
  359. }
  360. if (exists(USER_PGP_PUBRING_FILE)) {
  361. publicKey = findPublicKeyInPubring(USER_PGP_PUBRING_FILE, null,
  362. signingKey);
  363. if (publicKey != null) {
  364. // GPG < 2.1 may have both; the agent using the directory
  365. // and gpg using secring.gpg. GPG >= 2.1 delegates all
  366. // secret key handling to the agent and doesn't use
  367. // secring.gpg at all, even if it exists. Which means for us
  368. // we have to try both since we don't know which GPG version
  369. // the user has.
  370. key = findSecretKeyForKeyBoxPublicKey(publicKey,
  371. USER_PGP_PUBRING_FILE);
  372. if (key != null) {
  373. return key;
  374. }
  375. }
  376. }
  377. if (publicKey == null) {
  378. throw new PGPException(MessageFormat.format(
  379. BCText.get().gpgNoPublicKeyFound, signingKey));
  380. }
  381. // We found a public key, but didn't find the secret key in the
  382. // private key directory. Go try the secring.gpg.
  383. }
  384. boolean hasSecring = false;
  385. if (exists(USER_PGP_LEGACY_SECRING_FILE)) {
  386. hasSecring = true;
  387. key = loadKeyFromSecring(USER_PGP_LEGACY_SECRING_FILE);
  388. if (key != null) {
  389. return key;
  390. }
  391. }
  392. if (publicKey != null) {
  393. throw new PGPException(MessageFormat.format(
  394. BCText.get().gpgNoSecretKeyForPublicKey,
  395. Long.toHexString(publicKey.getKeyID())));
  396. } else if (hasSecring) {
  397. // publicKey == null: user has _only_ pubring.gpg/secring.gpg.
  398. throw new PGPException(MessageFormat.format(
  399. BCText.get().gpgNoKeyInLegacySecring, signingKey));
  400. } else {
  401. throw new PGPException(BCText.get().gpgNoKeyring);
  402. }
  403. }
  404. private boolean hasKeyFiles(Path dir) {
  405. try (DirectoryStream<Path> contents = Files.newDirectoryStream(dir,
  406. "*.key")) { //$NON-NLS-1$
  407. return contents.iterator().hasNext();
  408. } catch (IOException e) {
  409. // Not a directory, or something else
  410. return false;
  411. }
  412. }
  413. private BouncyCastleGpgKey loadKeyFromSecring(Path secring)
  414. throws IOException, PGPException {
  415. PGPSecretKey secretKey = findSecretKeyInLegacySecring(signingKey,
  416. secring);
  417. if (secretKey != null) {
  418. if (!secretKey.isSigningKey()) {
  419. throw new PGPException(MessageFormat
  420. .format(BCText.get().gpgNotASigningKey, signingKey));
  421. }
  422. return new BouncyCastleGpgKey(secretKey, secring);
  423. }
  424. return null;
  425. }
  426. private BouncyCastleGpgKey findSecretKeyForKeyBoxPublicKey(
  427. PGPPublicKey publicKey, Path userKeyboxPath)
  428. throws PGPException, CanceledException, UnsupportedCredentialItem,
  429. URISyntaxException {
  430. byte[] keyGrip = null;
  431. try {
  432. keyGrip = KeyGrip.getKeyGrip(publicKey);
  433. } catch (PGPException e) {
  434. throw new PGPException(
  435. MessageFormat.format(BCText.get().gpgNoKeygrip,
  436. Hex.toHexString(publicKey.getFingerprint())),
  437. e);
  438. }
  439. String filename = Hex.toHexString(keyGrip).toUpperCase(Locale.ROOT)
  440. + ".key"; //$NON-NLS-1$
  441. Path keyFile = USER_SECRET_KEY_DIR.resolve(filename);
  442. if (!Files.exists(keyFile)) {
  443. return null;
  444. }
  445. boolean clearPrompt = false;
  446. try {
  447. PGPDigestCalculatorProvider calculatorProvider = new JcaPGPDigestCalculatorProviderBuilder()
  448. .build();
  449. clearPrompt = true;
  450. PGPSecretKey secretKey = null;
  451. try {
  452. secretKey = attemptParseSecretKey(keyFile, calculatorProvider,
  453. () -> passphrasePrompt.getPassphrase(
  454. publicKey.getFingerprint(), userKeyboxPath),
  455. publicKey);
  456. } catch (PGPException e) {
  457. throw new PGPException(MessageFormat.format(
  458. BCText.get().gpgFailedToParseSecretKey,
  459. keyFile.toAbsolutePath()), e);
  460. }
  461. if (secretKey != null) {
  462. if (!secretKey.isSigningKey()) {
  463. throw new PGPException(MessageFormat.format(
  464. BCText.get().gpgNotASigningKey, signingKey));
  465. }
  466. clearPrompt = false;
  467. return new BouncyCastleGpgKey(secretKey, userKeyboxPath);
  468. }
  469. return null;
  470. } catch (RuntimeException e) {
  471. throw e;
  472. } catch (FileNotFoundException | NoSuchFileException e) {
  473. clearPrompt = false;
  474. return null;
  475. } catch (IOException e) {
  476. throw new PGPException(MessageFormat.format(
  477. BCText.get().gpgFailedToParseSecretKey,
  478. keyFile.toAbsolutePath()), e);
  479. } finally {
  480. if (clearPrompt) {
  481. passphrasePrompt.clear();
  482. }
  483. }
  484. }
  485. /**
  486. * Return the first suitable key for signing in the key ring collection. For
  487. * this case we only expect there to be one key available for signing.
  488. * </p>
  489. *
  490. * @param signingkey
  491. * @param secringFile
  492. *
  493. * @return the first suitable PGP secret key found for signing
  494. * @throws IOException
  495. * on I/O related errors
  496. * @throws PGPException
  497. * on BouncyCastle errors
  498. */
  499. private PGPSecretKey findSecretKeyInLegacySecring(String signingkey,
  500. Path secringFile) throws IOException, PGPException {
  501. try (InputStream in = newInputStream(secringFile)) {
  502. PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
  503. PGPUtil.getDecoderStream(new BufferedInputStream(in)),
  504. new JcaKeyFingerprintCalculator());
  505. String keyId = toFingerprint(signingkey).toLowerCase(Locale.ROOT);
  506. Iterator<PGPSecretKeyRing> keyrings = pgpSec.getKeyRings();
  507. while (keyrings.hasNext()) {
  508. PGPSecretKeyRing keyRing = keyrings.next();
  509. Iterator<PGPSecretKey> keys = keyRing.getSecretKeys();
  510. while (keys.hasNext()) {
  511. PGPSecretKey key = keys.next();
  512. // try key id
  513. String fingerprint = Hex
  514. .toHexString(key.getPublicKey().getFingerprint())
  515. .toLowerCase(Locale.ROOT);
  516. if (fingerprint.endsWith(keyId)) {
  517. return key;
  518. }
  519. // try user id
  520. Iterator<String> userIDs = key.getUserIDs();
  521. while (userIDs.hasNext()) {
  522. String userId = userIDs.next();
  523. if (containsSigningKey(userId, signingKey)) {
  524. return key;
  525. }
  526. }
  527. }
  528. }
  529. }
  530. return null;
  531. }
  532. /**
  533. * Return the first public key matching the key id ({@link #signingKey}.
  534. *
  535. * @param pubringFile
  536. * to search
  537. * @param keyId
  538. * to look for, may be null
  539. * @param keySpec
  540. * to look for
  541. *
  542. * @return the PGP public key, or {@code null} if none found
  543. * @throws IOException
  544. * on I/O related errors
  545. * @throws PGPException
  546. * on BouncyCastle errors
  547. */
  548. private static PGPPublicKey findPublicKeyInPubring(Path pubringFile,
  549. String keyId, String keySpec)
  550. throws IOException, PGPException {
  551. try (InputStream in = newInputStream(pubringFile)) {
  552. PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(
  553. new BufferedInputStream(in),
  554. new JcaKeyFingerprintCalculator());
  555. String id = keyId != null ? keyId
  556. : toFingerprint(keySpec).toLowerCase(Locale.ROOT);
  557. Iterator<PGPPublicKeyRing> keyrings = pgpPub.getKeyRings();
  558. while (keyrings.hasNext()) {
  559. PGPPublicKeyRing keyRing = keyrings.next();
  560. Iterator<PGPPublicKey> keys = keyRing.getPublicKeys();
  561. while (keys.hasNext()) {
  562. PGPPublicKey key = keys.next();
  563. // try key id
  564. String fingerprint = Hex.toHexString(key.getFingerprint())
  565. .toLowerCase(Locale.ROOT);
  566. if (fingerprint.endsWith(id)) {
  567. return key;
  568. }
  569. // try user id
  570. Iterator<String> userIDs = key.getUserIDs();
  571. while (userIDs.hasNext()) {
  572. String userId = userIDs.next();
  573. if (containsSigningKey(userId, keySpec)) {
  574. return key;
  575. }
  576. }
  577. }
  578. }
  579. } catch (FileNotFoundException | NoSuchFileException e) {
  580. // Ignore and return null
  581. }
  582. return null;
  583. }
  584. private static PGPPublicKey getPublicKey(KeyBlob blob, byte[] fingerprint)
  585. throws IOException {
  586. return ((PublicKeyRingBlob) blob).getPGPPublicKeyRing()
  587. .getPublicKey(fingerprint);
  588. }
  589. private static PGPPublicKey getSigningPublicKey(KeyBlob blob)
  590. throws IOException {
  591. PGPPublicKey masterKey = null;
  592. Iterator<PGPPublicKey> keys = ((PublicKeyRingBlob) blob)
  593. .getPGPPublicKeyRing().getPublicKeys();
  594. while (keys.hasNext()) {
  595. PGPPublicKey key = keys.next();
  596. // only consider keys that have the [S] usage flag set
  597. if (isSigningKey(key)) {
  598. if (key.isMasterKey()) {
  599. masterKey = key;
  600. } else {
  601. return key;
  602. }
  603. }
  604. }
  605. // return the master key if no other signing key was found or null if
  606. // the master key did not have the signing flag set
  607. return masterKey;
  608. }
  609. private static boolean isSigningKey(PGPPublicKey key) {
  610. Iterator signatures = key.getSignatures();
  611. while (signatures.hasNext()) {
  612. PGPSignature sig = (PGPSignature) signatures.next();
  613. if ((sig.getHashedSubPackets().getKeyFlags()
  614. & PGPKeyFlags.CAN_SIGN) > 0) {
  615. return true;
  616. }
  617. }
  618. return false;
  619. }
  620. private static KeyBox readKeyBoxFile(Path keyboxFile) throws IOException,
  621. NoSuchAlgorithmException, NoSuchProviderException,
  622. NoOpenPgpKeyException {
  623. if (keyboxFile.toFile().length() == 0) {
  624. throw new NoOpenPgpKeyException();
  625. }
  626. KeyBox keyBox;
  627. try (InputStream in = new BufferedInputStream(
  628. newInputStream(keyboxFile))) {
  629. keyBox = new JcaKeyBoxBuilder().build(in);
  630. }
  631. return keyBox;
  632. }
  633. }