List of usage examples for org.bouncycastle.openpgp PGPSecretKey getKeyID
public long getKeyID()
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Encrypt and sign the specified input file. If you pass in a seed, you * will get the same encrypted output for the same file + same seed + same signor. * //from w w w . j a v a2 s.c o m * DANGER! If you use the same seed for multiple different messages, you are * making your key stream vulnerable to hacking, and your encryption is near * meaningless! Make sure to use different seeds for different contents! * * @param seed */ public void encryptAndSignFile(String outputFilename, File inFile, InputStream publicRing, InputStream secretRing, String recipient, String signor, char[] passwd, boolean armor, boolean withIntegrityCheck, boolean oldFormat, byte[] seed) throws PGPException { try { // Get the public keyring PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(publicRing)); PGPSecretKeyRingCollection secRing = readSecretKeyRingCollection(secretRing); // Find the recipient's key PGPPublicKey encKey = readPublicKey(pubRing, recipient, true); if (encKey.isRevoked()) { String keyId = Long.toHexString(encKey.getKeyID()).substring(8); throw new PGPException("Encryption key (0x" + keyId + ") has been revoked"); } // Find the signing key PGPPublicKey publicKey; PGPSecretKey secretKey; if (signor != null) { publicKey = readPublicKey(pubRing, signor, false); secretKey = findSecretKey(secRing, publicKey.getKeyID(), true); } else { // Just look for the first signing key on the secret keyring (if any) secretKey = findSigningKey(secRing); publicKey = findPublicKey(pubRing, secretKey.getKeyID(), false); } if (publicKey.isRevoked()) { String keyId = Long.toHexString(publicKey.getKeyID()).substring(8); throw new PGPException("Signing key (0x" + keyId + ") has been revoked"); } PGPPrivateKey privateKey = secretKey.extractPrivateKey(passwd, "BC"); // Sign the data into an in-memory stream ByteArrayOutputStream bOut = new ByteArrayOutputStream(); if (oldFormat) { signDataV3(inFile, bOut, publicKey, privateKey); } else { signData(inFile, bOut, publicKey, privateKey); } SecureRandom secRand = makeSecureRandom(seed); PGPEncryptedDataGenerator cPk = oldFormat ? new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, secRand, oldFormat, "BC") : new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, withIntegrityCheck, secRand, "BC"); cPk.addMethod(encKey); byte[] bytes = bOut.toByteArray(); OutputStream out = new FileOutputStream(outputFilename); OutputStream aOut = armor ? new ArmoredOutputStream(out) : out; OutputStream cOut = cPk.open(aOut, bytes.length); cOut.write(bytes); cPk.close(); if (armor) { aOut.close(); } out.close(); } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in encryption", e); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Sign the specified file/* w ww . j av a2 s.c om*/ */ public void signFile(String outputFilename, File inFile, InputStream publicRing, InputStream secretRing, String signor, char[] passwd, boolean armor, boolean oldFormat) throws PGPException { try { PGPPublicKey publicKey; PGPSecretKey secretKey; // Get the public keyring PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(publicRing)); PGPSecretKeyRingCollection secRing = readSecretKeyRingCollection(secretRing); // Find the signing key if (signor != null) { publicKey = readPublicKey(pubRing, signor, false); secretKey = findSecretKey(secRing, publicKey.getKeyID(), true); } else { // Just look for the first signing key on the secret keyring (if any) secretKey = findSigningKey(secRing); publicKey = findPublicKey(pubRing, secretKey.getKeyID(), false); } if (publicKey.isRevoked()) { String keyId = Long.toHexString(publicKey.getKeyID()).substring(8); throw new PGPException("Signing key (0x" + keyId + ") has been revoked"); } PGPPrivateKey privateKey = secretKey.extractPrivateKey(passwd, "BC"); OutputStream out = new FileOutputStream(outputFilename); OutputStream aOut = armor ? new ArmoredOutputStream(out) : out; // Sign the data if (oldFormat) { signDataV3(inFile, aOut, publicKey, privateKey); } else { signData(inFile, aOut, publicKey, privateKey); } if (armor) { // close() just finishes and flushes the stream but does not close it aOut.close(); } out.close(); } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in signing", e); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Decrypt the specified (PKE) input file. * /*from ww w . j a va2 s . c o m*/ * Either pubRing and secRing should be null, or pgpSecKey should be null, but not both. * * @param out * @param inFile * @param pubRing * @param secRing * @param pgpSecKey * @param encKey * @param passwd * @param mdcRequired * @throws PGPException */ private void decryptKeyBasedFile(OutputStream out, InputStream inFile, PGPPublicKeyRingCollection pubRing, PGPSecretKeyRingCollection secRing, PGPSecretKey pgpSecKey, char[] passwd, boolean mdcRequired) throws PGPException { try { InputStream fileToDecrypt = PGPUtil.getDecoderStream(inFile); PGPObjectFactory pgpFact = new PGPObjectFactory(fileToDecrypt); Object message = pgpFact.nextObject(); PGPPublicKeyEncryptedData pked = null; // PGPCompressedData cData; // Check for signed only if (!(message instanceof PGPCompressedData)) { // // Encrypted - the first object might be a PGP marker packet. // if (!(message instanceof PGPEncryptedDataList)) { message = pgpFact.nextObject(); if (!(message instanceof PGPEncryptedDataList)) { throw new PGPException("Unrecognised PGP message type: " + message.getClass()); } } PGPEncryptedDataList enc = (PGPEncryptedDataList) message; int count = 0; // find the secret key that is needed while (count != enc.size()) { if (enc.get(count) instanceof PGPPublicKeyEncryptedData) { pked = (PGPPublicKeyEncryptedData) enc.get(count); if (pgpSecKey == null) { pgpSecKey = secRing.getSecretKey(pked.getKeyID()); if (pgpSecKey != null) { break; } } else { if (pgpSecKey.getKeyID() == pked.getKeyID()) { break; } } } count++; } if (pgpSecKey == null) { throw new PGPException("Corresponding secret key not found"); } // Check for revoked key PGPPublicKey encKey = pgpSecKey.getPublicKey(); if (encKey == null) { encKey = findPublicKey(pubRing, pgpSecKey.getKeyID(), true); } if (encKey.isRevoked()) { String keyId = Long.toHexString(encKey.getKeyID()).substring(8); System.out.println("Warning: Encryption key (0x" + keyId + ") has been revoked"); // throw new PGPException("Encryption key (0x"+keyId+") has been revoked"); } InputStream clear = pked.getDataStream(pgpSecKey.extractPrivateKey(passwd, "BC"), "BC"); PGPObjectFactory pgpClearFact = new PGPObjectFactory(clear); message = pgpClearFact.nextObject(); if (message == null) { message = pgpFact.nextObject(); } // // cData = (PGPCompressedData) pgpFact.nextObject(); // } // else { // cData = (PGPCompressedData) message; } if (message instanceof PGPCompressedData) { PGPCompressedData compressedData = (PGPCompressedData) message; pgpFact = new PGPObjectFactory(compressedData.getDataStream()); message = pgpFact.nextObject(); } // Plain file if (message instanceof PGPLiteralData) { PGPLiteralData ld = (PGPLiteralData) message; InputStream dataIn = ld.getInputStream(); int ch; while ((ch = dataIn.read()) >= 0) { out.write(ch); } out.close(); } else if (message instanceof PGPOnePassSignatureList) { // One-pass signature if (!checkOnePassSignature(out, (PGPOnePassSignatureList) message, pgpFact, pubRing)) { throw new PGPException("Signature verification failed"); } System.out.println("Signature verified"); } else if (message instanceof PGPSignatureList) { // Signature list if (!checkSignature(out, (PGPSignatureList) message, pgpFact, pubRing)) { throw new PGPException("Signature verification failed"); } System.out.println("Signature verified"); } else { // what? // System.out.println("Unrecognised message type"); throw new PGPException("Unrecognised PGP message type: " + message.getClass()); } if (pked != null) { if (pked.isIntegrityProtected()) { if (!pked.verify()) { throw new PGPException("Message failed integrity check"); } if (_verbose) { System.out.println("Message integrity check passed"); } } else { if (_verbose) { System.out.println("No message integrity check"); } if (mdcRequired) { throw new PGPException("Missing required message integrity check"); } } } } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in decryption", e); } }
From source file:com.github.sannies.nexusaptplugin.sign.PGPSigner.java
License:Apache License
/** * Returns the secret key matching the specified identifier. * /* w ww. j av a 2 s .co m*/ * @param input the input stream containing the keyring collection * @param keyId the 4 bytes identifier of the key */ private PGPSecretKey getSecretKey(InputStream input, String keyId) throws IOException, PGPException { PGPSecretKeyRingCollection keyrings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input)); Iterator rIt = keyrings.getKeyRings(); while (rIt.hasNext()) { PGPSecretKeyRing kRing = (PGPSecretKeyRing) rIt.next(); Iterator kIt = kRing.getSecretKeys(); while (kIt.hasNext()) { PGPSecretKey key = (PGPSecretKey) kIt.next(); if (key.isSigningKey() && Long.toHexString(key.getKeyID() & 0xFFFFFFFFL).equals(keyId.toLowerCase())) { return key; } } } return null; }
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 ww .ja v a 2 s . c o m*/ * @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.lyndir.lhunath.opal.crypto.gpg.GPG.java
License:Apache License
/** * Decrypt a PGP encrypted stream./*from w ww . ja v a 2 s .c o m*/ * * @param encryptedStream The stream that contains the encrypted data. * @param privateKey The private key to use for decrypting the data. * @param passPhrase The passphrase the private key is encrypted with. * * @return The plain-text stream. * * @throws NoSuchProviderException * @throws IOException * @throws PGPException */ public static InputStream decrypt(final InputStream encryptedStream, final PGPSecretKey privateKey, final String passPhrase) throws IOException, PGPException, NoSuchProviderException { /* Open the encrypted file. */ InputStream encryptedDataStream = PGPUtil.getDecoderStream(encryptedStream); PGPObjectFactory encryptedDataFactory = new PGPObjectFactory(encryptedDataStream); /* Find the PGP encrypted data. */ Object encryptedDataObjects = null; do try { encryptedDataObjects = encryptedDataFactory.nextObject(); } catch (final IOException e) { logger.warn(e.getMessage()); } while (!(encryptedDataObjects instanceof PGPEncryptedDataList) && encryptedDataObjects != null); if (encryptedDataObjects == null) throw new PGPException("No encrypted objects found."); @SuppressWarnings("unchecked") Iterator<PGPPublicKeyEncryptedData> encryptedDataIterator = ((PGPEncryptedDataList) encryptedDataObjects) .getEncryptedDataObjects(); /* Extract the public key out of the data and find the matching private key required to decrypt the data. */ PGPPublicKeyEncryptedData encryptedData = null; while (encryptedDataIterator.hasNext()) { encryptedData = encryptedDataIterator.next(); if (encryptedData.getKeyID() == privateKey.getKeyID()) break; } if (encryptedData == null) throw new PGPException("No encrypted data found."); /* Decrypt the data. */ InputStream unencryptedStream = encryptedData.getDataStream( privateKey.extractPrivateKey(passPhrase.toCharArray(), BouncyCastleProvider.PROVIDER_NAME), BouncyCastleProvider.PROVIDER_NAME); PGPObjectFactory pgpFactory = new PGPObjectFactory(unencryptedStream); Object unencryptedObject = pgpFactory.nextObject(); /* Possibly decompress the decrypted data. */ if (unencryptedObject instanceof PGPCompressedData) { PGPCompressedData compressedData = (PGPCompressedData) unencryptedObject; pgpFactory = new PGPObjectFactory(compressedData.getDataStream()); unencryptedObject = pgpFactory.nextObject(); } /* Verify integrity. */ if (encryptedData.isIntegrityProtected() && !encryptedData.verify()) throw new PGPException("Message integrity check failed."); /* Check to see if the data is valid decrypted data. */ if (unencryptedObject == null) throw new PGPException("No encrypted data found."); if (unencryptedObject instanceof PGPOnePassSignatureList) throw new PGPException("Encrypted data is a signature, not an encrypted message."); if (!(unencryptedObject instanceof PGPLiteralData)) throw new PGPException("Message type unrecognized: " + unencryptedObject.getClass()); /* Write out decrypted data. */ PGPLiteralData unencryptedData = (PGPLiteralData) unencryptedObject; return unencryptedData.getInputStream(); }
From source file:de.dentrassi.pm.signing.pgp.PgpHelper.java
License:Open Source License
public static PGPSecretKey loadSecretKey(final InputStream input, final String keyId) throws IOException, PGPException { final long keyIdNum = Long.parseUnsignedLong(keyId, 16); final BcPGPSecretKeyRingCollection keyrings = new BcPGPSecretKeyRingCollection( PGPUtil.getDecoderStream(input)); final Iterator<?> keyRingIter = keyrings.getKeyRings(); while (keyRingIter.hasNext()) { final PGPSecretKeyRing secretKeyRing = (PGPSecretKeyRing) keyRingIter.next(); final Iterator<?> secretKeyIterator = secretKeyRing.getSecretKeys(); while (secretKeyIterator.hasNext()) { final PGPSecretKey key = (PGPSecretKey) secretKeyIterator.next(); if (!key.isSigningKey()) { continue; }/*from ww w . j a v a 2 s . c om*/ final long shortId = key.getKeyID() & 0xFFFFFFFFL; if (key.getKeyID() != keyIdNum && shortId != keyIdNum) { continue; } return key; } } return null; }
From source file:de.softwareforge.pgpsigner.key.PublicKey.java
License:Apache License
public boolean isSignedWith(final SecretKey signKey) { if (signKey == null) { return false; }/*from ww w.ja v a 2 s. c o m*/ PGPSecretKey pgpSecretKey = signKey.getPGPSecretKey(); for (Iterator it = pgpPublicKey.getSignatures(); it.hasNext();) { PGPSignature sig = (PGPSignature) it.next(); if (pgpSecretKey.getKeyID() == sig.getKeyID()) { return true; } } return false; }
From source file:de.softwareforge.pgpsigner.key.SecretKey.java
License:Apache License
public SecretKey(final PGPSecretKey pgpSecretKey) { super(pgpSecretKey.getKeyID()); this.pgpSecretKey = pgpSecretKey; }
From source file:net.pgp2p.cryptoservice.PGPManager.java
License:Open Source License
/** * A simple routine that opens a key ring file and loads the first available key suitable for * signature generation.// www . j a v a 2 s . c om * * @param in * @return * @throws IOException * @throws PGPException */ public PGPSecretKey getSecretKey() { PGPSecretKey secKey = this.secretKeyRing.getSecretKey(); logger.log(Level.FINE, "Returning private key " + Long.toHexString(secKey.getKeyID())); return secKey; }