List of usage examples for org.bouncycastle.openpgp PGPSignature getKeyID
public long getKeyID()
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 w w w . j a v a 2s. c o 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.packages.security.ClearSignedVerifier.java
License:Open Source License
/** * Verify a PGP clearText-signature.//from ww w . j a va2 s .c o m * * @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 */// www . j a va2 s. co m 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/* w w w . j ava 2 s.co 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 av a 2 s. c o 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 String niceSig(PGPSignature sig) { return "signature (type=0x" + Integer.toHexString(sig.getSignatureType()) + ") issued by keyid 0x" + Long.toHexString(sig.getKeyID()); }
From source file:com.google.gerrit.gpg.GerritPublicKeyChecker.java
License:Apache License
private static boolean isValidCertification(PGPPublicKey key, PGPSignature sig, String userId) throws PGPException { if (sig.getSignatureType() != PGPSignature.DEFAULT_CERTIFICATION && sig.getSignatureType() != PGPSignature.POSITIVE_CERTIFICATION) { return false; }/*w ww .j av a 2 s .co m*/ if (sig.getKeyID() != key.getKeyID()) { return false; } // TODO(dborowitz): Handle certification revocations: // - Is there a revocation by either this key or another key trusted by the // server? // - Does such a revocation postdate all other valid certifications? sig.init(new BcPGPContentVerifierBuilderProvider(), key); return sig.verifyCertification(userId, key); }
From source file:com.google.gerrit.gpg.PublicKeyChecker.java
License:Apache License
private static PGPPublicKey getSigner(PublicKeyStore store, PGPSignature sig, String userId, PGPPublicKey key, List<CheckResult> results) { try {// w ww . j a v a2 s.c o m PGPPublicKeyRingCollection signers = store.get(sig.getKeyID()); if (!signers.getKeyRings().hasNext()) { results.add(new CheckResult( "Key " + keyIdToString(sig.getKeyID()) + " used for certification is not in store")); return null; } PGPPublicKey signer = PublicKeyStore.getSigner(signers, sig, userId, key); if (signer == null) { results.add(new CheckResult("Certification by " + keyIdToString(sig.getKeyID()) + " is not valid")); return null; } return signer; } catch (PGPException | IOException e) { results.add(new CheckResult("Error checking certification by " + keyIdToString(sig.getKeyID()))); return null; } }
From source file:com.google.gerrit.gpg.PushCertificateChecker.java
License:Apache License
private void checkSignature(PGPSignature sig, PushCertificate cert, PublicKeyStore store, List<String> problems) throws PGPException, IOException { PGPPublicKeyRingCollection keys = store.get(sig.getKeyID()); if (!keys.getKeyRings().hasNext()) { problems.add("No public keys found for key ID " + keyIdToString(sig.getKeyID())); return;//from www . j a v a 2 s . c o m } PGPPublicKey signer = PublicKeyStore.getSigner(keys, sig, Constants.encode(cert.toText())); if (signer == null) { problems.add("Signature by " + keyIdToString(sig.getKeyID()) + " is not valid"); return; } CheckResult result = publicKeyChecker.check(signer, store); if (!result.isOk()) { StringBuilder err = new StringBuilder("Invalid public key ").append(keyToString(signer)).append(":"); for (String problem : result.getProblems()) { err.append("\n ").append(problem); } problems.add(err.toString()); } }
From source file:com.google.gerrit.server.git.gpg.PushCertificateChecker.java
License:Apache License
/** * Check a push certificate.//w w w .ja va 2s. co m * * @return result of the check. * @throws PGPException if an error occurred during GPG checks. * @throws IOException if an error occurred reading from the repository. */ public final CheckResult check(PushCertificate cert) throws PGPException, IOException { if (cert.getNonceStatus() != NonceStatus.OK) { return new CheckResult("Invalid nonce"); } PGPSignature sig = readSignature(cert); if (sig == null) { return new CheckResult("Invalid signature format"); } Repository repo = getRepository(); List<String> problems = new ArrayList<>(); try (PublicKeyStore store = new PublicKeyStore(repo)) { checkSignature(sig, cert, store.get(sig.getKeyID()), problems); checkCustom(repo, problems); return new CheckResult(problems); } finally { if (shouldClose(repo)) { repo.close(); } } }