private void test11() throws Exception { PGPPublicKeyRing pubRing = new PGPPublicKeyRing(subKeyBindingKey, new BcKeyFingerprintCalculator()); Iterator it = pubRing.getPublicKeys(); while (it.hasNext()) { PGPPublicKey key = (PGPPublicKey)it.next(); if (key.getValidSeconds() != 0) { fail("expiration time non-zero"); } } }
private void checkSecretKeyRingWithPersonalCertificate(byte[] keyRing) throws Exception { PGPSecretKeyRingCollection secCol = new PGPSecretKeyRingCollection(keyRing, new BcKeyFingerprintCalculator()); int count = 0; for (Iterator rIt = secCol.getKeyRings(); rIt.hasNext();) { PGPSecretKeyRing ring = (PGPSecretKeyRing)rIt.next(); for (Iterator it = ring.getExtraPublicKeys(); it.hasNext();) { it.next(); count++; } } if (count != 1) { fail("personal certificate data subkey not found - count = " + count); } }
public PGPPublicKey getKey(long keyID) throws IOException, PGPException { File keyFile = null; PGPPublicKey key = null; try { String path = String.format("%02X/%02X/%016X.asc", (byte) (keyID >> 56), (byte) (keyID >> 48 & 0xff), keyID); keyFile = new File(cachePath, path); if (!keyFile.exists()) { receiveKey(keyFile, keyID); } InputStream keyIn = PGPUtil.getDecoderStream(new FileInputStream(keyFile)); PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(keyIn, new BcKeyFingerprintCalculator()); key = pgpRing.getPublicKey(keyID); } finally { if (key == null) { deleteFile(keyFile); } } return key; }
static PGPSecretKey readSecretKey() throws Exception { InputStream input = new ByteArrayInputStream(getSecKeyRing()); PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); @SuppressWarnings("rawtypes") Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next(); @SuppressWarnings("rawtypes") Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { PGPSecretKey key = (PGPSecretKey) keyIter.next(); if (key.isSigningKey()) { return key; } } } throw new IllegalArgumentException("Can't find signing key in key ring."); }
static PGPPublicKey readPublicKey(String keyringPath) throws Exception { InputStream input = new ByteArrayInputStream(getKeyRing(keyringPath)); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); @SuppressWarnings("rawtypes") Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); @SuppressWarnings("rawtypes") Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("Can't find encryption key in key ring."); }
/** * reads the public key ring from the input stream * * @param publicKey * the public key stream * @return the public key ring */ protected PGPPublicKeyRing readPublicKeyRing(InputStream publicKey) { LOGGER.trace("readPublicKeyRing(InputStream)"); PGPPublicKeyRing result = null; LOGGER.debug("Wrapping public key stream in decoder stream"); try( InputStream decoderStream = PGPUtil.getDecoderStream(publicKey) ) { LOGGER.debug("Creating PGP Object Factory"); PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(decoderStream, new BcKeyFingerprintCalculator()); Object o = null; LOGGER.debug("Looking up PGP Public KeyRing"); while( (o = pgpObjectFactory.nextObject()) != null && result == null ) { if( o instanceof PGPPublicKeyRing ) { LOGGER.info("PGP Public KeyRing retrieved"); result = (PGPPublicKeyRing)o; } } } catch (IOException e) { LOGGER.error("{}", e.getMessage()); } return result; }
/** * Verify a PGP signature. * * @param file the file * @param signature the signature * @param key the public key * @return true if the signature is verified * @throws Exception anything preventing the verification to happen */ public static boolean verifySignature( InputStream file, InputStream signature, PGPPublicKey key) throws Exception { InputStream sigInputStream = PGPUtil.getDecoderStream(signature); PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(sigInputStream, new BcKeyFingerprintCalculator()); PGPSignatureList sigList = (PGPSignatureList) pgpObjectFactory.nextObject(); PGPSignature pgpSignature = sigList.get(0); pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), key); try (InputStream inArtifact = new BufferedInputStream(file)) { int t; while ((t = inArtifact.read()) >= 0) { pgpSignature.update((byte) t); } } return pgpSignature.verify(); }
private void testExpiry( byte[] encodedRing, int masterDays, int subKeyDays) throws Exception { PGPPublicKeyRing pubRing = new PGPPublicKeyRing(encodedRing, new BcKeyFingerprintCalculator()); PGPPublicKey k = pubRing.getPublicKey(); if (k.getValidDays() != masterDays) { fail("mismatch on master valid days."); } Iterator it = pubRing.getPublicKeys(); it.next(); k = (PGPPublicKey)it.next(); if (k.getValidDays() != subKeyDays) { fail("mismatch on subkey valid days."); } }
PGPPublicKey getKey(long keyID) throws IOException, PGPException { File keyFile = null; PGPPublicKey key = null; try { String path = String.format("%02X/%02X/%016X.asc", (byte) (keyID >> 56), (byte) (keyID >> 48 & 0xff), keyID); keyFile = new File(cachePath, path); if (!keyFile.exists()) { receiveKey(keyFile, keyID); } InputStream keyIn = PGPUtil.getDecoderStream(new FileInputStream(keyFile)); PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(keyIn, new BcKeyFingerprintCalculator()); key = pgpRing.getPublicKey(keyID); } finally { if (key == null) { deleteFile(keyFile); } } return key; }
private static PGPLiteralData asLiteral( final byte[] data, final InputStream keyfile, final String passphrase) throws IOException, PGPException { PGPPrivateKey key = null; PGPPublicKeyEncryptedData encrypted = null; final PGPSecretKeyRingCollection keys = new PGPSecretKeyRingCollection(new ArmoredInputStream(keyfile), new BcKeyFingerprintCalculator()); for (final Iterator<PGPPublicKeyEncryptedData> i = getEncryptedObjects(data); key == null && i.hasNext();) { encrypted = i.next(); key = findSecretKey(keys, encrypted.getKeyID(), passphrase); } if (key == null) { throw new IllegalArgumentException("secret key for message not found."); } final InputStream stream = encrypted.getDataStream( new JcePublicKeyDataDecryptorFactoryBuilder() .setProvider(PROVIDER) .build(key)); return asLiteral(stream); }
private static PGPLiteralData asLiteral(final InputStream clear) throws IOException, PGPException { BcKeyFingerprintCalculator bcKeyFingerprintCalculator = new BcKeyFingerprintCalculator(); final PGPObjectFactory plainFact = new PGPObjectFactory(clear, bcKeyFingerprintCalculator); final Object message = plainFact.nextObject(); if (message instanceof PGPCompressedData) { final PGPCompressedData cData = (PGPCompressedData) message; final PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream(), bcKeyFingerprintCalculator); // Find the first PGPLiteralData object Object object = null; for (int safety = 0; safety++ < 1000 && !(object instanceof PGPLiteralData); object = pgpFact.nextObject()) { } return (PGPLiteralData) object; } else if (message instanceof PGPLiteralData) { return (PGPLiteralData) message; } else if (message instanceof PGPOnePassSignatureList) { throw new PGPException("encrypted message contains a signed message - not literal data."); } else { throw new PGPException("message is not a simple encrypted file - type unknown: " + message.getClass().getName()); } }
private PGPSignatureList readSignatureFile(final File signatureFile) throws PGPVerifyException { AssertUtil.assertNotNull(signatureFile, "signatureFile"); if (!signatureFile.isFile() || !signatureFile.canRead()) throw new PGPVerifyException("The signature-file does not exist or is not readable: " + signatureFile.getAbsolutePath()); try { final InputStream in = new BufferedInputStream(castStream(signatureFile.createInputStream())); try { final PGPObjectFactory objectFactory = new PGPObjectFactory( PGPUtil.getDecoderStream(in), new BcKeyFingerprintCalculator()); final PGPSignatureList sl = (PGPSignatureList) objectFactory.nextObject(); return sl; } finally { in.close(); } } catch (final Exception e) { throw new PGPVerifyException(signatureFile.getAbsolutePath() + ": " + e, e); } }
public void test6() throws Exception { PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection(pub6, new BcKeyFingerprintCalculator()); Iterator rIt = pubRings.getKeyRings(); while (rIt.hasNext()) { PGPPublicKeyRing pgpPub = (PGPPublicKeyRing)rIt.next(); Iterator it = pgpPub.getPublicKeys(); while (it.hasNext()) { PGPPublicKey k = (PGPPublicKey)it.next(); if (k.getKeyID() == 0x5ce086b5b5a18ff4L) { int count = 0; Iterator sIt = k.getSignaturesOfType(PGPSignature.SUBKEY_REVOCATION); while (sIt.hasNext()) { PGPSignature sig = (PGPSignature)sIt.next(); count++; } if (count != 1) { fail("wrong number of revocations in test6."); } } } } byte[] encRing = pubRings.getEncoded(); }
private void rewrapTest() throws Exception { SecureRandom rand = new SecureRandom(); // Read the secret key rings PGPSecretKeyRingCollection privRings = new PGPSecretKeyRingCollection( new ByteArrayInputStream(rewrapKey), new BcKeyFingerprintCalculator()); Iterator rIt = privRings.getKeyRings(); if (rIt.hasNext()) { PGPSecretKeyRing pgpPriv = (PGPSecretKeyRing)rIt.next(); Iterator it = pgpPriv.getSecretKeys(); while (it.hasNext()) { PGPSecretKey pgpKey = (PGPSecretKey)it.next(); // re-encrypt the key with an empty password pgpPriv = PGPSecretKeyRing.removeSecretKey(pgpPriv, pgpKey); pgpKey = PGPSecretKey.copyWithNewPassword( pgpKey, new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(rewrapPass), null); pgpPriv = PGPSecretKeyRing.insertSecretKey(pgpPriv, pgpKey); // this should succeed PGPPrivateKey privTmp = pgpKey.extractPrivateKey(null); } } }
private void testPublicKeyRingWithX509() throws Exception { checkPublicKeyRingWithX509(pubWithX509); PGPPublicKeyRing pubRing = new PGPPublicKeyRing(pubWithX509, new BcKeyFingerprintCalculator()); checkPublicKeyRingWithX509(pubRing.getEncoded()); }
private void testSecretKeyRingWithPersonalCertificate() throws Exception { checkSecretKeyRingWithPersonalCertificate(secWithPersonalCertificate); PGPSecretKeyRingCollection secRing = new PGPSecretKeyRingCollection(secWithPersonalCertificate, new BcKeyFingerprintCalculator()); checkSecretKeyRingWithPersonalCertificate(secRing.getEncoded()); }
private void checkPublicKeyRingWithX509(byte[] keyRing) throws Exception { PGPPublicKeyRing pubRing = new PGPPublicKeyRing(keyRing, new BcKeyFingerprintCalculator()); Iterator it = pubRing.getPublicKeys(); if (it.hasNext()) { PGPPublicKey key = (PGPPublicKey)it.next(); Iterator sIt = key.getSignatures(); if (sIt.hasNext()) { PGPSignature sig = (PGPSignature)sIt.next(); if (sig.getKeyAlgorithm() != 100) { fail("experimental signature not found"); } if (!areEqual(sig.getSignature(), Hex.decode("000101"))) { fail("experimental encoding check failed"); } } else { fail("no signature found"); } } else { fail("no key found"); } }
BcPrivateKey(String armoredKeyString, char[] passphrase) throws PGPKeyInitialisationException { try { PGPSecretKeyRing secKeyRing = new PGPSecretKeyRing( new ArmoredInputStream(new ByteArrayInputStream(armoredKeyString.getBytes(StandardCharsets.US_ASCII))), new BcKeyFingerprintCalculator()); PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(passphrase); ImmutableMap.Builder<Long, PGPPrivateKey> builder = ImmutableMap.builder(); List<PGPPublicKey> pubKeys = new ArrayList<>(2); for (Iterator iterator = secKeyRing.getSecretKeys(); iterator.hasNext(); ) { PGPSecretKey secretKey = (PGPSecretKey) iterator.next(); PGPPrivateKey privateKey = secretKey.extractPrivateKey(decryptor); builder.put(privateKey.getKeyID(), privateKey); pubKeys.add(secretKey.getPublicKey()); } this.secretKey = secKeyRing.getSecretKey(); this.privateKeys = builder.build(); this.privateKey = this.secretKey.extractPrivateKey(decryptor); if (pubKeys.size() >= 2) { this.publicKey = new BcPublicKey(pubKeys.get(0), pubKeys.get(1)); } else { this.publicKey = new BcPublicKey(pubKeys.get(0), pubKeys.get(0)); } } catch (PGPException | RuntimeException | IOException e) { throw new PGPKeyInitialisationException("Error instantiating a private key", e); } checkNotNull(this.secretKey); checkNotNull(this.privateKey); this.fingerprint = BcPublicKey.hexFingerprint(secretKey.getPublicKey()); }
public static BcPublicKey fromArmored(String armoredKeyString) throws PGPKeyInitialisationException { try { PGPPublicKeyRing pubKeyRing = new PGPPublicKeyRing( new ArmoredInputStream(new ByteArrayInputStream(armoredKeyString.getBytes(StandardCharsets.UTF_8))), new BcKeyFingerprintCalculator() ); if (Iterators.size(pubKeyRing.getPublicKeys()) < 1) { throw new PGPKeyInitialisationException("No keys in keyring"); } PGPPublicKey signingKey = pubKeyRing.getPublicKey(); PGPPublicKey encryptionKey; @SuppressWarnings("unchecked") List<PGPPublicKey> keys = Lists.newArrayList(pubKeyRing.getPublicKeys()); if (keys.size() == 1) { encryptionKey = signingKey; } else { encryptionKey = keys.get(1); } if (!encryptionKey.isEncryptionKey()) { throw new PGPKeyInitialisationException("Error instatiating public key: sign-only key."); } return new BcPublicKey(signingKey, encryptionKey); } catch (RuntimeException | IOException e) { throw new PGPKeyInitialisationException("Error instantiating a public key", e); } }
/** * Constructor * @param keyRingFileName * @param debug * @throws Exception */ public CryptDecryptUtil(final String keyRingFileName, final String passPhrase, final boolean debug) throws Exception { this.fingerPrintCalculator = new BcKeyFingerprintCalculator(); this.keyRing = keyRingFileName; this.enableDebugLog = debug; this.passPhrase = passPhrase; }
public static PGPPublicKeyRingCollection getPublicKeyRingCollection(CamelContext context, String filename, byte[] keyRing, boolean forEncryption) throws IOException, PGPException { InputStream is = determineKeyRingInputStream(context, filename, keyRing, forEncryption); try { return new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(is), new BcKeyFingerprintCalculator()); } finally { IOHelper.close(is); } }
private static PGPPublicKey findPublicKeyWithKeyId(InputStream input, long keyid) throws IOException, PGPException, NoSuchProviderException { PGPPublicKeyRingCollection pgpSec = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); return pgpSec.getPublicKey(keyid); }
private static List<PGPPublicKey> findPublicKeys(InputStream input, List<String> userids, boolean forEncryption) throws IOException, PGPException, NoSuchProviderException { PGPPublicKeyRingCollection pgpSec = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); return findPublicKeys(userids, forEncryption, pgpSec); }
private static List<PGPSecretKeyAndPrivateKeyAndUserId> findSecretKeysWithPrivateKeyAndUserId(InputStream keyringInput, Map<String, String> sigKeyUserId2Password, String provider) throws IOException, PGPException, NoSuchProviderException { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyringInput), new BcKeyFingerprintCalculator()); return findSecretKeysWithPrivateKeyAndUserId(sigKeyUserId2Password, provider, pgpSec); }
/** * reads the given secret key and applies the provided key filter * * @param secretKey * the secret key stream * @param keyFilter * the filter to apply on the stream * @return the secret key or null if none matches the filter acceptance criteria * @throws IOException * @throws PGPException */ protected PGPSecretKey findSecretKey(InputStream secretKey, KeyFilter<PGPSecretKey> keyFilter) throws IOException, PGPException { LOGGER.trace("findSecretKey(InputStream, KeyFilter<PGPSecretKey>)"); PGPSecretKey result = null; LOGGER.debug("Wrapping secret key stream in ArmoredInputStream"); try( InputStream armoredSecretKey = new ArmoredInputStream(secretKey) ) { LOGGER.debug("Creating PGPSecretKeyRingCollection"); PGPSecretKeyRingCollection keyRingCollection = new PGPSecretKeyRingCollection(armoredSecretKey, new BcKeyFingerprintCalculator()); result = retrieveSecretKey(keyRingCollection, keyFilter); } return result; }
public TestKey(String pubArmored, String secArmored) { this.pubArmored = pubArmored; this.secArmored = secArmored; BcKeyFingerprintCalculator fc = new BcKeyFingerprintCalculator(); try { this.pubRing = new PGPPublicKeyRing(newStream(pubArmored), fc); this.secRing = new PGPSecretKeyRing(newStream(secArmored), fc); } catch (PGPException | IOException e) { throw new AssertionError(e); } }
@Override public synchronized ImportKeysResult importKeys(IInputStream _in) { assertNotNull(_in, "in"); InputStream in = castStream(_in); final ImportKeysResult importKeysResult = new ImportKeysResult(); boolean modified = false; try { in = PGPUtil.getDecoderStream(in); final PGPObjectFactory pgpF = new PGPObjectFactory(in, new BcKeyFingerprintCalculator()); Object o; while ((o = pgpF.nextObject()) != null) { if (o instanceof PGPPublicKeyRing) modified |= importPublicKeyRing(importKeysResult, (PGPPublicKeyRing) o); else if (o instanceof PGPSecretKeyRing) modified |= importSecretKeyRing(importKeysResult, (PGPSecretKeyRing) o); else throw new IllegalStateException("Unexpected object in InputStream (only PGPPublicKeyRing and PGPSecretKeyRing are supported): " + o); } } catch (IOException | PGPException x) { throw new RuntimeException(x); } if (modified) // make sure the localRevision is incremented, even if the timestamp does not change (e.g. because the time resolution of the file system is too low). incLocalRevision(); return importKeysResult; }
public static PGPPrivateKey findSecretKey(final InputStream keyIn, final long keyID, final char[] pass) throws IOException, PGPException { final PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new BcKeyFingerprintCalculator()); final PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID); if (pgpSecKey == null) return null; final PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass); return pgpSecKey.extractPrivateKey(decryptor); }
private PGPSecretKey readSecretKey(InputStream in) throws IOException, PGPException { in = PGPUtil.getDecoderStream(in); PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(in, new BcKeyFingerprintCalculator()); PGPSecretKey key = null; Iterator<PGPSecretKeyRing> it = pgpSec.getKeyRings(); while (key == null && it.hasNext()) { PGPSecretKeyRing kRing = it.next(); Iterator<PGPSecretKey> it2 = kRing.getSecretKeys(); while (key == null && it2.hasNext()) { PGPSecretKey k = it2.next(); if (keyId == null && k.isSigningKey()) { key = k; } if (keyId != null && Long.valueOf(keyId, 16) == (k.getKeyID() & MASK)) { key = k; } } } if (key == null) { throw new IllegalArgumentException("Can't find encryption key" + (keyId != null ? " '" + keyId + "' " : " ") + "in key ring."); } return key; }