List of usage examples for org.bouncycastle.openpgp PGPSecretKey getUserIDs
public Iterator<String> getUserIDs()
From source file:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
/** * Gets the correct signing key from local secret keyring using the supplied * key information./*from w w w .j av a2 s .com*/ * * @param keyInfo * the supplied key information * @return the correct signing key * @throws IOException * Signals that an I/O exception has occurred. * @throws PGPException * thrown if an error is encountered */ public PGPSecretKey getSignKey(final String keyInfo) throws IOException, PGPException { final PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new FileInputStream(this.secretKeyRing))); final Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { final PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next(); final Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { final PGPSecretKey key = (PGPSecretKey) keyIter.next(); final Iterator idIter = key.getUserIDs(); while (idIter.hasNext()) { final String userID = idIter.next().toString(); if (userID.contains(keyInfo) && key.isSigningKey()) return key; } } } return null; }
From source file:com.arcusx.simplepgp.PgpKeyUtils.java
public static String getUserIdFrom(PGPSecretKey secretKey) { return (String) secretKey.getUserIDs().next(); }
From source file:com.lyndir.lhunath.opal.crypto.gpg.GPG.java
License:Apache License
/** * @param privateKeyFile The file that contains the private keys. * * @return all master key IDs available in the given key ring. * * @throws FileNotFoundException/* w w w . j ava 2 s .com*/ * @throws IOException * @throws PGPException */ public static List<PrintableKeyWrapper<PGPSecretKey>> getPrivateKeys(final File privateKeyFile) throws IOException, PGPException { /* Open the key ring. */ try (FileInputStream privateKeyInputStream = new FileInputStream(privateKeyFile)) { List<PrintableKeyWrapper<PGPSecretKey>> keys = new ArrayList<>(); PGPSecretKeyRingCollection privateKeyRing = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(privateKeyInputStream)); /* Enumerate the IDs. */ @SuppressWarnings("unchecked") Iterator<PGPSecretKeyRing> rings = privateKeyRing.getKeyRings(); while (rings.hasNext()) { @SuppressWarnings("unchecked") Iterator<PGPSecretKey> ring = rings.next().getSecretKeys(); while (ring.hasNext()) { PGPSecretKey key = ring.next(); if (!key.getUserIDs().hasNext()) continue; keys.add(new PrintableKeyWrapper<PGPSecretKey>(key, key.getKeyID()) { @Override public String toString() { return getKey().getUserIDs().next().toString(); } }); } } return keys; } }
From source file:com.verhas.licensor.License.java
License:Open Source License
/** * Load the secret key to be used to encrypt the license. After the key is * loaded it can be used to encrypt license files. * /*from www . j a v a 2s. co m*/ * @param in * input stream of the file containing the key rings * @param userId * the user id of the key. If this parameter is {@code null} then * the first key on the key ring appropriate to sign will be * used. * @throws java.io.IOException * @throws org.bouncycastle.openpgp.PGPException */ @SuppressWarnings("unchecked") public License loadKey(InputStream in, final String userId) throws IOException, PGPException { in = PGPUtil.getDecoderStream(in); final PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(in); key = null; for (final PGPSecretKeyRing kRing : in((Iterator<PGPSecretKeyRing>) pgpSec.getKeyRings())) { for (final PGPSecretKey k : in((Iterator<PGPSecretKey>) kRing.getSecretKeys())) { for (final String keyUserId : in((Iterator<String>) k.getUserIDs())) { if (keyIsAppropriate(userId, keyUserId, k)) { key = k; return this; } } } } throw new IllegalArgumentException("Can't find signing key in key ring."); }
From source file:net.staticsnow.nexus.repository.apt.internal.gpg.AptSigningFacet.java
License:Open Source License
public byte[] signInline(String input) throws IOException, PGPException { PGPSecretKey signKey = readSecretKey(); PGPPrivateKey privKey = signKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray())); PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256) .setProvider("BC")); sigGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privKey); @SuppressWarnings("unchecked") Iterator<String> userIds = signKey.getUserIDs(); if (userIds.hasNext()) { PGPSignatureSubpacketGenerator sigSubpacketGenerator = new PGPSignatureSubpacketGenerator(); sigSubpacketGenerator.setSignerUserID(false, userIds.next()); sigGenerator.setHashedSubpackets(sigSubpacketGenerator.generate()); }//from w w w . j av a 2 s . c o m String[] lines = input.split("\r?\n"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) { aOut.beginClearText(PGPUtil.SHA256); boolean firstLine = true; for (String line : lines) { String sigLine = (firstLine ? "" : "\r\n") + line.replaceAll("\\s*$", ""); sigGenerator.update(sigLine.getBytes(Charsets.UTF_8)); aOut.write((line + "\n").getBytes(Charsets.UTF_8)); firstLine = false; } aOut.endClearText(); BCPGOutputStream bOut = new BCPGOutputStream(aOut); sigGenerator.generate().encode(bOut); } return buffer.toByteArray(); }
From source file:org.apache.camel.converter.crypto.PGPDataFormatUtil.java
License:Apache License
@SuppressWarnings("unchecked") private static PGPPrivateKey findPrivateKeyWithKeyId(InputStream keyringInput, long keyid, String passphrase, PGPPassphraseAccessor passphraseAccessor, String provider) throws IOException, PGPException { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyringInput)); for (Iterator<?> i = pgpSec.getKeyRings(); i.hasNext();) { Object data = i.next();//w w w. j av a 2 s . c o m if (data instanceof PGPSecretKeyRing) { PGPSecretKeyRing keyring = (PGPSecretKeyRing) data; for (Iterator<PGPSecretKey> secKeys = keyring.getSecretKeys(); secKeys.hasNext();) { PGPSecretKey secKey = secKeys.next(); if (secKey != null && keyid == secKey.getKeyID()) { if (passphrase == null && passphraseAccessor != null) { // get passphrase from accessor Iterator<String> userIDs = secKey.getUserIDs(); while (passphrase == null && userIDs.hasNext()) { passphrase = passphraseAccessor.getPassphrase(userIDs.next()); } } if (passphrase != null) { PGPPrivateKey privateKey = secKey .extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(provider) .build(passphrase.toCharArray())); if (privateKey != null) { return privateKey; } } } } } } return null; }
From source file:org.apache.camel.converter.crypto.PGPDataFormatUtil.java
License:Apache License
@Deprecated private static PGPPrivateKey findPrivateKey(InputStream keyringInput, InputStream encryptedInput, String passphrase, PGPPassphraseAccessor passphraseAccessor, String provider) throws IOException, PGPException, NoSuchProviderException { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyringInput)); PGPObjectFactory factory = new PGPObjectFactory(PGPUtil.getDecoderStream(encryptedInput)); PGPEncryptedDataList enc;/* w w w. j av a2 s . co m*/ Object o = factory.nextObject(); if (o == null) { throw new PGPException("Provided input is not encrypted."); } if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) factory.nextObject(); } encryptedInput.reset(); // nextObject() method reads from the InputStream, so rewind it! Iterator<?> encryptedDataObjects = enc.getEncryptedDataObjects(); PGPPrivateKey privateKey = null; PGPPublicKeyEncryptedData encryptedData = null; while (privateKey == null && encryptedDataObjects.hasNext()) { encryptedData = (PGPPublicKeyEncryptedData) encryptedDataObjects.next(); PGPSecretKey pgpSecKey = pgpSec.getSecretKey(encryptedData.getKeyID()); if (pgpSecKey != null) { if (passphrase == null && passphraseAccessor != null) { // get passphrase from accessor @SuppressWarnings("unchecked") Iterator<String> userIDs = pgpSecKey.getUserIDs(); while (passphrase == null && userIDs.hasNext()) { passphrase = passphraseAccessor.getPassphrase(userIDs.next()); } } privateKey = pgpSecKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(provider) .build(passphrase.toCharArray())); } } if (privateKey == null && pgpSec.size() > 0 && encryptedData != null) { throw new PGPException("Provided input is encrypted with unknown pair of keys."); } return privateKey; }
From source file:org.apache.camel.converter.crypto.PGPDataFormatUtil.java
License:Apache License
@SuppressWarnings("unchecked") private static PGPSecretKey findSecretKey(InputStream keyringInput, String passphrase, String userId, String provider) throws IOException, PGPException, NoSuchProviderException { PGPSecretKey pgpSecKey = null;// w ww .j a va2s . co m PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyringInput)); for (Iterator<?> i = pgpSec.getKeyRings(); i.hasNext() && pgpSecKey == null;) { Object data = i.next(); if (data instanceof PGPSecretKeyRing) { PGPSecretKeyRing keyring = (PGPSecretKeyRing) data; PGPSecretKey secKey = keyring.getSecretKey(); if (userId != null) { for (Iterator<String> iterator = secKey.getUserIDs(); iterator.hasNext();) { String keyUserId = iterator.next(); // there can be serveral user IDs! if (keyUserId != null && keyUserId.contains(userId)) { PGPPrivateKey privateKey = secKey .extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(provider) .build(passphrase.toCharArray())); if (privateKey != null) { return secKey; } } } } else { PGPPrivateKey privateKey = secKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder() .setProvider(provider).build(passphrase.toCharArray())); if (privateKey != null) { pgpSecKey = secKey; } } } } return pgpSecKey; }
From source file:org.eclipse.packagedrone.repo.signing.pgp.internal.managed.Entry.java
License:Open Source License
private void processKey(final List<ManagedKey> keys, final PGPSecretKey key) throws Exception { final String keyId = String.format("%016X", key.getKeyID()); @SuppressWarnings("unchecked") final Stream<?> s = StreamSupport .stream(Spliterators.spliteratorUnknownSize(key.getUserIDs(), Spliterator.ORDERED), false); final List<String> users = s.map(Object::toString).collect(Collectors.toList()); final int bits = key.getPublicKey().getBitStrength(); final ManagedKey mkey = new ManagedKey(keyId, users, !key.isMasterKey(), bits); keys.add(mkey);//from w ww .j a v a2 s.c om registerKey(key, users); }
From source file:org.sufficientlysecure.keychain.pgp.PgpToX509.java
License:Open Source License
/** * Creates a self-signed certificate from a PGP Secret Key. * * @param pgpSecKey PGP Secret Key (from which one can extract the public and private * keys and other attributes). * @param pgpPrivKey PGP Private Key corresponding to the Secret Key (password callbacks * should be done before calling this method) * @param subjAltNameURI optional URI to embed in the subject alternative-name * @return self-signed certificate/*from ww w .jav a 2 s . c om*/ * @throws PGPException * @throws NoSuchProviderException * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws SignatureException * @throws CertificateException * @author Bruno Harbulot */ public static X509Certificate createSelfSignedCert(PGPSecretKey pgpSecKey, PGPPrivateKey pgpPrivKey, String subjAltNameURI) throws PGPException, NoSuchProviderException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, CertificateException { // get public key from secret key PGPPublicKey pgpPubKey = pgpSecKey.getPublicKey(); // LOGGER.info("Key ID: " + Long.toHexString(pgpPubKey.getKeyID() & 0xffffffffL)); /* * The X.509 Name to be the subject DN is prepared. The CN is extracted from the Secret Key * user ID. */ Vector<DERObjectIdentifier> x509NameOids = new Vector<DERObjectIdentifier>(); Vector<String> x509NameValues = new Vector<String>(); x509NameOids.add(X509Name.O); x509NameValues.add(DN_COMMON_PART_O); x509NameOids.add(X509Name.OU); x509NameValues.add(DN_COMMON_PART_OU); for (@SuppressWarnings("unchecked") Iterator<Object> it = (Iterator<Object>) pgpSecKey.getUserIDs(); it.hasNext();) { Object attrib = it.next(); x509NameOids.add(X509Name.CN); x509NameValues.add("CryptoCall"); // x509NameValues.add(attrib.toString()); } /* * Currently unused. */ Log.d(Constants.TAG, "User attributes: "); for (@SuppressWarnings("unchecked") Iterator<Object> it = (Iterator<Object>) pgpSecKey.getUserAttributes(); it.hasNext();) { Object attrib = it.next(); Log.d(Constants.TAG, " - " + attrib + " -- " + attrib.getClass()); } X509Name x509name = new X509Name(x509NameOids, x509NameValues); Log.d(Constants.TAG, "Subject DN: " + x509name); /* * To check the signature from the certificate on the recipient side, the creation time * needs to be embedded in the certificate. It seems natural to make this creation time be * the "not-before" date of the X.509 certificate. Unlimited PGP keys have a validity of 0 * second. In this case, the "not-after" date will be the same as the not-before date. This * is something that needs to be checked by the service receiving this certificate. */ Date creationTime = pgpPubKey.getCreationTime(); Log.d(Constants.TAG, "pgp pub key creation time=" + DateFormat.getDateInstance().format(creationTime)); Log.d(Constants.TAG, "pgp valid seconds=" + pgpPubKey.getValidSeconds()); Date validTo = null; if (pgpPubKey.getValidSeconds() > 0) { validTo = new Date(creationTime.getTime() + 1000L * pgpPubKey.getValidSeconds()); } X509Certificate selfSignedCert = createSelfSignedCert( pgpPubKey.getKey(Constants.BOUNCY_CASTLE_PROVIDER_NAME), pgpPrivKey.getKey(), x509name, creationTime, validTo, subjAltNameURI); return selfSignedCert; }