List of usage examples for org.bouncycastle.openpgp PGPObjectFactory PGPObjectFactory
public PGPObjectFactory(byte[] bytes, KeyFingerPrintCalculator fingerPrintCalculator)
From source file:bisq.desktop.main.overlays.windows.downloadupdate.BisqInstaller.java
License:Open Source License
/** * Verifies detached PGP signatures against GPG/openPGP RSA public keys. Does currently not work with openssl or JCA/JCE keys. * * @param pubKeyFile Path to file providing the public key to use * @param sigFile Path to detached signature file * @param dataFile Path to signed data file * @return {@code true} if signature is valid, {@code false} if signature is not valid * @throws Exception throws various exceptions in case something went wrong. Main reason should be that key or * signature could be extracted from the provided files due to a "bad" format.<br> * <code>FileNotFoundException, IOException, SignatureException, PGPException</code> *//* w ww .j a v a 2 s . com*/ public static VerifyStatusEnum verifySignature(File pubKeyFile, File sigFile, File dataFile) throws Exception { InputStream inputStream; int bytesRead; PGPPublicKey publicKey; PGPSignature pgpSignature; boolean result; // Read keys from file inputStream = PGPUtil.getDecoderStream(new FileInputStream(pubKeyFile)); PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection(inputStream, new JcaKeyFingerprintCalculator()); inputStream.close(); Iterator<PGPPublicKeyRing> iterator = publicKeyRingCollection.getKeyRings(); PGPPublicKeyRing pgpPublicKeyRing; if (iterator.hasNext()) { pgpPublicKeyRing = iterator.next(); } else { throw new PGPException("Could not find public keyring in provided key file"); } // Would be the solution for multiple keys in one file // Iterator<PGPPublicKey> kIt; // kIt = pgpPublicKeyRing.getPublicKeys(); // publicKey = pgpPublicKeyRing.getPublicKey(0xF5B84436F379A1C6L); // Read signature from file inputStream = PGPUtil.getDecoderStream(new FileInputStream(sigFile)); PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(inputStream, new JcaKeyFingerprintCalculator()); Object o = pgpObjectFactory.nextObject(); if (o instanceof PGPSignatureList) { PGPSignatureList signatureList = (PGPSignatureList) o; checkArgument(!signatureList.isEmpty(), "signatureList must not be empty"); pgpSignature = signatureList.get(0); } else if (o instanceof PGPSignature) { pgpSignature = (PGPSignature) o; } else { throw new SignatureException("Could not find signature in provided signature file"); } inputStream.close(); log.debug("KeyID used in signature: %X\n", pgpSignature.getKeyID()); publicKey = pgpPublicKeyRing.getPublicKey(pgpSignature.getKeyID()); // If signature is not matching the key used for signing we fail if (publicKey == null) return VerifyStatusEnum.FAIL; log.debug("The ID of the selected key is %X\n", publicKey.getKeyID()); pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey); // Read file to verify byte[] data = new byte[1024]; inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile))); while (true) { bytesRead = inputStream.read(data, 0, 1024); if (bytesRead == -1) break; pgpSignature.update(data, 0, bytesRead); } inputStream.close(); // Verify the signature result = pgpSignature.verify(); return result ? VerifyStatusEnum.OK : VerifyStatusEnum.FAIL; }
From source file:cc.arduino.contributions.GPGDetachedSignatureVerifier.java
License:Open Source License
protected boolean verify(File signedFile, File signature, File publicKey) throws IOException { FileInputStream signatureInputStream = null; FileInputStream signedFileInputStream = null; try {/*from w w w . j a va2 s . co m*/ signatureInputStream = new FileInputStream(signature); PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(signatureInputStream, new BcKeyFingerprintCalculator()); Object nextObject; try { nextObject = pgpObjectFactory.nextObject(); if (!(nextObject instanceof PGPSignatureList)) { return false; } } catch (IOException e) { return false; } PGPSignatureList pgpSignatureList = (PGPSignatureList) nextObject; assert pgpSignatureList.size() == 1; PGPSignature pgpSignature = pgpSignatureList.get(0); PGPPublicKey pgpPublicKey = readPublicKey(publicKey, keyId); pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), pgpPublicKey); signedFileInputStream = new FileInputStream(signedFile); pgpSignature.update(IOUtils.toByteArray(signedFileInputStream)); return pgpSignature.verify(); } catch (PGPException e) { throw new IOException(e); } finally { IOUtils.closeQuietly(signatureInputStream); IOUtils.closeQuietly(signedFileInputStream); } }
From source file:com.bekwam.resignator.util.CryptUtils.java
License:Apache License
private byte[] decrypt(byte[] encrypted, char[] passPhrase) throws IOException, PGPException, NoSuchProviderException { try (InputStream in = new ByteArrayInputStream(encrypted)) { InputStream decoderIn = PGPUtil.getDecoderStream(in); PGPObjectFactory pgpF = new PGPObjectFactory(decoderIn, new BcKeyFingerprintCalculator()); PGPEncryptedDataList enc;/*w w w . ja va2s . co m*/ Object o = pgpF.nextObject(); if (o == null) { // decryption failed; there is no next object // // This could arise if there is a problem with the underlying file. // if (logger.isWarnEnabled()) { logger.warn( "Field could not be decrypted. (Config file modified outside of app?) Returning input bytes as encrypted bytes."); } return encrypted; } // // the first object might be a PGP marker packet. // if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpF.nextObject(); // i don't think this will be used } PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0); InputStream clear = pbe.getDataStream(new JcePBEDataDecryptorFactoryBuilder( new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC") .build(passPhrase)); return Streams.readAll(clear); } }
From source file:com.github.s4u.plugins.PGPVerifyMojo.java
License:Apache License
private boolean verifyPGPSignature(Artifact artifact, File artifactFile, File signatureFile) throws MojoFailureException { final Map<Integer, String> weakSignatures = ImmutableMap.<Integer, String>builder().put(1, "MD5") .put(4, "DOUBLE_SHA").put(5, "MD2").put(6, "TIGER_192").put(7, "HAVAL_5_160").put(11, "SHA224") .build();/*from w w w . j a va2 s . co m*/ getLog().debug("Artifact file: " + artifactFile); getLog().debug("Artifact sign: " + signatureFile); try { InputStream sigInputStream = PGPUtil.getDecoderStream(new FileInputStream(signatureFile)); PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(sigInputStream, new BcKeyFingerprintCalculator()); PGPSignatureList sigList = (PGPSignatureList) pgpObjectFactory.nextObject(); if (sigList == null) { throw new MojoFailureException("Invalid signature file: " + signatureFile); } PGPSignature pgpSignature = sigList.get(0); PGPPublicKey publicKey = pgpKeysCache.getKey(pgpSignature.getKeyID()); if (!keysMap.isValidKey(artifact, publicKey)) { String msg = String.format("%s=0x%X", ArtifactUtils.key(artifact), publicKey.getKeyID()); String keyUrl = pgpKeysCache.getUrlForShowKey(publicKey.getKeyID()); getLog().error(String.format("Not allowed artifact %s and keyID:\n\t%s\n\t%s\n", artifact.getId(), msg, keyUrl)); return false; } pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey); try (InputStream inArtifact = new BufferedInputStream(new FileInputStream(artifactFile))) { int t; while ((t = inArtifact.read()) >= 0) { pgpSignature.update((byte) t); } } String msgFormat = "%s PGP Signature %s\n KeyId: 0x%X UserIds: %s"; if (pgpSignature.verify()) { getLog().info(String.format(msgFormat, artifact.getId(), "OK", publicKey.getKeyID(), Lists.newArrayList(publicKey.getUserIDs()))); if (weakSignatures.containsKey(pgpSignature.getHashAlgorithm())) { if (failWeakSignature) { getLog().error("Weak signature algorithm used: " + weakSignatures.get(pgpSignature.getHashAlgorithm())); throw new MojoFailureException("Weak signature algorithm used: " + weakSignatures.get(pgpSignature.getHashAlgorithm())); } else { getLog().warn("Weak signature algorithm used: " + weakSignatures.get(pgpSignature.getHashAlgorithm())); } } return true; } else { getLog().warn(String.format(msgFormat, artifact.getId(), "ERROR", publicKey.getKeyID(), Lists.newArrayList(publicKey.getUserIDs()))); getLog().warn(artifactFile.toString()); getLog().warn(signatureFile.toString()); return false; } } catch (IOException | PGPException e) { throw new MojoFailureException(e.getMessage(), e); } }
From source file:com.google.e2e.bcdriver.Decryptor.java
License:Apache License
static final Result decrypt(InputStream in, PGPPrivateKey decryptKey, KeyChecker.PKR verify) throws IOException, PGPException, SignatureException { PGPObjectFactory pgpf = new PGPObjectFactory(PGPUtil.getDecoderStream(in), new BcKeyFingerprintCalculator()); Object o = pgpf.nextObject(); if (o == null) { throw new IOException("No encrypted content"); }//from w w w . j a v a 2 s . c om PGPEncryptedDataList enclist; if (o instanceof PGPEncryptedDataList) { enclist = (PGPEncryptedDataList) o; } else { enclist = (PGPEncryptedDataList) (pgpf.nextObject()); } Iterator<PGPPublicKeyEncryptedData> pkedi = Util.getTypedIterator(enclist.getEncryptedDataObjects(), PGPPublicKeyEncryptedData.class); if (pkedi == null) { throw new IOException("no encrypted data found!"); } while (pkedi.hasNext()) { PGPPublicKeyEncryptedData pked = pkedi.next(); if (pked.getKeyID() == decryptKey.getKeyID()) { return decryptSignedContent(pked, decryptKey, verify); } } return null; }
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();/*from w ww . j ava2 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:com.google.e2e.bcdriver.KeyChecker.java
License:Apache License
private static final boolean isGoodBackSignature(PGPSignature sig, PGPPublicKey signer, PGPPublicKey target, StringBuilder errors) throws PGPException, SignatureException, IOException { SignatureSubpacket esigpack = null;// w w w. j ava2s. c om // Prefer to get it from the hashed subpacket. PGPSignatureSubpacketVector svec = sig.getHashedSubPackets(); if (svec != null) { esigpack = svec.getSubpacket(SignatureSubpacketTags.EMBEDDED_SIGNATURE); } if (esigpack == null) { svec = sig.getUnhashedSubPackets(); if (svec != null) { esigpack = svec.getSubpacket(SignatureSubpacketTags.EMBEDDED_SIGNATURE); } } if (esigpack == null) { errors.append("Rejecting " + niceSig(sig) + " for subkey " + nicePk(target) + " because it doesn't have a cross-certification.\n" + "See https://www.gnupg.org/faq/subkey-cross-certify.html\n"); return false; } // Unfortunately, since PGPSignature(byte[]) is not public, we // have to go through this ugly contortion to get a signature. ByteArrayOutputStream baout = new ByteArrayOutputStream(); // dump out an old-style header. int hdr = 0x80 | (PacketTags.SIGNATURE << 2); int len = esigpack.getData().length; if (len <= 0xff) { baout.write(hdr); baout.write(len); } else if (len <= 0xffff) { baout.write(hdr | 0x01); baout.write((len >> 8) & 0xff); baout.write(len & 0xff); } else { baout.write(hdr | 0x02); baout.write((len >> 24) & 0xff); baout.write((len >> 16) & 0xff); baout.write((len >> 8) & 0xff); baout.write(len & 0xff); } baout.write(esigpack.getData()); baout.close(); PGPObjectFactory fact = new PGPObjectFactory(new ByteArrayInputStream(baout.toByteArray()), new BcKeyFingerprintCalculator()); Object obj = fact.nextObject(); if (!(obj instanceof PGPSignatureList)) { errors.append("Rejecting " + niceSig(sig) + " for subkey " + nicePk(target) + " because no usable embedded signature is available.\n"); return false; } PGPSignatureList esiglist = (PGPSignatureList) obj; if (esiglist.size() != 1) { errors.append("Rejecting " + niceSig(sig) + " for subkey " + nicePk(target) + " because no usable embedded signature is available.\n"); return false; } PGPSignature esig = esiglist.get(0); if (esig.getSignatureType() != PGPSignature.PRIMARYKEY_BINDING) { errors.append("Rejecting " + niceSig(sig) + " for subkey " + nicePk(target) + " because the embedded " + niceSig(esig) + " is not a proper backsignature.\n"); return false; } esig.init(new BcPGPContentVerifierBuilderProvider(), target); return esig.verifyCertification(signer, target) && isSignatureCurrent(esig, errors); }
From source file:dorkbox.util.crypto.CryptoPGP.java
License:Apache License
/** * Decode a PGP public key block and return the keyring it represents. */// w w w.j a v a 2 s . com public static PGPPublicKeyRing getKeyring(InputStream keyBlockStream) throws IOException { BcKeyFingerprintCalculator keyfp = new BcKeyFingerprintCalculator(); // PGPUtil.getDecoderStream() will detect ASCII-armor automatically and decode it, // the PGPObject factory then knows how to read all the data in the encoded stream PGPObjectFactory factory = new PGPObjectFactory(PGPUtil.getDecoderStream(keyBlockStream), keyfp); // these files should really just have one object in them, and that object should be a PGPPublicKeyRing. Object o = factory.nextObject(); if (o instanceof PGPPublicKeyRing) { return (PGPPublicKeyRing) o; } throw new IllegalArgumentException("Input stream does not contain a PGP Public Key"); }
From source file:dorkbox.util.crypto.CryptoPGP.java
License:Apache License
private static void verify(final InputStream publicKeyInputStream, final byte[] signature) throws Exception { PGPPublicKey publicKey = findPublicGPGKey(publicKeyInputStream); String text = new String(signature); Pattern regex = Pattern.compile( "-----BEGIN PGP SIGNED MESSAGE-----\\r?\\n.*?\\r?\\n\\r?\\n(.*)\\r?\\n(-----BEGIN PGP SIGNATURE-----\\r?\\n.*-----END PGP SIGNATURE-----)", Pattern.CANON_EQ | Pattern.DOTALL); Matcher regexMatcher = regex.matcher(text); if (regexMatcher.find()) { String dataText = regexMatcher.group(1); String signText = regexMatcher.group(2); ByteArrayInputStream dataIn = new ByteArrayInputStream(dataText.getBytes("UTF8")); ByteArrayInputStream signIn = new ByteArrayInputStream(signText.getBytes("UTF8")); InputStream signIn2 = PGPUtil.getDecoderStream(signIn); PGPObjectFactory pgpFact = new PGPObjectFactory(signIn2, new BcKeyFingerprintCalculator()); PGPSignatureList p3 = null;//from w w w.ja v a 2 s .c o m Object o; try { o = pgpFact.nextObject(); if (o == null) { throw new Exception(); } } catch (Exception ex) { throw new Exception("Invalid input data"); } if (o instanceof PGPCompressedData) { PGPCompressedData c1 = (PGPCompressedData) o; pgpFact = new PGPObjectFactory(c1.getDataStream(), new BcKeyFingerprintCalculator()); p3 = (PGPSignatureList) pgpFact.nextObject(); } else { p3 = (PGPSignatureList) o; } // PGPSignature sig = p3.get(0); // PGPPublicKey key = KeyRing.getPublicKeyByID(sig.getKeyID()); // // if (key == null) // throw new Exception("Cannot find key 0x" + Integer.toHexString((int) sig.getKeyID()).toUpperCase() + " in the pubring"); // // sig.initVerify(key, "BC"); // // while ((ch = dataIn.read()) >= 0) { // sig.update((byte) ch); //TODO migliorabile con byte[] // } // // if (sig.verify()) // return new PrintablePGPPublicKey(key).toString(); // else // return null; // return verifyFile(dataIn, signIn); } }
From source file:org.jpos.util.PGPHelper.java
License:Open Source License
public static boolean verifySignature(InputStream in, PGPPublicKey pk) throws IOException, NoSuchProviderException, PGPException, SignatureException { boolean verify = false; boolean newl = false; int ch;//from w w w .j av a2s . c o m ArmoredInputStream ain = new ArmoredInputStream(in, true); ByteArrayOutputStream out = new ByteArrayOutputStream(); while ((ch = ain.read()) >= 0 && ain.isClearText()) { if (newl) { out.write((byte) '\n'); newl = false; } if (ch == '\n') { newl = true; continue; } out.write((byte) ch); } PGPObjectFactory pgpf = new PGPObjectFactory(ain, fingerPrintCalculater); Object o = pgpf.nextObject(); if (o instanceof PGPSignatureList) { PGPSignatureList list = (PGPSignatureList) o; if (list.size() > 0) { PGPSignature sig = list.get(0); sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), pk); while ((ch = ain.read()) >= 0 && ain.isClearText()) { if (newl) { out.write((byte) '\n'); newl = false; } if (ch == '\n') { newl = true; continue; } out.write((byte) ch); } sig.update(out.toByteArray()); verify = sig.verify(); } } return verify; }