/** * * @param dsaKeyPair - the generated DSA key pair * @param elGamalKeyPair - the generated El Gamal key pair * @param identity - the given identity of the key pair ring * @param passphrase - the secret pass phrase to protect the key pair * @return a PGP Key Ring Generate with the El Gamal key pair added as sub key * @throws Exception */ public static final PGPKeyRingGenerator createPGPKeyRingGenerator(KeyPair dsaKeyPair, KeyPair elGamalKeyPair, String identity, char[] passphrase) throws Exception { PGPKeyPair dsaPgpKeyPair = new JcaPGPKeyPair(PGPPublicKey.DSA, dsaKeyPair, new Date()); PGPKeyPair elGamalPgpKeyPair = new JcaPGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elGamalKeyPair, new Date()); PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1); PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator( PGPSignature.POSITIVE_CERTIFICATION, dsaPgpKeyPair, identity, sha1Calc, null, null, new JcaPGPContentSignerBuilder(dsaPgpKeyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1), new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha1Calc).setProvider("BC").build(passphrase) ); keyRingGen.addSubKey(elGamalPgpKeyPair); return keyRingGen; }
static String signArmoredAscii(PGPPrivateKey privateKey, String data, int signatureAlgo) throws IOException, PGPException { String signature = null; final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), signatureAlgo)); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey); ByteArrayOutputStream signatureOutput = new ByteArrayOutputStream(); try( BCPGOutputStream outputStream = new BCPGOutputStream( new ArmoredOutputStream(signatureOutput)) ) { Utils.processStringAsStream(data, new StreamHandler() { @Override public void handleStreamBuffer(byte[] buffer, int offset, int length) throws IOException { signatureGenerator.update(buffer, offset, length); } }); signatureGenerator.generate().encode(outputStream); } signature = new String(signatureOutput.toByteArray(), "UTF-8"); return signature; }
static String signArmoredAscii(PGPPrivateKey privateKey, byte[] data, int signatureAlgo) throws IOException, PGPException { String signature = null; final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), signatureAlgo)); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey); ByteArrayOutputStream signatureOutput = new ByteArrayOutputStream(); try( BCPGOutputStream outputStream = new BCPGOutputStream( new ArmoredOutputStream(signatureOutput)) ) { Utils.processByteArrayAsStream(data, new StreamHandler() { @Override public void handleStreamBuffer(byte[] buffer, int offset, int length) throws IOException { signatureGenerator.update(buffer, offset, length); } }); signatureGenerator.generate().encode(outputStream); } signature = new String(signatureOutput.toByteArray(), "UTF-8"); return signature; }
/** * Usage flags as Bouncy castle {@link PGPKeyFlags} bits. */ public int getUsageFlags() throws PGPException { if (publicKey == null) return 0; int flags = 0; // actually only need POSITIVE_CERTIFICATION (for master key) // and SUBKEY_BINDING (for subkeys) Iterator<PGPSignature> signatures = publicKey.getSignatures(); while (signatures.hasNext()) { PGPSignature signature = signatures.next(); PGPSignatureSubpacketVector hashedSubPackets = signature.getHashedSubPackets(); if (hashedSubPackets != null) flags |= hashedSubPackets.getKeyFlags(); } return flags; }
/** * Builds a {@link Verifier} for each specified signature * for which a verification key is available. */ protected List<Verifier> buildVerifiers(Iterator signatures) throws PGPException { ArrayList<Verifier> verifiers = new ArrayList<Verifier>(); while (signatures.hasNext()) { Verifier verifier = null; Object signature = signatures.next(); if (signature instanceof PGPSignature) verifier = new Verifier((PGPSignature) signature); else if (signature instanceof PGPOnePassSignature) verifier = new Verifier((PGPOnePassSignature) signature); if (verifier != null && verifier.isKeyAvailable()) verifiers.add(verifier); } return verifiers; }
public void setSig(PGPSignature s) throws PGPException { sig = s; if (sig1 != null) return; key = getRing().findById(s.getKeyID()); if (key == null) { if (Decryptor.this.log.isLoggable(Level.INFO)) Decryptor.this.log.info("not found verification key " + Util.formatKeyId(s.getKeyID())); return; } Subkey subkey = key.findById(s.getKeyID()); if (subkey == null || !subkey.isForVerification()) key = null; else s.init(getVerifierProvider(), subkey.getPublicKey()); if (Decryptor.this.log.isLoggable(Level.INFO)) Decryptor.this.log.info((key == null ? "not " : "") + "using verification key " + subkey); }
/** * Verify a signature. Only return true if signature matches calculated signature of signedData * and if it was signed by the publicKey * * @param signedData * @param signature * @return */ public boolean verify(InputStream signedData, InputStream signature) { try { signature = PGPUtil.getDecoderStream(signature); JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(signature); PGPSignature sig = ((PGPSignatureList) pgpFact.nextObject()).get(0); PGPPublicKey key = pgpPubRingCollection.getPublicKey(sig.getKeyID()); sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), key); byte[] buff = new byte[1024]; int read = 0; while ((read = signedData.read(buff)) != -1) { sig.update(buff, 0, read); } signedData.close(); return sig.verify(); } catch (Exception ex) { // can we put a logger here please? return false; } }
/** * Verifies that a public key is signed with another public key * * @param keyToVerify the public key to verify * @param id the id we are verifying against the public key * @param keyToVerifyWith the key to verify with * * @return true if verified, false otherwise */ public static boolean verifyPublicKey( PGPPublicKey keyToVerify, String id, PGPPublicKey keyToVerifyWith ) throws PGPException { try { Iterator<PGPSignature> signIterator = keyToVerify.getSignatures(); while ( signIterator.hasNext() ) { PGPSignature signature = signIterator.next(); signature.init( new JcaPGPContentVerifierBuilderProvider().setProvider( provider ), keyToVerifyWith ); if ( signature.verifyCertification( id.getBytes(), keyToVerify ) ) { return true; } } return false; } catch ( Exception e ) { //throw custom exception throw new PGPException( "Error verifying public key", e ); } }
private boolean printPublicKeySignatures( PGPPublicKey publicKey, final PGPPublicKey secondPublicKey ) { boolean verification = false; try { verification = PGPEncryptionUtil .verifyPublicKey( publicKey, Long.toHexString( secondPublicKey.getKeyID() ), secondPublicKey ); } catch ( PGPException e ) { e.printStackTrace(); } logger.info( "%%%%%%%%%%%%% Signature verification: " + verification ); Iterator keySignatures = publicKey.getSignatures(); while ( keySignatures.hasNext() ) { PGPSignature signature = ( PGPSignature ) keySignatures.next(); signature.getSignatureType(); logger.info( Long.toHexString( signature.getKeyID() ) ); } return verification; }
/** * Simply stores the key ID in {@link #discoveredKeyIds} for future * reference of all Key IDs we've come across. This method uses a * {@link PGPPublicKeyRing} to ensure the input is actually a valid key, * plus locating any key IDs that have signed the key. * <p> * Please note {@link #discoveredKeyIds} is not used for any key functions * of this class. It is simply for user interface convenience. * * @param keyRing the key ID to store (required) */ @SuppressWarnings("unchecked") private void rememberKey(final PGPPublicKeyRing keyRing) { final PGPPublicKey key = keyRing.getPublicKey(); if (key != null) { final PgpKeyId keyId = new PgpKeyId(key); discoveredKeyIds.add(keyId); final Iterator<String> userIdIterator = key.getUserIDs(); while (userIdIterator.hasNext()) { final String userId = userIdIterator.next(); final Iterator<PGPSignature> signatureIterator = key .getSignaturesForID(userId); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); final PgpKeyId signatureKeyId = new PgpKeyId(signature); discoveredKeyIds.add(signatureKeyId); } } } }
public byte[] signExternal(String input) throws IOException, PGPException { PGPSecretKey signKey = readSecretKey(); PGPPrivateKey privKey = signKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray())); PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC")); sigGenerator.init(PGPSignature.BINARY_DOCUMENT, privKey); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) { BCPGOutputStream bOut = new BCPGOutputStream(aOut); sigGenerator.update(input.getBytes(Charsets.UTF_8)); sigGenerator.generate().encode(bOut); } return buffer.toByteArray(); }
/** * Checks whether one of the signatures of the key has one of the expected * key flags * * @param key * @return {@link Boolean#TRUE} if key has one of the expected flag, * <code>null</code> if the key does not have any key flags, * {@link Boolean#FALSE} if the key has none of the expected flags */ private static Boolean hasOneOfExpectedKeyFlags(PGPPublicKey key, int[] expectedKeyFlags) { boolean containsKeyFlags = false; for (@SuppressWarnings("unchecked") Iterator<PGPSignature> itsig = key.getSignatures(); itsig.hasNext();) { PGPSignature sig = itsig.next(); PGPSignatureSubpacketVector subPacks = sig.getHashedSubPackets(); if (subPacks != null) { int keyFlag = subPacks.getKeyFlags(); if (keyFlag > 0 && !containsKeyFlags) { containsKeyFlags = true; } for (int expectdKeyFlag : expectedKeyFlags) { int result = keyFlag & expectdKeyFlag; if (result == expectdKeyFlag) { return Boolean.TRUE; } } } } if (containsKeyFlags) { return Boolean.FALSE; } return null; // no key flag }
private void createSignature(OutputStream out) throws Exception { PGPSecretKey pgpSec = readSecretKey(); PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(getProvider()).build( "sdude".toCharArray())); PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1).setProvider(getProvider())); sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey); BCPGOutputStream bOut = new BCPGOutputStream(out); InputStream fIn = new ByteArrayInputStream("Test Signature".getBytes("UTF-8")); int ch; while ((ch = fIn.read()) >= 0) { sGen.update((byte) ch); } fIn.close(); sGen.generate().encode(bOut); }
@Override public void close () throws IOException { testInit (); if ( this.inline ) { this.armoredOutput.endClearText (); } try { final PGPSignature signature = this.signatureGenerator.generate (); signature.encode ( new BCPGOutputStream ( this.armoredOutput ) ); } catch ( final PGPException e ) { throw new IOException ( e ); } this.armoredOutput.close (); super.close (); }
private void gatherRevocationProblems(PGPPublicKey key, Date now, List<String> problems) { try { List<PGPSignature> revocations = new ArrayList<>(); Map<Long, RevocationKey> revokers = new HashMap<>(); PGPSignature selfRevocation = scanRevocations(key, now, revocations, revokers); if (selfRevocation != null) { RevocationReason reason = getRevocationReason(selfRevocation); if (isRevocationValid(selfRevocation, reason, now)) { problems.add(reasonToString(reason)); } } else { checkRevocations(key, revocations, revokers, problems); } } catch (PGPException | IOException e) { problems.add("Error checking key revocation"); } }
private String checkTrustSubpacket(PGPSignature sig, int depth) { SignatureSubpacket trustSub = sig.getHashedSubPackets().getSubpacket(SignatureSubpacketTags.TRUST_SIG); if (trustSub == null || trustSub.getData().length != 2) { return "Certification is missing trust information"; } byte amount = trustSub.getData()[1]; if (amount < COMPLETE_TRUST) { return "Certification does not fully trust key"; } byte level = trustSub.getData()[0]; int required = depth + 1; if (level < required) { return "Certification trusts to depth " + level + ", but depth " + required + " is required"; } return null; }
private Result checkSignature(PGPSignature sig, PushCertificate cert, PublicKeyStore store) throws PGPException, IOException { PGPPublicKeyRingCollection keys = store.get(sig.getKeyID()); if (!keys.getKeyRings().hasNext()) { return new Result( null, CheckResult.bad("No public keys found for key ID " + keyIdToString(sig.getKeyID()))); } PGPPublicKey signer = PublicKeyStore.getSigner(keys, sig, Constants.encode(cert.toText())); if (signer == null) { return new Result( null, CheckResult.bad("Signature by " + keyIdToString(sig.getKeyID()) + " is not valid")); } CheckResult result = publicKeyChecker.setStore(store).setEffectiveTime(sig.getCreationTime()).check(signer); if (!result.getProblems().isEmpty()) { StringBuilder err = new StringBuilder("Invalid public key ") .append(keyToString(signer)) .append(":\n ") .append(Joiner.on("\n ").join(result.getProblems())); return new Result(signer, CheckResult.create(result.getStatus(), err.toString())); } return new Result(signer, result); }
private boolean hasAllowedUserId(PGPPublicKey key, Set<String> allowedUserIds) throws PGPException { Iterator<String> userIds = key.getUserIDs(); while (userIds.hasNext()) { String userId = userIds.next(); if (isAllowed(userId, allowedUserIds)) { Iterator<PGPSignature> sigs = getSignaturesForId(key, userId); while (sigs.hasNext()) { if (isValidCertification(key, sigs.next(), userId)) { return true; } } } } return false; }
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; } 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); }
private Set<PgpKeyFlag> getPgpKeyFlags() { final EnumSet<PgpKeyFlag> result = EnumSet.noneOf(PgpKeyFlag.class); final PgpKeyId masterKeyId = masterKey == null ? getPgpKeyId() : masterKey.getPgpKeyId(); final Iterator<?> sigIt = publicKey.getSignatures(); while (sigIt.hasNext()) { final PGPSignature signature = (PGPSignature) sigIt.next(); if (signature.getKeyID() != masterKeyId.longValue()) continue; // It seems, the signature type is not always the way it should be (to my understanding). // To look for PGPSignature.SUBKEY_BINDING works fine, but PGPSignature.PRIMARYKEY_BINDING seems to // never be used. I thus do not filter by signature-type at all, anymore, but collect all keyFlags // from all signatures made by the master-key. final PGPSignatureSubpacketVector hashedSubPackets = signature.getHashedSubPackets(); if (hashedSubPackets != null) { final int keyFlags = hashedSubPackets.getKeyFlags(); result.addAll(getPgpKeyFlags(keyFlags)); } } return result; }
private void printPublicKey(final PGPPublicKey publicKey) { final byte[] fingerprint = publicKey.getFingerprint(); System.out.println(">>> pub >>>"); System.out.println("keyID: " + encodeHexStr(longToBytes(publicKey.getKeyID()))); System.out.println("fingerprint: " + (fingerprint == null ? "" : formatEncodedHexStrForHuman(encodeHexStr(fingerprint)))); System.out.println("masterKey: " + publicKey.isMasterKey()); System.out.println("encryptionKey: " + publicKey.isEncryptionKey()); // trustData is *always* null :-( // final byte[] trustData = publicKey.getTrustData(); // System.out.println("trustData: " + (trustData == null ? null : encodeHexStr(trustData))); for (final Iterator<?> it3 = publicKey.getUserIDs(); it3.hasNext(); ) { final String userId = (String) it3.next(); System.out.println("userID: " + userId); } for (final Iterator<?> it4 = publicKey.getSignatures(); it4.hasNext(); ) { final PGPSignature signature = (PGPSignature) it4.next(); System.out.println("signature.keyID: " + encodeHexStr(longToBytes(signature.getKeyID()))); System.out.println("signature.signatureType: " + signatureTypeToString(signature.getSignatureType())); } System.out.println("<<< pub <<<"); }
/** * Verify a PGP signature. * * @param file the file * @param signature the signature * @param key the public key * @return true if the signature is verified * @throws Exception anything preventing the verification to happen */ public static boolean verifySignature( InputStream file, InputStream signature, PGPPublicKey key) throws Exception { InputStream sigInputStream = PGPUtil.getDecoderStream(signature); PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(sigInputStream, new BcKeyFingerprintCalculator()); PGPSignatureList sigList = (PGPSignatureList) pgpObjectFactory.nextObject(); PGPSignature pgpSignature = sigList.get(0); pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), key); try (InputStream inArtifact = new BufferedInputStream(file)) { int t; while ((t = inArtifact.read()) >= 0) { pgpSignature.update((byte) t); } } return pgpSignature.verify(); }
public static final List<String> listCertifications(File publicKeyFile) throws IOException { FileInputStream keyInputStream = new FileInputStream(publicKeyFile); List<String> keyIds = new ArrayList<String>(); PGPPublicKeyRing pgpPubRing = new PGPPublicKeyRing(PGPUtil.getDecoderStream(keyInputStream), new JcaKeyFingerprintCalculator()); PGPPublicKey pubKey = pgpPubRing.getPublicKey(); @SuppressWarnings("unchecked") Iterator<PGPSignature> sigIter = pubKey.getSignatures(); while (sigIter.hasNext()) { PGPSignature pgpSig = sigIter.next(); long keyId = pgpSig.getKeyID(); keyIds.add(Long.toHexString(keyId).toUpperCase()); } return keyIds; }
private PKR (Status status, PGPPublicKeyRing pkr, List<byte[]> designated_revoker_fps, List<PGPSignature> primary_revoking_sigs, List<UserID> uids, List<UserAttribute> attrs, List<Subkey> subkeys, PGPPublicKey encrypt_key, StringBuilder errors) { m_status = status; m_pkr = pkr; m_designated_revoker_fps = designated_revoker_fps; m_primary_revoking_sigs = primary_revoking_sigs; m_uids = uids; m_attrs = attrs; m_subkeys = subkeys; m_encrypt_key = encrypt_key; m_errors = errors; }
private final static void updateCertMap (Map<String, Certification> fp2certs, PGPSignature sig, PGPPublicKey signer) { String fp = Hex.toHexString(signer.getFingerprint()); Certification cert = fp2certs.get(fp); if (cert == null) { cert = new Certification(signer, sig); fp2certs.put(fp, cert); } else { // Update to most recent signature. if (cert.getSignature().getCreationTime().getTime() < sig.getCreationTime().getTime()) { cert.setSignature(sig); } } }
private final static List<Certification> filterCerts (Map<String,Certification> fp2certs, String tag, StringBuilder errors) { List<Certification> certs = new ArrayList<Certification>(); for (String fp: fp2certs.keySet()) { Certification cert = fp2certs.get(fp); int typ = cert.getSignature().getSignatureType(); if ((typ >= PGPSignature.DEFAULT_CERTIFICATION) && (typ <= PGPSignature.POSITIVE_CERTIFICATION)) { certs.add(cert); } else { errors.append (niceSig(cert.getSignature())+ " revoked "+tag+", removing its certification.\n"); } } return certs; }
private final static boolean isGoodUIDSignature (PGPSignature sig, PGPPublicKey masterpk, String uid, boolean self, PrimaryKeyFinder kf, KeyInfo signer_info, StringBuilder errors) throws PGPException,SignatureException,IOException { List<PGPPublicKey> signers = findSigners (sig, masterpk, self, kf, "'"+uid+"'", errors); if (signers == null) { return false; } for (PGPPublicKey signer: signers) { sig.init(new BcPGPContentVerifierBuilderProvider(), signer); if (!sig.verifyCertification(uid, masterpk)) { errors.append ("Skipping certification "+niceSig(sig)+" for '"+uid+ "' because the signature is invalid.\n"); continue; } if (isSignatureCurrent(sig, errors)) { signer_info.setKey(signer); return true; } } return false; }
private final static List<PGPPublicKey> findSigners (PGPSignature sig, PGPPublicKey masterpk, boolean self, PrimaryKeyFinder kf, String tag, StringBuilder errors) { List<PGPPublicKey> signers = null; if (self) { if (sig.getKeyID() != masterpk.getKeyID()) { return null; } signers = Arrays.asList(masterpk); } else { if (sig.getKeyID() == masterpk.getKeyID()) { return null; } if (kf != null) { signers = kf.findByKeyID(sig.getKeyID()); } } if ((signers == null) || (signers.size() == 0)) { errors.append ("Skipping certification "+niceSig(sig)+" for "+tag+ " because its public key is unavailable.\n"); return null; } return signers; }
private final static boolean isGoodAttributeSignature (PGPSignature sig, PGPPublicKey masterpk, PGPUserAttributeSubpacketVector attr, boolean self, PrimaryKeyFinder kf, KeyInfo signer_info, StringBuilder errors) throws PGPException,SignatureException,IOException { List<PGPPublicKey> signers = findSigners (sig, masterpk, self, kf, "attribute", errors); if (signers == null) { return false; } for (PGPPublicKey signer: signers) { sig.init(new BcPGPContentVerifierBuilderProvider(), signer); if (!sig.verifyCertification(attr, masterpk)) { errors.append ("Skipping certification "+niceSig(sig)+ " for attribute because the signature is invalid.\n"); continue; } if (isSignatureCurrent(sig, errors)) { signer_info.setKey(signer); return true; } } return false; }
private final static boolean acceptableInterval (PGPSignature sig, long start, long delta, StringBuilder errors) { if (delta < 0) { errors.append (niceSig(sig)+" has a negative expiration interval (" +delta+")\n"); return false; } if ((start + delta) < (System.currentTimeMillis() - ACCEPTABLE_DELTA_MSEC)) { errors.append(niceSig(sig)+" has expired\n"); return false; } return true; }
@Test public void verifyGoodSignature() throws Exception { final PGPPublicKeyRingCollection publicKeyRing = getPublicKeyRingWithTrustedKeys(); final PGPSignatureList sl = readSignatureFile("/content1.sig"); assertThat(sl.isEmpty()).isFalse(); assertThat(sl.size()).isEqualTo(1); PGPSignature signature = sl.get(0); signature.init(new BcPGPContentVerifierBuilderProvider(), publicKeyRing.getPublicKey(signature.getKeyID())); InputStream contentIn = PGPTest.class.getResourceAsStream("/content1"); byte[] buf = new byte[4096]; int len; while (0 <= (len = contentIn.read(buf))) { signature.update(buf, 0, len); } contentIn.close(); assertThat(signature.verify()).isTrue(); }
@Test public void verifyBadSignature() throws Exception { final PGPPublicKeyRingCollection publicKeyRing = getPublicKeyRingWithTrustedKeys(); final PGPSignatureList sl = readSignatureFile("/content1.sig"); assertThat(sl.isEmpty()).isFalse(); assertThat(sl.size()).isEqualTo(1); PGPSignature signature = sl.get(0); signature.init(new BcPGPContentVerifierBuilderProvider(), publicKeyRing.getPublicKey(signature.getKeyID())); InputStream contentIn = PGPTest.class.getResourceAsStream("/content1"); byte[] buf = new byte[4096]; int len; while (0 <= (len = contentIn.read(buf))) { buf[0] = 0; signature.update(buf, 0, len); } contentIn.close(); assertThat(signature.verify()).isFalse(); }
public PGPSignatureGenerator createSignatureGenerator() { try { PGPSignatureGenerator generator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)); generator.init(PGPSignature.BINARY_DOCUMENT, privateKey); return generator; } catch (PGPException e) { throw new UncheckedException(e); } }
/** * Matches the specified trailing signatures to the specified verifiers. */ protected void matchSignatures(Iterator<PGPSignature> signatures, List<Verifier> verifiers) { while (signatures.hasNext()) { PGPSignature signature = signatures.next(); for (Verifier verifier : verifiers) verifier.match(signature); } }
/** * Tries to match the specified PGPSignature to this verifier's * PGPOnePassSignature (sig1); if found sets sig and returns true. */ public boolean match(PGPSignature s) { if (sig1 != null && sig1.getKeyID() == s.getKeyID()) { sig = s; return true; } return false; }
public void test6() throws Exception { PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection(pub6, new BcKeyFingerprintCalculator()); Iterator rIt = pubRings.getKeyRings(); while (rIt.hasNext()) { PGPPublicKeyRing pgpPub = (PGPPublicKeyRing)rIt.next(); Iterator it = pgpPub.getPublicKeys(); while (it.hasNext()) { PGPPublicKey k = (PGPPublicKey)it.next(); if (k.getKeyID() == 0x5ce086b5b5a18ff4L) { int count = 0; Iterator sIt = k.getSignaturesOfType(PGPSignature.SUBKEY_REVOCATION); while (sIt.hasNext()) { PGPSignature sig = (PGPSignature)sIt.next(); count++; } if (count != 1) { fail("wrong number of revocations in test6."); } } } } byte[] encRing = pubRings.getEncoded(); }
private void checkPublicKeyRingWithX509(byte[] keyRing) throws Exception { PGPPublicKeyRing pubRing = new PGPPublicKeyRing(keyRing, new BcKeyFingerprintCalculator()); Iterator it = pubRing.getPublicKeys(); if (it.hasNext()) { PGPPublicKey key = (PGPPublicKey)it.next(); Iterator sIt = key.getSignatures(); if (sIt.hasNext()) { PGPSignature sig = (PGPSignature)sIt.next(); if (sig.getKeyAlgorithm() != 100) { fail("experimental signature not found"); } if (!areEqual(sig.getSignature(), Hex.decode("000101"))) { fail("experimental encoding check failed"); } } else { fail("no signature found"); } } else { fail("no key found"); } }
public static boolean verifySignature( ContentAndSignatures contentAndSignatures, PGPPublicKey publicKey ) throws PGPException { Preconditions.checkNotNull( contentAndSignatures ); Preconditions.checkNotNull( publicKey ); try { for ( int i = 0; i < contentAndSignatures.getOnePassSignatureList().size(); i++ ) { PGPOnePassSignature ops = contentAndSignatures.getOnePassSignatureList().get( 0 ); ops.init( new JcaPGPContentVerifierBuilderProvider().setProvider( provider ), publicKey ); ops.update( contentAndSignatures.getDecryptedContent() ); PGPSignature signature = contentAndSignatures.getSignatureList().get( i ); if ( !ops.verify( signature ) ) { return false; } } return true; } catch ( Exception e ) { throw new PGPException( "Error in verifySignature", e ); } }
private static void processLine( PGPSignature sig, byte[] line ) throws SignatureException, IOException { int length = getLengthWithoutWhiteSpace( line ); if ( length > 0 ) { sig.update( line, 0, length ); } }
/** * Signs a public key * * @param publicKeyRing a public key ring containing the single public key to sign * @param id the id we are certifying against the public key * @param secretKey the signing key * @param secretKeyPassword the signing key password * * @return a public key ring with the signed public key */ public static PGPPublicKeyRing signPublicKey( PGPPublicKeyRing publicKeyRing, String id, PGPSecretKey secretKey, String secretKeyPassword ) throws PGPException { try { PGPPublicKey oldKey = publicKeyRing.getPublicKey(); PGPPrivateKey pgpPrivKey = secretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ) .build( secretKeyPassword.toCharArray() ) ); PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder( secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1 ) ); signatureGenerator.init( PGPSignature.DEFAULT_CERTIFICATION, pgpPrivKey ); PGPSignature signature = signatureGenerator.generateCertification( id, oldKey ); PGPPublicKey newKey = PGPPublicKey.addCertification( oldKey, signature ); PGPPublicKeyRing newPublicKeyRing = PGPPublicKeyRing.removePublicKey( publicKeyRing, oldKey ); return PGPPublicKeyRing.insertPublicKey( newPublicKeyRing, newKey ); } catch ( Exception e ) { //throw custom exception throw new PGPException( "Error signing public key", e ); } }