List of usage examples for org.bouncycastle.openpgp PGPOnePassSignatureList get
public PGPOnePassSignature get(int index)
From source file:org.apache.camel.converter.crypto.PGPKeyAccessDataFormat.java
License:Apache License
protected PGPOnePassSignature getSignature(Exchange exchange, PGPOnePassSignatureList signatureList) throws Exception { if (SIGNATURE_VERIFICATION_OPTION_IGNORE.equals(getSignatureVerificationOption())) { return null; }/*from www . jav a 2 s .c o m*/ if (SIGNATURE_VERIFICATION_OPTION_NO_SIGNATURE_ALLOWED.equals(getSignatureVerificationOption())) { throw new PGPException( "PGP message contains a signature although a signature is not expected. Either change the configuration of the PGP decryptor or send a PGP message with no signature."); } List<String> allowedUserIds = determineSignaturenUserIds(exchange); for (int i = 0; i < signatureList.size(); i++) { PGPOnePassSignature signature = signatureList.get(i); // Determine public key from signature keyId PGPPublicKey sigPublicKey = publicKeyAccessor.getPublicKey(exchange, signature.getKeyID(), allowedUserIds); if (sigPublicKey == null) { continue; } // choose that signature for which a public key exists! signature.init(new JcaPGPContentVerifierBuilderProvider().setProvider(getProvider()), sigPublicKey); return signature; } if (signatureList.isEmpty()) { return null; } else { throw new IllegalArgumentException( "Cannot verify the PGP signature: No public key found for the key ID(s) contained in the PGP signature(s). " + "Either the received PGP message contains a signature from an unexpected sender or the Public Keyring does not contain the public key of the sender."); } }
From source file:org.brownsocks.payments.gateways.enets.pgp.BCPGPProvider.java
@Override public String decryptAndVerify(String messageIn) throws IOException, SignatureVerificationException { try {/* w ww . ja v a2 s . com*/ /* Stage zero: Convert to ASCII armored format and open a decoding stream */ InputStream is = new ByteArrayInputStream(Base64.decode(messageIn)); InputStream decoderStream = PGPUtil.getDecoderStream(is); /* Stage one: Init a decrypting stream */ PGPObjectFactory pgpFactory = new PGPObjectFactory(decoderStream); PGPEncryptedDataList cryptedDataList = (PGPEncryptedDataList) pgpFactory.nextObject(); PGPPublicKeyEncryptedData cryptedData = (PGPPublicKeyEncryptedData) cryptedDataList.get(0); InputStream clearStream = cryptedData.getDataStream(getCryptingPrivateKey(), _provider); /* Stage two: Seperate the XML data from the signatures */ PGPObjectFactory plainFact = new PGPObjectFactory(clearStream); PGPOnePassSignatureList onePassSignatureList = (PGPOnePassSignatureList) plainFact.nextObject(); PGPLiteralData literalData = (PGPLiteralData) plainFact.nextObject(); String xmlMessage = IOUtils.toString(literalData.getInputStream()); PGPSignatureList signatureList = (PGPSignatureList) plainFact.nextObject(); /* Stage three: Verify signature */ PGPOnePassSignature ops = onePassSignatureList.get(0); PGPPublicKey key = _remotePublicKeyRing.getPublicKey(ops.getKeyID()); ops.initVerify(key, _provider); ops.update(xmlMessage.getBytes()); if (!ops.verify(signatureList.get(0))) { throw new SignatureVerificationException( "Failed to verify message signature. Message authenticity cannot be thrusted."); } return xmlMessage; } catch (PGPException pgpException) { throw new IOException("PGP subsystem problem.", pgpException); } catch (SignatureException signException) { throw new IOException("PGP subsystem problem.", signException); } catch (Throwable t) { throw new IOException("Unknown error occured in PGP subsystem: " + t.getMessage(), t); } }
From source file:org.kontalk.crypto.Coder.java
License:Open Source License
private static DecryptionResult decryptAndVerify(InputStream encryptedStream, PersonalKey myKey, PGPPublicKey senderKey) {/*from w w w. j a v a 2 s .c o m*/ // note: the signature is inside the encrypted data DecryptionResult result = new DecryptionResult(); PGPObjectFactory pgpFactory = new PGPObjectFactory(encryptedStream); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { // catch all IO and PGP exceptions // the first object might be a PGP marker packet Object o = pgpFactory.nextObject(); // nullable if (!(o instanceof PGPEncryptedDataList)) { o = pgpFactory.nextObject(); // nullable } if (!(o instanceof PGPEncryptedDataList)) { LOGGER.warning("can't find encrypted data list in data"); result.errors.add(Error.INVALID_DATA); return result; } PGPEncryptedDataList encDataList = (PGPEncryptedDataList) o; // check if secret key matches our encryption keyID Iterator<?> it = encDataList.getEncryptedDataObjects(); PGPPrivateKey sKey = null; PGPPublicKeyEncryptedData pbe = null; long myKeyID = myKey.getPrivateEncryptionKey().getKeyID(); while (sKey == null && it.hasNext()) { Object i = it.next(); if (!(i instanceof PGPPublicKeyEncryptedData)) continue; pbe = (PGPPublicKeyEncryptedData) i; if (pbe.getKeyID() == myKeyID) sKey = myKey.getPrivateEncryptionKey(); } if (sKey == null || pbe == null) { LOGGER.warning("private key for message not found"); result.errors.add(Error.INVALID_PRIVATE_KEY); return result; } InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey)); PGPObjectFactory plainFactory = new PGPObjectFactory(clear); Object object = plainFactory.nextObject(); // nullable if (!(object instanceof PGPCompressedData)) { LOGGER.warning("data packet not compressed"); result.errors.add(Error.INVALID_DATA); return result; } PGPCompressedData cData = (PGPCompressedData) object; PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream()); object = pgpFact.nextObject(); // nullable // the first object could be the signature list // get signature from it PGPOnePassSignature ops = null; if (object instanceof PGPOnePassSignatureList) { PGPOnePassSignatureList signatureList = (PGPOnePassSignatureList) object; // there is a signature list, so we assume the message is signed // (makes sense) result.signing = Signing.SIGNED; if (signatureList.isEmpty()) { LOGGER.warning("signature list is empty"); result.errors.add(Error.INVALID_SIGNATURE_DATA); } else { ops = signatureList.get(0); ops.init(new BcPGPContentVerifierBuilderProvider(), senderKey); } object = pgpFact.nextObject(); // nullable } else { LOGGER.warning("signature list not found"); result.signing = Signing.NOT; } if (!(object instanceof PGPLiteralData)) { LOGGER.warning("unknown packet type: " + object.getClass().getName()); result.errors.add(Error.INVALID_DATA); return result; } PGPLiteralData ld = (PGPLiteralData) object; InputStream unc = ld.getInputStream(); int ch; while ((ch = unc.read()) >= 0) { outputStream.write(ch); if (ops != null) try { ops.update((byte) ch); } catch (SignatureException ex) { LOGGER.log(Level.WARNING, "can't read signature", ex); } } result.decryptedStream = Optional.of(outputStream); if (ops != null) { result = verifySignature(result, pgpFact, ops); } // verify message integrity if (pbe.isIntegrityProtected()) { if (!pbe.verify()) { LOGGER.warning("message integrity check failed"); result.errors.add(Error.INVALID_INTEGRITY); } } else { LOGGER.warning("message is not integrity protected"); result.errors.add(Error.NO_INTEGRITY); } } catch (IOException | PGPException ex) { LOGGER.log(Level.WARNING, "can't decrypt message", ex); result.errors.add(Error.UNKNOWN_ERROR); } return result; }
From source file:org.mule.module.pgp.DecryptStreamTransformer.java
License:Open Source License
/** * {@inheritDoc}//from w w w . jav a2 s . c om */ @Override public void initialize(OutputStream out) throws Exception { InputStream decodedInputStream = PGPUtil.getDecoderStream(this.toBeDecrypted); PGPObjectFactory pgpF = new PGPObjectFactory(decodedInputStream); Object o = pgpF.nextObject(); if (o == null) { throw new IllegalArgumentException("Invalid PGP message"); } // the first object might be a PGP marker packet. PGPEncryptedDataList enc; if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpF.nextObject(); } // This loop looks like it is ready for multiple encrypted // objects, but really only one is expected. Iterator<?> it = enc.getEncryptedDataObjects(); PGPPublicKeyEncryptedData pbe = null; PGPPrivateKey privateKey = null; while (privateKey == null && it.hasNext()) { pbe = (PGPPublicKeyEncryptedData) it.next(); privateKey = getPrivateKey(pbe.getKeyID(), this.password); if (privateKey == null) { throw new IllegalArgumentException("Failed to find private key with ID " + pbe.getKeyID()); } } clearStream = pbe.getDataStream(privateKey, "BC"); PGPObjectFactory plainFact = new PGPObjectFactory(clearStream); o = plainFact.nextObject(); PGPOnePassSignature signature = null; if (o instanceof PGPOnePassSignatureList) { PGPOnePassSignatureList list = (PGPOnePassSignatureList) o; signature = list.get(0); signature.initVerify(this.publicKey, "BC"); // TODO verify signature // signature.verify(null); o = plainFact.nextObject(); } compressedStream = null; if (o instanceof PGPCompressedData) { PGPCompressedData cData = (PGPCompressedData) o; compressedStream = new BufferedInputStream(cData.getDataStream()); PGPObjectFactory pgpFact = new PGPObjectFactory(compressedStream); Object streamData = pgpFact.nextObject(); o = streamData; } if (o instanceof PGPLiteralData) { PGPLiteralData ld = (PGPLiteralData) o; uncStream = ld.getInputStream(); } else { throw new PGPException("input is not PGPLiteralData - type unknown."); } }
From source file:org.opentestsystem.delivery.testreg.transformer.GpgVerifier.java
License:Open Source License
public byte[] decryptAndVerify(File encryptedSignedFile) throws IOException, SignatureException, PGPException { byte[] output = null; InputStream in = PGPUtil.getDecoderStream(new FileInputStream(encryptedSignedFile)); InputStream publicKeyIn = encryptor.getStreamForPath(publicKeyringLocation); ByteArrayOutputStream fOut = new ByteArrayOutputStream(); PGPObjectFactory pgpF = new PGPObjectFactory(in); PGPEncryptedDataList enc;//from w w w.j a v a2 s . com Object o = pgpF.nextObject(); // // the first object might be a PGP marker packet. // while (!(o instanceof PGPEncryptedDataList)) { o = pgpF.nextObject(); } if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpF.nextObject(); } // // find the secret key // Iterator<?> it = enc.getEncryptedDataObjects(); PGPPrivateKey sKey = null; PGPPublicKeyEncryptedData pbe = null; while (sKey == null && it.hasNext()) { pbe = (PGPPublicKeyEncryptedData) it.next(); InputStream secretKeyringInputStream = encryptor.getStreamForPath(secretKeyringLocation); PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(secretKeyringInputStream)); PGPSecretKey pgpSecKey = pgpSec.getSecretKey(pbe.getKeyID()); if (pgpSecKey == null) { fail("could not find secret key"); } PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder( new BcPGPDigestCalculatorProvider()).build(LANDINGZONE_PASS); sKey = pgpSecKey.extractPrivateKey(decryptor); } if (sKey == null) { throw new IllegalArgumentException("secret key for message not found."); } InputStream clear = pbe .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey)); PGPObjectFactory plainFact = new PGPObjectFactory(clear); Object message = null; PGPOnePassSignatureList onePassSignatureList = null; PGPSignatureList signatureList = null; PGPCompressedData compressedData = null; message = plainFact.nextObject(); ByteArrayOutputStream actualOutput = new ByteArrayOutputStream(); while (message != null) { LOGGER.debug("decrypted message: " + message.toString()); if (message instanceof PGPCompressedData) { compressedData = (PGPCompressedData) message; plainFact = new PGPObjectFactory(compressedData.getDataStream()); message = plainFact.nextObject(); } if (message instanceof PGPLiteralData) { // have to read it and keep it somewhere. Streams.pipeAll(((PGPLiteralData) message).getInputStream(), actualOutput); } else if (message instanceof PGPOnePassSignatureList) { onePassSignatureList = (PGPOnePassSignatureList) message; } else if (message instanceof PGPSignatureList) { signatureList = (PGPSignatureList) message; } else { throw new PGPException("message unknown message type."); } message = plainFact.nextObject(); } actualOutput.close(); PGPPublicKey publicKey = null; output = actualOutput.toByteArray(); if (onePassSignatureList == null || signatureList == null) { throw new PGPException("Signatures not found."); } else { for (int i = 0; i < onePassSignatureList.size(); i++) { PGPOnePassSignature ops = onePassSignatureList.get(0); LOGGER.debug("verifier : " + ops.getKeyID()); PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(publicKeyIn)); publicKey = pgpRing.getPublicKey(ops.getKeyID()); if (publicKey != null) { ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey); ops.update(output); PGPSignature signature = signatureList.get(i); // apparently the signature can only be verified once?? if the verify method is called a 2nd time it // will fail boolean signatureVerified = ops.verify(signature); assertThat(signatureVerified, is(true)); if (signatureVerified) { Iterator<?> userIds = publicKey.getUserIDs(); while (userIds.hasNext()) { String userId = (String) userIds.next(); LOGGER.debug("Signed by " + userId); } LOGGER.debug("Signature verified"); } else { throw new SignatureException("Signature verification failed"); } } } } if (pbe.isIntegrityProtected() && !pbe.verify()) { throw new PGPException("Data is integrity protected but integrity is lost."); } else if (publicKey == null) { throw new SignatureException("Signature not found"); } else { fOut.write(output); fOut.flush(); fOut.close(); LOGGER.debug("decrypt and verify output: " + fOut.toString()); } return output; }
From source file:org.sufficientlysecure.keychain.pgp.PgpSignatureChecker.java
License:Open Source License
boolean initializeOnePassSignature(Object dataChunk, OperationLog log, int indent) throws PGPException { if (!(dataChunk instanceof PGPOnePassSignatureList)) { return false; }/* w w w.jav a 2 s . com*/ log.add(LogType.MSG_DC_CLEAR_SIGNATURE, indent + 1); PGPOnePassSignatureList sigList = (PGPOnePassSignatureList) dataChunk; findAvailableSignature(sigList); if (signingKey != null) { // key found in our database! signatureResultBuilder.initValid(signingKey); JcaPGPContentVerifierBuilderProvider contentVerifierBuilderProvider = new JcaPGPContentVerifierBuilderProvider() .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); onePassSignature.init(contentVerifierBuilderProvider, signingKey.getPublicKey()); checkKeySecurity(log, indent); } else if (!sigList.isEmpty()) { signatureResultBuilder.setSignatureAvailable(true); signatureResultBuilder.setKnownKey(false); signatureResultBuilder.setKeyId(sigList.get(0).getKeyID()); } return true; }
From source file:org.sufficientlysecure.keychain.pgp.PgpSignatureChecker.java
License:Open Source License
private void findAvailableSignature(PGPOnePassSignatureList sigList) { // go through all signatures (should be just one), make sure we have // the key and it matches the one were looking for for (int i = 0; i < sigList.size(); ++i) { try {//from w w w . ja v a2 s .c o m long sigKeyId = sigList.get(i).getKeyID(); CanonicalizedPublicKeyRing signingRing = mProviderHelper .getCanonicalizedPublicKeyRing(KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(sigKeyId)); CanonicalizedPublicKey keyCandidate = signingRing.getPublicKey(sigKeyId); if (!keyCandidate.canSign()) { continue; } signatureIndex = i; signingKey = keyCandidate; onePassSignature = sigList.get(i); return; } catch (ProviderHelper.NotFoundException e) { Log.d(Constants.TAG, "key not found, trying next signature..."); } } }