Question

Decrypt pgp file using bouncycastle api

Asked by: alexk23

Hello, I am trying to decrypt PGP encrypted file. The file was encrypted using my public key that I generated. I could encrypt and decrypt the files that I created locally using bouncycastle API, but when my client encrypts the file on his side I am not able to decrypt it using bouncycastle API but could decrypt it manually using gnupg on command prompt.

When run decryption in my class I am not able to find secret key to decrypt the file. And I am not sure how my client decrypts it.

Please let me know if you have any suggestions.

import org.bouncycastle.openpgp.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
 
 
import java.io.*;
import java.util.Iterator;
import java.security.NoSuchProviderException;
import java.security.Security;
 
 
 
public class PGPSecurityService {
    public PGPSecurityService(){}
 
    public static  void main(String[] args){
        try{
            Security.addProvider(new BouncyCastleProvider());
            FileInputStream privKey = new FileInputStream("C:\\apps\\private\\secring.gpg");
            InputStream file = new BufferedInputStream (new FileInputStream("C:\\apps\\private\\encrypted.pgp"));
            System.out.println(decryptFile(file, privKey, "mykey".toCharArray()));
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }
 
 
    private static String decryptFile(InputStream in, InputStream keyIn, char[] passwd) throws Exception {
        try {
            PGPObjectFactory pgpF = new PGPObjectFactory(PGPUtil.getDecoderStream(in));
            Object o = pgpF.nextObject();
            PGPEncryptedDataList enc = o instanceof  PGPEncryptedDataList ? (PGPEncryptedDataList) o :(PGPEncryptedDataList) pgpF.nextObject();
            Iterator it = enc.getEncryptedDataObjects();
            PGPPrivateKey sKey = null;
            PGPPublicKeyEncryptedData pbe = null;
 
            while (sKey == null && it.hasNext()) {
                pbe = (PGPPublicKeyEncryptedData) it.next();
                sKey =findSecretKey(keyIn, pbe.getKeyID(), passwd);
            }
            if (sKey == null) {
 
                throw new IllegalArgumentException("secret key for message not found.");
            }
 
            InputStream clear = pbe.getDataStream(sKey, "BC");
            PGPObjectFactory plainFact = new PGPObjectFactory(clear);
            Object message = plainFact.nextObject();
            if (message instanceof  PGPCompressedData) {
                PGPCompressedData cData = (PGPCompressedData) message;
                PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream());
                message = pgpFact.nextObject();
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (message instanceof PGPLiteralData) {
                PGPLiteralData ld = (PGPLiteralData) message;
                InputStream unc = ld.getInputStream();
                int ch;
                while ((ch = unc.read()) >= 0) {
                    baos.write(ch);
                }
            } else if (message instanceof  PGPOnePassSignatureList) {
                throw new PGPException("encrypted message contains a signed message - not literal data.");
            } else {
                throw new PGPException("message is not a simple encrypted file - type unknown.");
            }
 
            if (pbe.isIntegrityProtected()) {
               if (!pbe.verify()) {
                    System.err.println("message failed integrity check");
               }
            } else {
                System.err.println("no message integrity check");
            }
            return baos.toString();
        } catch (PGPException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    private static PGPPrivateKey findSecretKey(InputStream keyIn, long keyID, char[] pass) throws IOException, PGPException, NoSuchProviderException {
        PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));
        System.out.println("pgpSec size="+pgpSec);
        System.out.println(keyID);
        PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
        return pgpSecKey != null? pgpSecKey.extractPrivateKey(pass, "BC"): null;
    }
    /*
    public static String decrypt(byte[] encdata, String keyLocation, String phrase) {
            try {
                ByteArrayInputStream bais = new ByteArrayInputStream(encdata);
                FileInputStream privKey = new FileInputStream(keyLocation);
                return decryptFile(bais, privKey, phrase.toCharArray());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        */
  
 
}

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-04-22 at 08:58:59ID24345724
Tags

decrypt bouncycastle pgp

Topic

Java Programming Language

Participating Experts
2
Points
500
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. PGP?
    Hi, I am trying to grab bunch of PGP files from a ftp site and decrypt them from local machine (HP-UX). I was able to download files but can not decrypt files using perl script. I have pgp-6.5.8 installed on my machine along with perl-5.6.0. I do not wish to use CPAN modul...
  2. PGP Howto
    Hi, I manage to install new pgp rpm into Linux box version 6.5. I encrypt a file with receipent user id and sent the encrypted file together with my public key. The receipient can decrypt the file successfully. Then, the receipient (PGP Client on Windows), encrypt one fil...
  3. PGP Decryption - Manual vs programmatically
    I've inherited an old application that uses PGP 6.5.2 and VB6. I am trying to decrypt a file from a vendor. I am able to decrypt it if I right-mouse-click on it in Windows Explorer and select PGP, Decrypt. But if I try to do it programmatically I get a "PGP Error 32: Dec...
  4. VB and PGP Decryption
    Hi: I have a VB 6.0 application that needs to download files from an FTP site where the files are PGP encrypted. I've been doing a little research, but have been a little confused by the results I've found. There seem to be a variety of free and pay-for solutions out there....

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: gibu_georgePosted on 2009-04-22 at 09:01:00ID: 24206406

What is the error/exception thrown  when you try to decrypt?

 

by: CEHJPosted on 2009-04-22 at 09:03:12ID: 24206437

>>but when my client encrypts the file on his side I am not able to decrypt it using bouncycastle API

You are, i assume, attempting to decrypt it using his *public* key are you? That's what you must do

 

by: alexk23Posted on 2009-04-22 at 09:13:16ID: 24206536

The error is throwing by my null check when I am checking if the key is null
throw new IllegalArgumentException("secret key for message not found.");

 

by: alexk23Posted on 2009-04-22 at 09:15:40ID: 24206569

CEHJ, I am trying to decrypt the file by my secret key that I used to generate the public key for my client. Are you saying I should use public key to decrypt the file as well?

 

by: CEHJPosted on 2009-04-22 at 09:25:56ID: 24206690

You decrypt messages *he* sends using *his* public key. He encrypts his own messages using his private key

 

by: alexk23Posted on 2009-04-22 at 09:41:44ID: 24206858

CEHJ, no the message is being encrypted using public key that I sent to them. And I am able to decrypt the message on command prompt using GnuPG. I checked the path to the secret key and the file I am trying to decrypt all looks good just can't find the key to decrypt encrypted file using my implementation of bouncy castle api

 

by: CEHJPosted on 2009-04-22 at 09:45:27ID: 24206911

Sorry alexk23, what i just said was wrong.

He encrypts messages he sends to you using *your* public key. Is that what's happening?

 

by: alexk23Posted on 2009-04-22 at 09:48:45ID: 24206942

Yes. let me know if you would like to see the encrypted file.

 

by: alexk23Posted on 2009-04-22 at 10:24:18ID: 24207306

Thaks CEHJ, let me look at it and will let you know!

 

by: alexk23Posted on 2009-04-22 at 13:00:17ID: 24208959

The example does almost the same thing in comparing the keys, but the problem is that when I compare the public vs. private keys I am getting following results:

Data was encrypted using public key:  -4270675083819455261
Data was encrypted using public key:  5471684833902076854

Got secret key: -7878772790183064541 mask=true SigningKey = true
Got secret key: 5471684833902076854 mask=false SigningKey= false

But it still puzzles me how I was able to decrypt same file in command prompt I got couple messages but was able to decrypt it.

gpg: Signature made 04/21/09 03:41:20  using DSA key ID 2BD4FDE5
gpg: Can't check signature: public key not found
gpg: WARNING: message was not integrity protected

 

by: alexk23Posted on 2009-04-27 at 20:39:37ID: 24247415

I figured it out the problem was with the message was encrypted and signed so I had to check the message signature first. Although example wasnt clear and had some issues but gave me an idea, thanks CEHJ

import org.bouncycastle.openpgp.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
 
import java.io.*;
import java.util.Iterator;
 
 
import java.security.NoSuchProviderException;
import java.security.Security;
 
 
 
public class PGPSecurityService {
 
 
    public static  void main(String[] args){
        try{
            Security.addProvider(new BouncyCastleProvider());
 
            /**
             * decrypt file
             **/
            // my private key
            InputStream privKey = new BufferedInputStream (new FileInputStream("C:\\apps\\private\\secring.gpg"));
            // file to decrypt
            InputStream file = new BufferedInputStream (new FileInputStream("C:\\apps\\encrypted.pgp"));
 
            decryptFile(file, privKey,"mykey".toCharArray());
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }
 
    private static PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection  pgpSec, long keyID, char[] pass)
        throws PGPException, NoSuchProviderException{
        PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
        if (pgpSecKey == null){
            return null;
        } else {
            return pgpSecKey.extractPrivateKey(pass, "BC");
        }
    }
 
    private static PGPPublicKey readPublicKeyFromCol(InputStream in)throws Exception {
        PGPPublicKeyRing pkRing = null;
        PGPPublicKeyRingCollection pkCol = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(in));
        //System.out.println("key ring size=" + pkCol.size());
        Iterator it = pkCol.getKeyRings();
        while (it.hasNext()) {
            pkRing = (PGPPublicKeyRing) it.next();
            Iterator pkIt = pkRing.getPublicKeys();
            while (pkIt.hasNext()) {
                PGPPublicKey key = (PGPPublicKey) pkIt.next();
                //System.out.println("Encryption key = " + key.isEncryptionKey() + ", Master key = " +key.isMasterKey());
                if (key.isMasterKey())
                    return key;
            }
        }
        return null;
    }
 
    private static void decryptFile( InputStream in, InputStream keyIn, char[] passwd)throws Exception{
        in = PGPUtil.getDecoderStream(in);
        try{
            PGPObjectFactory pgpF = new PGPObjectFactory(in);
            Object o = pgpF.nextObject();
            PGPEncryptedDataList enc = o instanceof PGPEncryptedDataList?(PGPEncryptedDataList)o : (PGPEncryptedDataList)pgpF.nextObject();
 
 
 
            //
            // the first object might be a PGP marker packet.
            //
            /*
            if (o instanceof PGPEncryptedDataList){
                enc = (PGPEncryptedDataList)o;
            }  else {
                enc = (PGPEncryptedDataList)pgpF.nextObject();
            }
            */
            //
            // find the secret key
            //
            Iterator it = enc.getEncryptedDataObjects();
            PGPPrivateKey sKey = null;
            PGPPublicKeyEncryptedData pbe = null;
            PGPSecretKeyRingCollection  pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));
 
            while (sKey == null && it.hasNext()){
                pbe = (PGPPublicKeyEncryptedData)it.next();
                sKey = findSecretKey(pgpSec, pbe.getKeyID(), passwd);
            }
            if (sKey == null){
                throw new IllegalArgumentException("secret key for message not found.");
            }
 
            InputStream clear = pbe.getDataStream(sKey, "BC");
            PGPObjectFactory plainFact = new PGPObjectFactory(clear);
            Object message = plainFact.nextObject();
            if (message instanceof PGPCompressedData){
                PGPCompressedData   cData = (PGPCompressedData)message;
                PGPObjectFactory  pgpFact = new PGPObjectFactory(cData.getDataStream());
                message = pgpFact.nextObject();
                if (message instanceof PGPLiteralData){
                    PGPLiteralData      ld = (PGPLiteralData)message;
                    FileOutputStream    fOut = new FileOutputStream("C:\\apps\\private\\outputsigned.txt");
                    InputStream    unc = ld.getInputStream();
                    int    ch;
                    while ((ch = unc.read()) >= 0){
                        fOut.write(ch);
                    }
                }else if (message instanceof PGPOnePassSignatureList) {
 
                    PGPOnePassSignatureList p1 = (PGPOnePassSignatureList) message;
                    InputStream pubKey = new BufferedInputStream (new FileInputStream("C:\\apps\\private\\pubring.gpg"));
                    PGPPublicKey key =readPublicKeyFromCol(pubKey);
                    if(key!=null){
                        PGPOnePassSignature ops = p1.get(0);
                        System.out.println("ops.getKeyID()="+ops.getKeyID());
                        ops.initVerify(key, "BC");
                        // file output dirctory
                        FileOutputStream out = new FileOutputStream("C:\\apps\\private\\outputsigned.txt");
                        PGPLiteralData  p2 = (PGPLiteralData) pgpFact.nextObject();
                        int ch;
                        InputStream  dIn = p2.getInputStream();
                        while ((ch = dIn.read()) >= 0) {
                            ops.update((byte)ch);
                            out.write(ch);
                        }
                        out.close();
                    } else {
                        throw new PGPException ("unable to find public key for signed file");
                    }
                } else {
                    throw new PGPException("message is not a simple encrypted file - type unknown.");
                }
 
                if (pbe.isIntegrityProtected()){
                    if (!pbe.verify()){
                        System.err.println("message failed integrity check");
                    } else{
                        System.err.println("message integrity check passed");
                    }
                } else {
                    System.err.println("no message integrity check");
                }
            } else {
                System.out.println("unable to verify message");
            }
        }catch (PGPException e){
            System.err.println(e);
            if (e.getUnderlyingException() != null){
                e.getUnderlyingException().printStackTrace();
            }
        }
    }
 
 
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:

Select allOpen in new window

 

by: alexk23Posted on 2009-04-27 at 20:40:47ID: 31573353

Although example wasnt clear and had some issues but gave me an idea, thanks CEHJ

 

by: CEHJPosted on 2009-04-28 at 00:15:04ID: 24248276

Good :-)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...