List of usage examples for org.bouncycastle.openpgp PGPOnePassSignatureList size
public int size()
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Check a one-pass signature/* w ww . j a v a2 s. c o m*/ */ private boolean checkOnePassSignature(OutputStream out, PGPOnePassSignatureList p1, PGPObjectFactory pgpFact, PGPPublicKeyRingCollection pgpRing) throws PGPException { try { PGPOnePassSignature ops = null; PGPPublicKey key = null; int count = 0; while (count < p1.size()) { ops = p1.get(count); key = pgpRing.getPublicKey(ops.getKeyID()); if (key != null) { break; } count++; } if (key == null) { throw new PGPException("Corresponding public key not found"); } if (key.isRevoked()) { String keyId = Long.toHexString(key.getKeyID()).substring(8); System.out.println("Warning: Signing key (0x" + keyId + ") has been revoked"); // throw new PGPException("Signing key (0x"+keyId+") has been revoked"); } PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject(); // if (outputFilename == null) { // outputFilename = ld.getFileName(); // } // // FileOutputStream out = new FileOutputStream(outputFilename); InputStream dataIn = ld.getInputStream(); ops.initVerify(key, "BC"); int ch; while ((ch = dataIn.read()) >= 0) { ops.update((byte) ch); out.write(ch); } out.close(); PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject(); return ops.verify(p3.get(0)); } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in verification", e); } }
From source file:com.google.e2e.bcdriver.Decryptor.java
License:Apache License
private static final Result verifySignedContent(InputStream inp, KeyChecker.PKR verify) throws IOException, PGPException, SignatureException { PGPObjectFactory plainFact = new PGPObjectFactory(inp, new BcKeyFingerprintCalculator()); Object msg = plainFact.nextObject(); // swap in uncompressed data if necessary if (msg instanceof PGPCompressedData) { PGPCompressedData cData = (PGPCompressedData) msg; plainFact = new PGPObjectFactory(cData.getDataStream(), new BcKeyFingerprintCalculator()); msg = plainFact.nextObject();/*w ww .j a v a2 s. c o m*/ } PGPOnePassSignatureList onePassSigList; PGPLiteralData lData; if (msg instanceof PGPOnePassSignatureList) { onePassSigList = (PGPOnePassSignatureList) msg; lData = (PGPLiteralData) plainFact.nextObject(); } else { onePassSigList = null; lData = (PGPLiteralData) msg; } if ((verify != null) && (onePassSigList == null)) { throw new IOException("Message is unsigned"); } PGPOnePassSignature onePassSig = null; int onePassStartIndex = -1; PGPPublicKey verifyKey = null; if (verify != null) { for (int i = 0; i < onePassSigList.size(); i++) { List<PGPPublicKey> candidates = verify.getSigningKeysByKeyID(onePassSigList.get(i).getKeyID()); if (candidates.size() == 1) { onePassSig = onePassSigList.get(i); onePassStartIndex = i; verifyKey = candidates.get(0); break; } } } if ((verify != null) && (onePassSig == null)) { throw new IOException("Failed to find a signature from verifying key"); } if (onePassSig != null) { onePassSig.init(new BcPGPContentVerifierBuilderProvider(), verifyKey); } ByteArrayOutputStream baout = new ByteArrayOutputStream(); InputStream lin = lData.getInputStream(); byte buf[] = new byte[8192]; int nread; while ((nread = lin.read(buf)) > 0) { baout.write(buf, 0, nread); if (onePassSig != null) { onePassSig.update(buf, 0, nread); } } baout.close(); if (onePassSig != null) { PGPSignatureList sigList = (PGPSignatureList) plainFact.nextObject(); // One pass signature trailers occur in LIFO order compared to their // location in the header. PGPSignature sig = sigList.get(sigList.size() - 1 - onePassStartIndex); if (!onePassSig.verify(sig)) { throw new IOException("Invalid signature in message"); } } return new Result(baout.toByteArray(), lData.getFileName()); }
From source file:google.registry.rde.BouncyCastleTest.java
License:Open Source License
@Test public void testSignVerify_OnePass() throws Exception { // Load the keys. PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY); PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY); PGPPublicKey publicKey = publicKeyRing.getPublicKey(); PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey()); // Sign the data and write signature data to "signatureFile". PGPSignatureGenerator signer = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256)); signer.init(PGPSignature.BINARY_DOCUMENT, privateKey); addUserInfoToSignature(publicKey, signer); ByteArrayOutputStream output = new ByteArrayOutputStream(); signer.generateOnePassVersion(false).encode(output); signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); signer.generate().encode(output);/*from w w w. ja v a 2 s.c o m*/ byte[] signatureFileData = output.toByteArray(); logger.info(".sig file data: " + dumpHex(signatureFileData)); // Load algorithm information and signature data from "signatureFileData". PGPSignature sig; PGPOnePassSignature onePass; try (ByteArrayInputStream input = new ByteArrayInputStream(signatureFileData)) { PGPObjectFactory pgpFact = new BcPGPObjectFactory(input); PGPOnePassSignatureList onePassList = (PGPOnePassSignatureList) pgpFact.nextObject(); PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject(); assertThat(onePassList.size()).isEqualTo(1); assertThat(sigList.size()).isEqualTo(1); onePass = onePassList.get(0); sig = sigList.get(0); } // Use "onePass" and "sig" to verify "publicKey" signed the text. onePass.init(new BcPGPContentVerifierBuilderProvider(), publicKey); onePass.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); assertThat(onePass.verify(sig)).isTrue(); // Verify that they DIDN'T sign the text "hello monster". onePass.init(new BcPGPContentVerifierBuilderProvider(), publicKey); onePass.update("hello monster".getBytes(UTF_8)); assertThat(onePass.verify(sig)).isFalse(); }
From source file:org.apache.camel.converter.crypto.PGPDataFormat.java
License:Apache License
protected PGPOnePassSignature getSignature(Exchange exchange, PGPOnePassSignatureList signatureList) throws IOException, PGPException, NoSuchProviderException { for (int i = 0; i < signatureList.size(); i++) { PGPOnePassSignature signature = signatureList.get(i); // Determine public key from signature keyId PGPPublicKey sigPublicKey = PGPDataFormatUtil.findPublicKeyWithKeyId(exchange.getContext(), findSignatureKeyFileName(exchange), findSignatureKeyRing(exchange), signature.getKeyID(), false);/*from w w w . j a va2s . c o m*/ 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( "No public key found fitting to the signature key Id; cannot verify the signature"); } }
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; }// w w w.jav a 2 s .co 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.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;// w w w.j a v a 2 s. c o m 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
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 {// w w w .j av a 2 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..."); } } }