List of usage examples for org.bouncycastle.openpgp PGPPublicKeyRing getPublicKey
public PGPPublicKey getPublicKey()
From source file:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
@Override public void importCryptographyMetadata(final InputStream input) { OpenPGPSecurityUtility.LOGGER.info("Importing cryptography metadata"); try {/*from w w w .j a va 2 s . com*/ PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(new FileInputStream(this.publicKeyRing))); final PGPPublicKeyRingCollection pgpPubIncoming = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(input)); PGPPublicKeyRing ppKr; final Iterator<PGPPublicKeyRing> it = pgpPubIncoming.getKeyRings(); while (it.hasNext()) { ppKr = it.next(); if (!pgpPub.contains(ppKr.getPublicKey().getKeyID())) { pgpPub = PGPPublicKeyRingCollection.addPublicKeyRing(pgpPub, ppKr); } } pgpPub.encode(new FileOutputStream(new File(this.publicKeyRing.getAbsolutePath()))); } catch (final FileNotFoundException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } catch (final PGPException e) { e.printStackTrace(); } }
From source file:com.github.chrbayer84.keybits.GnuPGP.java
License:Open Source License
public PGPPublicKeyRing getPublicKeyRing(PGPPublicKeyRingCollection public_key_ring_collection, String id) { PGPPublicKeyRing ret = null;// ww w. j av a 2s .c o m Iterator<PGPPublicKeyRing> iterator = public_key_ring_collection.getKeyRings(); while (iterator.hasNext()) { PGPPublicKeyRing public_key_ring = iterator.next(); if (Long.toHexString(public_key_ring.getPublicKey().getKeyID()).equals(id)) return public_key_ring; } return ret; }
From source file:com.github.chrbayer84.keybits.KeyBits.java
License:Open Source License
/** * @param args/* w ww . j a v a2s .c om*/ */ public static void main(String[] args) throws Exception { int number_of_addresses = 1; int depth = 1; String usage = "java -jar KeyBits.jar [options]"; // create parameters which can be chosen Option help = new Option("h", "print this message"); Option verbose = new Option("v", "verbose"); Option exprt = new Option("e", "export public key to blockchain"); Option imprt = OptionBuilder.withArgName("string").hasArg() .withDescription("import public key from blockchain").create("i"); Option blockchain_address = OptionBuilder.withArgName("string").hasArg().withDescription("bitcoin address") .create("a"); Option create_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("create wallet") .create("c"); Option update_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("update wallet") .create("u"); Option balance_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("return balance of wallet").create("b"); Option show_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("show content of wallet").create("w"); Option send_coins = OptionBuilder.withArgName("file name").hasArg().withDescription("send satoshis") .create("s"); Option monitor_pending = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor pending transactions of wallet").create("p"); Option monitor_depth = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor transaction depths of wallet").create("d"); Option number = OptionBuilder.withArgName("integer").hasArg() .withDescription("in combination with -c, -d, -r or -s").create("n"); Option reset = OptionBuilder.withArgName("file name").hasArg().withDescription("reset wallet").create("r"); Options options = new Options(); options.addOption(help); options.addOption(verbose); options.addOption(imprt); options.addOption(exprt); options.addOption(blockchain_address); options.addOption(create_wallet); options.addOption(update_wallet); options.addOption(balance_wallet); options.addOption(show_wallet); options.addOption(send_coins); options.addOption(monitor_pending); options.addOption(monitor_depth); options.addOption(number); options.addOption(reset); BasicParser parser = new BasicParser(); CommandLine cmd = null; String header = "This is KeyBits v0.01b.1412953962" + System.getProperty("line.separator"); // show help if wrong usage try { cmd = parser.parse(options, args); } catch (Exception e) { printHelp(usage, options, header); } if (cmd.getOptions().length == 0) printHelp(usage, options, header); if (cmd.hasOption("h")) printHelp(usage, options, header); if (cmd.hasOption("v")) System.out.println(header); if (cmd.hasOption("c") && cmd.hasOption("n")) number_of_addresses = new Integer(cmd.getOptionValue("n")).intValue(); if (cmd.hasOption("d") && cmd.hasOption("n")) depth = new Integer(cmd.getOptionValue("n")).intValue(); String checkpoints_file_name = "checkpoints"; if (!new File(checkpoints_file_name).exists()) checkpoints_file_name = null; // --------------------------------------------------------------------- if (cmd.hasOption("c")) { String wallet_file_name = cmd.getOptionValue("c"); String passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); if (!new File(wallet_file_name).exists()) { String passphrase_ = HelpfulStuff.reInsertPassphrase("enter password for " + wallet_file_name); if (!passphrase.equals(passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(wallet_file_name, wallet_file_name + ".chain", number_of_addresses, passphrase); System.exit(0); } if (cmd.hasOption("u")) { String wallet_file_name = cmd.getOptionValue("u"); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("b")) { String wallet_file_name = cmd.getOptionValue("b"); System.out.println( MyWallet.getBalanceOfWallet(wallet_file_name, wallet_file_name + ".chain").longValue()); System.exit(0); } if (cmd.hasOption("w")) { String wallet_file_name = cmd.getOptionValue("w"); System.out.println(MyWallet.showContentOfWallet(wallet_file_name, wallet_file_name + ".chain")); System.exit(0); } if (cmd.hasOption("p")) { System.out.println("monitoring of pending transactions ... "); String wallet_file_name = cmd.getOptionValue("p"); MyWallet.monitorPendingTransactions(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("d")) { System.out.println("monitoring of transaction depth ... "); String wallet_file_name = cmd.getOptionValue("d"); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, depth); System.exit(0); } if (cmd.hasOption("r") && cmd.hasOption("n")) { long epoch = new Long(cmd.getOptionValue("n")); System.out.println("resetting wallet ... "); String wallet_file_name = cmd.getOptionValue("r"); File chain_file = (new File(wallet_file_name + ".chain")); if (chain_file.exists()) chain_file.delete(); MyWallet.setCreationTime(wallet_file_name, epoch); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("s") && cmd.hasOption("a") && cmd.hasOption("n")) { String wallet_file_name = cmd.getOptionValue("s"); String address = cmd.getOptionValue("a"); Integer amount = new Integer(cmd.getOptionValue("n")); String wallet_passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); MyWallet.sendCoins(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, address, new BigInteger(amount + ""), wallet_passphrase); System.out.println("waiting ..."); Thread.sleep(10000); System.out.println("monitoring of transaction depth ... "); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, 1); System.out.println("transaction fixed in blockchain with depth " + depth); System.exit(0); } // ---------------------------------------------------------------------------------------- // creates public key // ---------------------------------------------------------------------------------------- GnuPGP gpg = new GnuPGP(); if (cmd.hasOption("e")) { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = input.readLine()) != null) sb.append(line + "\n"); PGPPublicKeyRing public_key_ring = gpg.getDearmored(sb.toString()); //System.out.println(gpg.showPublicKeys(public_key_ring)); byte[] public_key_ring_encoded = gpg.getEncoded(public_key_ring); String[] addresses = (new Encoding()).encodePublicKey(public_key_ring_encoded); // System.out.println(gpg.showPublicKey(gpg.getDecoded(encoding.decodePublicKey(addresses)))); // file names for message String public_key_file_name = Long.toHexString(public_key_ring.getPublicKey().getKeyID()) + ".wallet"; String public_key_wallet_file_name = public_key_file_name; String public_key_chain_file_name = public_key_wallet_file_name + ".chain"; // hier muss dass passwort noch nach encodeAddresses weitergeleitet werden da sonst zweimal abfrage String public_key_wallet_passphrase = HelpfulStuff .insertPassphrase("enter password for " + public_key_wallet_file_name); if (!new File(public_key_wallet_file_name).exists()) { String public_key_wallet_passphrase_ = HelpfulStuff .reInsertPassphrase("enter password for " + public_key_wallet_file_name); if (!public_key_wallet_passphrase.equals(public_key_wallet_passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(public_key_wallet_file_name, public_key_chain_file_name, 1, public_key_wallet_passphrase); MyWallet.updateWallet(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name); String public_key_address = MyWallet.getAddress(public_key_wallet_file_name, public_key_chain_file_name, 0); System.out.println("address of public key: " + public_key_address); // 10000 additional satoshis for sending transaction to address of recipient of message and 10000 for fees KeyBits.encodeAddresses(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name, addresses, 2 * SendRequest.DEFAULT_FEE_PER_KB.intValue(), depth, public_key_wallet_passphrase); } if (cmd.hasOption("i")) { String location = cmd.getOptionValue("i"); String[] addresses = null; if (location.indexOf(",") > -1) { String[] locations = location.split(","); addresses = MyWallet.getAddressesFromBlockAndTransaction("main.wallet", "main.wallet.chain", checkpoints_file_name, locations[0], locations[1]); } else { addresses = BlockchainDotInfo.getKeys(location); } byte[] encoded = (new Encoding()).decodePublicKey(addresses); PGPPublicKeyRing public_key_ring = gpg.getDecoded(encoded); System.out.println(gpg.getArmored(public_key_ring)); System.exit(0); } }
From source file:com.google.e2e.bcdriver.KeyChecker.java
License:Apache License
/** * <p>This is the primary way to use this utility. It examines a * provided PGPPublicKeyRing and returns a wrapped object that * provides access only to verified key material.</p> * * @param pkr is the keyring to be examined. * @return an object that provides filtered access to verified key material. *//* w ww . j a va 2s.c o m*/ public static final PKR validate(PGPPublicKeyRing pkr) throws PGPException, SignatureException, IOException { // First handle keyring revocation/designated revokers PGPPublicKey masterpk = pkr.getPublicKey(); if (!masterpk.isMasterKey()) { throw new IllegalArgumentException("Unexpected - first key is not master"); } StringBuilder errors = new StringBuilder(); List<UserID> userids = new ArrayList<UserID>(); List<Subkey> subkeys = new ArrayList<Subkey>(); int validRejects = 0; if (masterpk.hasRevocation()) { // Second pass - check for revocations. Iterator<PGPSignature> masterSigit = Util.getTypedIterator( masterpk.getSignaturesOfType(PGPSignature.KEY_REVOCATION), PGPSignature.class); while (masterSigit.hasNext()) { PGPSignature sig = masterSigit.next(); if (isGoodDirectSignature(sig, masterpk, masterpk, errors)) { validRejects++; } } } if (validRejects > 0) { // Primary key is revoked, discard everything else. return new PKR(PKR.Status.REVOKED, pkr, userids, subkeys, errors); } // Filter for valid userids. Iterator<String> uidit = Util.getTypedIterator(masterpk.getUserIDs(), String.class); while (uidit.hasNext()) { maybeAddUserID(userids, masterpk, uidit.next(), errors); } // Don't bother with subkeys if we don't have a valid uid. if ((userids.size() == 0)) { return new PKR(PKR.Status.UNUSABLE, pkr, userids, subkeys, errors); } // Now start checking subkeys. Iterator<PGPPublicKey> keysit = pkr.getPublicKeys(); // Skip the first (master) key. keysit.next(); while (keysit.hasNext()) { PGPPublicKey subkey = keysit.next(); if (subkey.isMasterKey()) { throw new IllegalArgumentException("unexpected"); } maybeAddSubkey(subkeys, masterpk, subkey, errors); } return new PKR(PKR.Status.OK, pkr, userids, subkeys, errors); }
From source file:com.google.gerrit.gpg.GerritPublicKeyCheckerTest.java
License:Apache License
@Test public void keyLaterInTrustChainMissingUserId() throws Exception { // A---Bx//from ww w.ja va 2 s . co m // \ // \---C // // The server ultimately trusts B. // C signed A's key but is not in the store. TestKey keyA = add(keyA(), user); PGPPublicKeyRing keyRingB = keyB().getPublicKeyRing(); PGPPublicKey keyB = keyRingB.getPublicKey(); keyB = PGPPublicKey.removeCertification(keyB, (String) keyB.getUserIDs().next()); keyRingB = PGPPublicKeyRing.insertPublicKey(keyRingB, keyB); add(keyRingB, addUser("userB")); PublicKeyChecker checkerA = checkerFactory.create(user, store); assertProblems(checkerA.check(keyA.getPublicKey()), Status.OK, "No path to a trusted key", "Certification by " + keyToString(keyB) + " is valid, but key is not trusted", "Key D24FE467 used for certification is not in store"); }
From source file:com.google.gerrit.gpg.GerritPublicKeyCheckerTest.java
License:Apache License
private void add(PGPPublicKeyRing kr, IdentifiedUser user) throws Exception { Account.Id id = user.getAccountId(); List<AccountExternalId> newExtIds = new ArrayList<>(2); newExtIds.add(new AccountExternalId(id, toExtIdKey(kr.getPublicKey()))); @SuppressWarnings("unchecked") String userId = (String) Iterators.getOnlyElement(kr.getPublicKey().getUserIDs(), null); if (userId != null) { String email = PushCertificateIdent.parse(userId).getEmailAddress(); assertThat(email).contains("@"); AccountExternalId mailto = new AccountExternalId(id, new AccountExternalId.Key(SCHEME_MAILTO, email)); mailto.setEmailAddress(email);/*from w w w . j av a2 s . c o m*/ newExtIds.add(mailto); } store.add(kr); PersonIdent ident = new PersonIdent("A U Thor", "author@example.com"); CommitBuilder cb = new CommitBuilder(); cb.setAuthor(ident); cb.setCommitter(ident); assertThat(store.save(cb)).isAnyOf(NEW, FAST_FORWARD, FORCED); db.accountExternalIds().insert(newExtIds); accountCache.evict(user.getAccountId()); }
From source file:com.google.gerrit.gpg.PublicKeyCheckerTest.java
License:Apache License
@Test public void revokedKeyDueToCompromise() throws Exception { TestKey k = add(revokedCompromisedKey()); add(validKeyWithoutExpiration());/*from w ww. j a v a2s .c o m*/ save(); assertProblems(k, "Key is revoked (key material has been compromised):" + " test6 compromised"); PGPPublicKeyRing kr = removeRevokers(k.getPublicKeyRing()); store.add(kr); save(); // Key no longer specified as revoker. assertNoProblems(kr.getPublicKey()); }
From source file:com.google.gerrit.gpg.PublicKeyCheckerTest.java
License:Apache License
private PGPPublicKeyRing removeRevokers(PGPPublicKeyRing kr) { PGPPublicKey k = kr.getPublicKey(); @SuppressWarnings("unchecked") Iterator<PGPSignature> sigs = k.getSignaturesOfType(DIRECT_KEY); while (sigs.hasNext()) { PGPSignature sig = sigs.next();/* w w w .j a v a 2s . c om*/ if (sig.getHashedSubPackets().hasSubpacket(REVOCATION_KEY)) { k = PGPPublicKey.removeCertification(k, sig); } } return PGPPublicKeyRing.insertPublicKey(kr, k); }
From source file:com.google.gerrit.gpg.PublicKeyStore.java
License:Apache License
/** * Choose the public key that produced a signature. * <p>/*from w w w . j av a 2s . c om*/ * @param keyRings candidate keys. * @param sig signature object. * @param data signed payload. * @return the key chosen from {@code keyRings} that was able to verify the * signature, or null if none was found. * @throws PGPException if an error occurred verifying the signature. */ public static PGPPublicKey getSigner(Iterable<PGPPublicKeyRing> keyRings, PGPSignature sig, byte[] data) throws PGPException { for (PGPPublicKeyRing kr : keyRings) { PGPPublicKey k = kr.getPublicKey(); sig.init(new BcPGPContentVerifierBuilderProvider(), k); sig.update(data); if (sig.verify()) { return k; } } return null; }
From source file:com.google.gerrit.gpg.PublicKeyStore.java
License:Apache License
/** * Choose the public key that produced a certification. * <p>/*from w ww .jav a 2 s . c o m*/ * @param keyRings candidate keys. * @param sig signature object. * @param userId user ID being certified. * @param key key being certified. * @return the key chosen from {@code keyRings} that was able to verify the * certification, or null if none was found. * @throws PGPException if an error occurred verifying the certification. */ public static PGPPublicKey getSigner(Iterable<PGPPublicKeyRing> keyRings, PGPSignature sig, String userId, PGPPublicKey key) throws PGPException { for (PGPPublicKeyRing kr : keyRings) { PGPPublicKey k = kr.getPublicKey(); sig.init(new BcPGPContentVerifierBuilderProvider(), k); if (sig.verifyCertification(userId, key)) { return k; } } return null; }