List of usage examples for org.bouncycastle.openpgp PGPSignature verify
public boolean verify() throws PGPException
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> *//*from ww w .jav a2 s . co m*/ 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 va 2 s. c o 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:cc.arduino.packages.security.ClearSignedVerifier.java
License:Open Source License
/** * Verify a PGP clearText-signature.//from ww w. j a va2s . com * * @param signedTextFile A File containing the clearText signature * @param pubKeyRing A public key-ring containing the public key needed for the * signature verification * @return A VerifyResult class with the clearText and the signature * verification status * @throws FileNotFoundException */ public static VerifyResult verify(File signedTextFile, PGPPublicKeyRingCollection pubKeyRing) { // Create the result object VerifyResult result = new VerifyResult(); result.clearText = null; result.verified = false; result.error = null; ArmoredInputStream in = null; try { // Extract clear text. // Dash-encoding is removed by ArmoredInputStream. in = new ArmoredInputStream(new FileInputStream(signedTextFile)); ByteArrayOutputStream temp = new ByteArrayOutputStream(in.available()); while (true) { int c = in.read(); if (c == -1) throw new IOException("Unexpected end of file"); if (!in.isClearText()) break; temp.write(c); } byte clearText[] = temp.toByteArray(); result.clearText = clearText; // Extract signature from clear-signed text PGPObjectFactory pgpFact = new PGPObjectFactory(in); PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject(); PGPSignature sig = p3.get(0); // Decode public key PGPPublicKey publicKey = pubKeyRing.getPublicKey(sig.getKeyID()); // Verify signature Security.addProvider(new BouncyCastleProvider()); sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey); // RFC 4880, section 7: http://tools.ietf.org/html/rfc4880#section-7 // The signature must be validated using clear text: // - without trailing white spaces on every line // - using CR LF line endings, no matter what the original line ending is // - without the latest line ending BufferedReader textIn = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(clearText))); while (true) { // remove trailing whitespace and line endings String line = StringUtils.rtrim(textIn.readLine()); sig.update(line.getBytes()); if (!textIn.ready()) // skip latest line ending break; // always use CR LF sig.update((byte) '\r'); sig.update((byte) '\n'); } // Prepare the result result.verified = sig.verify(); } catch (Exception e) { result.error = e; } finally { if (in != null) try { in.close(); } catch (IOException e) { // ignored } } return result; }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Check the signature in clear-signed data *///from w w w. j a va2 s.c om private boolean checkClearsign(InputStream in, PGPPublicKeyRingCollection pgpRings) throws PGPException { try { // // read the input, making sure we ingore the last newline. // ArmoredInputStream aIn = (ArmoredInputStream) in; boolean newLine = false; ByteArrayOutputStream bOut = new ByteArrayOutputStream(); int ch; while ((ch = aIn.read()) >= 0 && aIn.isClearText()) { if (newLine) { bOut.write((byte) '\n'); newLine = false; } if (ch == '\n') { newLine = true; continue; } bOut.write((byte) ch); } PGPObjectFactory pgpFact = new PGPObjectFactory(aIn); PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject(); PGPSignature sig = null; PGPPublicKey key = null; int count = 0; while (count < p3.size()) { sig = (PGPSignature) p3.get(count); key = pgpRings.getPublicKey(sig.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"); } sig.initVerify(key, "BC"); sig.update(bOut.toByteArray()); return sig.verify(); } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in verification", e); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Check a signature// ww w .j a v a2 s .c o m */ private boolean checkSignature(OutputStream out, PGPSignatureList sigList, PGPObjectFactory pgpFact, PGPPublicKeyRingCollection pgpRing) throws PGPException { try { PGPSignature sig = null; PGPPublicKey key = null; int count = 0; while (count < sigList.size()) { sig = sigList.get(count); key = pgpRing.getPublicKey(sig.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(); sig.initVerify(key, "BC"); int ch; while ((ch = dataIn.read()) >= 0) { sig.update((byte) ch); out.write(ch); } out.close(); return sig.verify(); } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in verification", e); } }
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 v a 2s .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.KeyChecker.java
License:Apache License
private static final boolean isGoodDirectSignature(PGPSignature sig, PGPPublicKey signer, PGPPublicKey target, StringBuilder errors) throws PGPException, SignatureException, IOException { sig.init(new BcPGPContentVerifierBuilderProvider(), signer); boolean ok;// www. ja v a2 s . co m // There's a bug that prevents sig.verifyCertification(signer) // working for DIRECT_KEY signatures. // // So, re-implement the code again here. if (sig.getSignatureType() == PGPSignature.DIRECT_KEY) { byte[] bytes = target.getPublicKeyPacket().getEncodedContents(); sig.update((byte) 0x99); sig.update((byte) (bytes.length >> 8)); sig.update((byte) (bytes.length)); sig.update(bytes); ok = sig.verify(); } else { ok = sig.verifyCertification(target); } // If we have a good signature, also ensure the signature // hasn't expired. return ok && isSignatureCurrent(sig, errors); }
From source file:com.google.gerrit.gpg.PublicKeyStore.java
License:Apache License
/** * Choose the public key that produced a signature. * <p>/*from w ww . j a v a2 s . c o m*/ * @param keyRings candidate keys. * @param sig signature object. * @param data signed payload. * @return the key chosen from {@code keyRings} that was able to verify the * signature, or null if none was found. * @throws PGPException if an error occurred verifying the signature. */ public static PGPPublicKey getSigner(Iterable<PGPPublicKeyRing> keyRings, PGPSignature sig, byte[] data) throws PGPException { for (PGPPublicKeyRing kr : keyRings) { PGPPublicKey k = kr.getPublicKey(); sig.init(new BcPGPContentVerifierBuilderProvider(), k); sig.update(data); if (sig.verify()) { return k; } } return null; }
From source file:com.google.gerrit.server.git.gpg.PushCertificateChecker.java
License:Apache License
private void checkSignature(PGPSignature sig, PushCertificate cert, PGPPublicKeyRingCollection keys, List<String> problems) { List<String> deferredProblems = new ArrayList<>(); boolean anyKeys = false; for (PGPPublicKeyRing kr : keys) { PGPPublicKey k = kr.getPublicKey(); anyKeys = true;/*from w ww . ja v a 2 s . c o m*/ try { sig.init(new BcPGPContentVerifierBuilderProvider(), k); sig.update(Constants.encode(cert.toText())); if (!sig.verify()) { // TODO(dborowitz): Privacy issues with exposing fingerprint/user ID // of keys having the same ID as the pusher's key? deferredProblems.add("Signature not valid with public key: " + keyToString(k)); continue; } CheckResult result = publicKeyChecker.check(k, sig.getKeyID()); if (result.isOk()) { return; } StringBuilder err = new StringBuilder("Invalid public key (").append(keyToString(k)).append("):"); for (int i = 0; i < result.getProblems().size(); i++) { err.append('\n').append(" ").append(result.getProblems().get(i)); } problems.add(err.toString()); return; } catch (PGPException e) { deferredProblems .add("Error checking signature with public key (" + keyToString(k) + ": " + e.getMessage()); } } if (!anyKeys) { problems.add("No public keys found for Key ID " + keyIdToString(sig.getKeyID())); } else { problems.addAll(deferredProblems); } }
From source file:com.navnorth.learningregistry.LRVerify.java
License:Apache License
/** * Verfies that the provided message and signature using the public key * * @param isSignature InputStream of the signature * @param isMessage InputStream of the message * @param isPublicKey InputStream of the public key * @throws LRException//from w ww . j a va 2 s .c o m */ private static boolean Verify(InputStream isSignature, InputStream isMessage, InputStream isPublicKey) throws LRException { // Get the public key ring collection from the public key input stream PGPPublicKeyRingCollection pgpRings = null; try { pgpRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(isPublicKey)); } catch (Exception e) { throw new LRException(LRException.INVALID_PUBLIC_KEY); } // Add the Bouncy Castle security provider Security.addProvider(new BouncyCastleProvider()); // Build an output stream from the message for verification boolean verify = false; int ch; ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ArmoredInputStream aIn = null; try { aIn = new ArmoredInputStream(isMessage); // We are making no effort to clean the input for this example // If this turns into a fully-featured verification utility in a future version, this will need to be handled while ((ch = aIn.read()) >= 0 && aIn.isClearText()) { bOut.write((byte) ch); } bOut.close(); } catch (Exception e) { throw new LRException(LRException.MESSAGE_INVALID); } // Build an object factory from the signature input stream and try to get an object out of it Object o = null; try { PGPObjectFactory pgpFact = new PGPObjectFactory(PGPUtil.getDecoderStream(isSignature)); o = pgpFact.nextObject(); } catch (Exception e) { throw new LRException(LRException.SIGNATURE_INVALID); } // Check if the object we fetched is a signature list and if it is, get the signature and use it to verfiy try { if (o instanceof PGPSignatureList) { PGPSignatureList list = (PGPSignatureList) o; if (list.size() > 0) { PGPSignature sig = list.get(0); PGPPublicKey publicKey = pgpRings.getPublicKey(sig.getKeyID()); sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey); sig.update(bOut.toByteArray()); verify = sig.verify(); } } } catch (Exception e) { throw new LRException(LRException.SIGNATURE_NOT_FOUND); } return verify; }