org.bouncycastle.openpgp.PGPSignature Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPSignature. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Subkey.java    From jpgpj with MIT License 6 votes vote down vote up
/**
 * 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)
    @SuppressWarnings("unchecked")
    Iterator<PGPSignature> signatures = publicKey.getSignatures();
    while (signatures.hasNext()) {
        PGPSignature signature = signatures.next();
        PGPSignatureSubpacketVector hashedSubPackets =
            signature.getHashedSubPackets();

        if (hashedSubPackets != null)
            flags |= hashedSubPackets.getKeyFlags();
    }
    return flags;
}
 
Example #2
Source File: PGPEncryptionUtilTest.java    From peer-os with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: Decryptor.java    From jpgpj with MIT License 6 votes vote down vote up
/**
 * Builds a {@link Verifier} for each specified signature
 * for which a verification key is available.
 */
protected List<Verifier> buildVerifiers(Iterator<?> signatures)
        throws PGPException {
    List<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;
}
 
Example #4
Source File: AptITSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public boolean verifyReleaseFilePgpSignature(final InputStream signedData,
                                             final InputStream signature,
                                             final InputStream publicKey)
    throws Exception
{
  PGPObjectFactory pgpFact =
      new PGPObjectFactory(PGPUtil.getDecoderStream(signature), new JcaKeyFingerprintCalculator());
  PGPSignature sig = ((PGPSignatureList) pgpFact.nextObject()).get(0);

  PGPPublicKeyRingCollection pgpPubRingCollection =
      new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicKey),
          new JcaKeyFingerprintCalculator());

  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();
}
 
Example #5
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
/**
 * 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 );
    }
}
 
Example #6
Source File: Decryptor.java    From jpgpj with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: AptSigningFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public byte[] signExternal(final String input) throws IOException {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  try {
    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);

    try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
      BCPGOutputStream bOut = new BCPGOutputStream(aOut);
      sigGenerator.update(input.getBytes(Charsets.UTF_8));
      sigGenerator.generate().encode(bOut);
    }
  }
  catch (PGPException ex) {
    throw new RuntimeException(ex);
  }

  return buffer.toByteArray();
}
 
Example #8
Source File: SigningStream.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
@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 ();
}
 
Example #9
Source File: PublicKeyUtils.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Return master key for given sub public key.
 *
 * @param publicKey
 *         given key
 * @param publicKeyRing
 *         keys ring with master and sub keys
 *
 * @return master key of empty if not found or given key is master key
 */
public static Optional<PGPPublicKey> getMasterKey(PGPPublicKey publicKey, PGPPublicKeyRing publicKeyRing) {

    if (publicKey.isMasterKey()) {
        return Optional.empty();
    }

    Iterator<?> signatures = publicKey.getSignaturesOfType(PGPSignature.SUBKEY_BINDING);
    if (signatures.hasNext()) {
        PGPSignature sig = (PGPSignature) signatures.next();
        return Optional.ofNullable(publicKeyRing.getPublicKey(sig.getKeyID()));
    }

    return Optional.empty();
}
 
Example #10
Source File: AptSigningFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
public byte[] signInline(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.CANONICAL_TEXT_DOCUMENT, privKey);

  @SuppressWarnings("unchecked")
  Iterator<String> userIds = signKey.getUserIDs();
  if (userIds.hasNext()) {
    PGPSignatureSubpacketGenerator sigSubpacketGenerator = new PGPSignatureSubpacketGenerator();
    sigSubpacketGenerator.setSignerUserID(false, userIds.next());
    sigGenerator.setHashedSubpackets(sigSubpacketGenerator.generate());
  }

  String[] lines = input.split("\r?\n");
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
    aOut.beginClearText(PGPUtil.SHA256);

    boolean firstLine = true;
    for (String line : lines) {
      String sigLine = (firstLine ? "" : "\r\n") + line.replaceAll("\\s*$", "");
      sigGenerator.update(sigLine.getBytes(Charsets.UTF_8));
      aOut.write((line + "\n").getBytes(Charsets.UTF_8));
      firstLine = false;
    }
    aOut.endClearText();

    BCPGOutputStream bOut = new BCPGOutputStream(aOut);
    sigGenerator.generate().encode(bOut);
  }
  return buffer.toByteArray();
}
 
Example #11
Source File: AptSigningFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
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();
}
 
Example #12
Source File: AptSigningFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public byte[] signInline(final String input) throws IOException {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  try {
    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.CANONICAL_TEXT_DOCUMENT, privKey);

    Iterator<String> userIds = signKey.getUserIDs();
    if (userIds.hasNext()) {
      PGPSignatureSubpacketGenerator sigSubpacketGenerator = new PGPSignatureSubpacketGenerator();
      sigSubpacketGenerator.setSignerUserID(false, userIds.next());
      sigGenerator.setHashedSubpackets(sigSubpacketGenerator.generate());
    }

    String[] lines = input.split("\r?\n");
    try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
      aOut.beginClearText(PGPUtil.SHA256);

      boolean firstLine = true;
      for (String line : lines) {
        String sigLine = (firstLine ? "" : "\r\n") + line.replaceAll("\\s*$", "");
        sigGenerator.update(sigLine.getBytes(Charsets.UTF_8));
        aOut.write((line + "\n").getBytes(Charsets.UTF_8));
        firstLine = false;
      }
      aOut.endClearText();

      BCPGOutputStream bOut = new BCPGOutputStream(aOut);
      sigGenerator.generate().encode(bOut);
    }
  }
  catch (PGPException ex) {
    throw new RuntimeException(ex);
  }
  return buffer.toByteArray();
}
 
Example #13
Source File: SigningStream.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
protected void testInit () throws IOException
{
    if ( this.initialized )
    {
        return;
    }

    this.initialized = true;

    try
    {
        this.signatureGenerator = new PGPSignatureGenerator ( new BcPGPContentSignerBuilder ( this.privateKey.getPublicKeyPacket ().getAlgorithm (), this.digestAlgorithm ) );
        this.signatureGenerator.init ( PGPSignature.BINARY_DOCUMENT, this.privateKey );

        this.armoredOutput = new ArmoredOutputStream ( this.stream );
        if ( this.version != null )
        {
            this.armoredOutput.setHeader ( "Version", this.version );
        }

        if ( this.inline )
        {
            this.armoredOutput.beginClearText ( this.digestAlgorithm );
        }
    }
    catch ( final PGPException e )
    {
        throw new IOException ( e );
    }
}
 
Example #14
Source File: RsaHeaderSignatureProcessor.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void feedHeader ( final ByteBuffer header )
{
    try
    {
        final BcPGPContentSignerBuilder contentSignerBuilder = new BcPGPContentSignerBuilder ( this.privateKey.getPublicKeyPacket ().getAlgorithm (), this.hashAlgorithm );
        final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator ( contentSignerBuilder );

        signatureGenerator.init ( PGPSignature.BINARY_DOCUMENT, this.privateKey );

        if ( header.hasArray () )
        {
            signatureGenerator.update ( header.array (), header.position (), header.remaining () );
        }
        else
        {
            final byte[] buffer = new byte[header.remaining ()];
            header.get ( buffer );
            signatureGenerator.update ( buffer );
        }

        this.value = signatureGenerator.generate ().getEncoded ();
        logger.info ( "RSA HEADER: {}", this.value );
    }
    catch ( final Exception e )
    {
        throw new RuntimeException ( e );
    }
}
 
Example #15
Source File: PGPVerifyMojo.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void verifyWeakSignature(PGPSignature pgpSignature) throws MojoFailureException {
    final String weakHashAlgorithm = PGPSignatureUtils.checkWeakHashAlgorithm(pgpSignature);
    if (weakHashAlgorithm == null) {
        return;
    }
    final String logMessage = "Weak signature algorithm used: " + weakHashAlgorithm;
    if (failWeakSignature) {
        getLog().error(logMessage);
        throw new MojoFailureException(logMessage);
    } else {
        getLog().warn(logMessage);
    }
}
 
Example #16
Source File: PGPSignatureUtils.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Check PGP signature for bad algorithms.
 *
 * @param signature PGP signature instance
 *
 * @return Returns null if no bad algorithms used, or algorithm name if used.
 */
public static String checkWeakHashAlgorithm(PGPSignature signature) {
    switch (signature.getHashAlgorithm()) {
        case HashAlgorithmTags.MD5:
            return "MD5";
        case HashAlgorithmTags.DOUBLE_SHA:
            return "double-width SHA";
        case HashAlgorithmTags.MD2:
            return "MD2";
        case HashAlgorithmTags.TIGER_192:
            return "TIGER/192";
        case HashAlgorithmTags.HAVAL_5_160:
            return "HAVAL (5 pass, 160-bit)";
        case HashAlgorithmTags.SHA224:
            return "SHA-224";
        case HashAlgorithmTags.SHA1:
            // fallthrough
        case HashAlgorithmTags.RIPEMD160:
            // fallthrough
        case HashAlgorithmTags.SHA256:
            // fallthrough
        case HashAlgorithmTags.SHA384:
            // fallthrough
        case HashAlgorithmTags.SHA512:
            return null;
        default:
            throw new UnsupportedOperationException("Unknown hash algorithm value encountered: "
                    + signature.getHashAlgorithm());
    }
}
 
Example #17
Source File: PGPSignatureUtils.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Read the content of a file into the PGP signature instance (for verification).
 *
 * @param signature the PGP signature instance. The instance is expected to be initialized.
 * @param file      the file to read
 *
 * @throws IOException In case of failure to open the file or failure while reading its content.
 */
public static void readFileContentInto(final PGPSignature signature, final File file) throws IOException {
    try (InputStream inArtifact = new BufferedInputStream(new FileInputStream(file))) {
        int t;
        while ((t = inArtifact.read()) >= 0) {
            signature.update((byte) t);
        }
    }
}
 
Example #18
Source File: BouncyCastleTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignVerify_Detached() 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".
  // Note: RSA_GENERAL will encrypt AND sign. RSA_SIGN and RSA_ENCRYPT are deprecated.
  PGPSignatureGenerator signer = new PGPSignatureGenerator(
      new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256));
  signer.init(PGPSignature.BINARY_DOCUMENT, privateKey);
  addUserInfoToSignature(publicKey, signer);
  signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  signer.generate().encode(output);
  byte[] signatureFileData = output.toByteArray();
  logger.atInfo().log(".sig file data: %s", dumpHex(signatureFileData));

  // Load algorithm information and signature data from "signatureFileData".
  PGPSignature sig;
  try (ByteArrayInputStream input = new ByteArrayInputStream(signatureFileData)) {
    PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
    PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject();
    assertThat(sigList.size()).isEqualTo(1);
    sig = sigList.get(0);
  }

  // Use "onePass" and "sig" to verify "publicKey" signed the text.
  sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
  sig.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
  assertThat(sig.verify()).isTrue();

  // Verify that they DIDN'T sign the text "hello monster".
  sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
  sig.update("hello monster".getBytes(UTF_8));
  assertThat(sig.verify()).isFalse();
}
 
Example #19
Source File: PublicKeyUtils.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static void verifySigForSubKey(PGPPublicKey subKey, PGPPublicKeyRing publicKeyRing) throws PGPException {

        int signatureTypeToCheck = subKey.hasRevocation()
                ? PGPSignature.SUBKEY_REVOCATION : PGPSignature.SUBKEY_BINDING;

        AtomicBoolean hasValidSignature = new AtomicBoolean(false);

        Iterator<?> it = subKey.getSignaturesOfType(signatureTypeToCheck);
        it.forEachRemaining(s -> Try.run(() -> {
                    PGPSignature sig = (PGPSignature) s;

                    PGPPublicKey masterKey = publicKeyRing.getPublicKey(sig.getKeyID());
                    if (masterKey != null) {
                        sig.init(new BcPGPContentVerifierBuilderProvider(), masterKey);
                        if (sig.verifyCertification(masterKey, subKey)) {
                            hasValidSignature.set(true);
                        } else {
                            LOGGER.debug("Invalid signature [{}] type: {} for subKey: {}",
                                    sig.getCreationTime(), sig.getSignatureType(), fingerprint(subKey));
                        }
                    } else {
                        throw new PGPException(
                                String.format("Signature type: %d Not found key 0x%016X for subKeyId: %s",
                                sig.getSignatureType(), sig.getKeyID(), fingerprint(subKey)));
                    }
                }).get()
        );

        if (!hasValidSignature.get()) {
            throw new PGPException(String.format("No valid signature type: %d for subKey: %s",
                    signatureTypeToCheck, fingerprint(subKey)));
        }
    }
 
Example #20
Source File: PGPSignatureUtilsTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadSignatureContentIsSignature() throws IOException, PGPSignatureException {

    try (InputStream input = getClass().getResourceAsStream("/helloworld-1.0.jar.asc")) {
        PGPSignature signature = PGPSignatureUtils.loadSignature(input);
        assertThat(signature.getKeyID()).isEqualTo(0x9F1A263E15FD0AC9L);
    }
}
 
Example #21
Source File: PGPSignatureUtilsTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "provider-signature-hash-algorithms")
public void testCheckWeakHashAlgorithmAllAlgorithms(int algorithm, boolean strong) {

    PGPSignature sig = mock(PGPSignature.class);
    when(sig.getHashAlgorithm()).thenReturn(algorithm);

    assertThat(PGPSignatureUtils.checkWeakHashAlgorithm(sig) == null).isEqualTo(strong);
}
 
Example #22
Source File: PGPSignatureUtilsTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckWeakHashAlgorithmsUnknownAlgorithm() {

    PGPSignature sig = mock(PGPSignature.class);
    when(sig.getHashAlgorithm()).thenReturn(999);

    assertThatCode(() -> PGPSignatureUtils.checkWeakHashAlgorithm(sig))
            .isExactlyInstanceOf(UnsupportedOperationException.class);
}
 
Example #23
Source File: PGPSignatureUtilsTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void loadSignatureFromPGPMessage() throws IOException, PGPSignatureException {

    try (InputStream input = getClass().getResourceAsStream("/fop-0.95.pom.asc")) {
        PGPSignature signature = PGPSignatureUtils.loadSignature(input);
        assertThat(signature.getKeyID()).isEqualTo(0x8E1E35C66754351BL);
    }
}
 
Example #24
Source File: PGPSignatureUtilsTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void signatureKeyIdFromSubpackage() throws IOException, PGPSignatureException {
    PGPSignature signature;

    try (InputStream input = getClass().getResourceAsStream("/helloworld-1.0.jar.asc")) {
        signature = PGPSignatureUtils.loadSignature(input);
    }

    PGPKeyId pgpKeyId = PGPSignatureUtils.retrieveKeyId(signature);
    assertThat(pgpKeyId).asString().isEqualTo("0x466583F9480EBE2462C46B309F1A263E15FD0AC9");
}
 
Example #25
Source File: PGPSignatureUtilsTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void signatureKeyIdFromSubpackageIssuerKeyInHashed() throws IOException, PGPSignatureException {
    PGPSignature signature;

    try (InputStream input = getClass().getResourceAsStream("/ant-launcher-1.9.4.jar.asc")) {
        signature = PGPSignatureUtils.loadSignature(input);
    }

    PGPKeyId pgpKeyId = PGPSignatureUtils.retrieveKeyId(signature);
    assertThat(pgpKeyId).asString().isEqualTo("0x5EFAD9FE82A7FBCD");
}
 
Example #26
Source File: Decryptor.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
private static DecryptionResult verifySignature(DecryptionResult result,
        PGPObjectFactory pgpFact, PGPOnePassSignature ops) throws PGPException, IOException {
    Object object = pgpFact.nextObject(); // nullable
    if (!(object instanceof PGPSignatureList)) {
        LOGGER.warning("invalid signature packet");
        result.errors.add(Coder.Error.INVALID_SIGNATURE_DATA);
        return result;
    }

    PGPSignatureList signatureList = (PGPSignatureList) object;
    if (signatureList.isEmpty()) {
        LOGGER.warning("no signature in signature list");
        result.errors.add(Coder.Error.INVALID_SIGNATURE_DATA);
        return result;
    }

    PGPSignature signature = signatureList.get(0);
    // TODO signature.getCreationTime()
    if (ops.verify(signature)) {
        // signature verification successful!
        result.signing = Coder.Signing.VERIFIED;
    } else {
        LOGGER.warning("signature verification failed");
        result.errors.add(Coder.Error.INVALID_SIGNATURE);
    }
    return result;
}
 
Example #27
Source File: PGPUtils.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
private static int getKeyFlags(PGPPublicKey key) {
    @SuppressWarnings("unchecked")
    Iterator<PGPSignature> sigs = key.getSignatures();
    while (sigs.hasNext()) {
        PGPSignature sig = sigs.next();
        PGPSignatureSubpacketVector subpackets = sig.getHashedSubPackets();
        if (subpackets != null)
            return subpackets.getKeyFlags();
    }
    return 0;
}
 
Example #28
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
private static void processLine( PGPSignature sig, byte[] line ) throws SignatureException, IOException
{
    int length = getLengthWithoutWhiteSpace( line );
    if ( length > 0 )
    {
        sig.update( line, 0, length );
    }
}
 
Example #29
Source File: PGPSignatureUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if publicKey is signed by signerPublicKey, without any verification. In future we have to review carefully
 * the PGP Specs and implement the verification. See also: http://osdir.com/ml/encryption.bouncy-castle
 * .devel/2006-12/msg00005.html
 */
public static boolean isSignedBy( PGPPublicKey pubKey, PGPPublicKey signerPubKey )
{
    PGPSignature sig = getSignatures( pubKey ).get( signerPubKey.getKeyID() );

    return sig != null && ( sig.getSignatureType() == PGPSignature.DEFAULT_CERTIFICATION
            || sig.getSignatureType() == PGPSignature.DIRECT_KEY );
}
 
Example #30
Source File: PGPSignatureUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a map containing key IDs and corresponding signatures.
 */
public static Map<Long, PGPSignature> getSignatures( PGPPublicKey pubKey )
{
    HashMap<Long, PGPSignature> sigs = new HashMap<>();
    Iterator signatures = pubKey.getSignatures();

    while ( signatures.hasNext() )
    {
        PGPSignature sign = ( PGPSignature ) signatures.next();

        sigs.put( sign.getKeyID(), sign );
    }

    return sigs;
}