Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Problem in enc/dec with DSA-Elgamal (keys generated using GNUPG utility)

843811Feb 1 2006 — edited Jan 31 2007
Hi all

Facing the problem in encryption/decryption using DSA-Elgamal (keys generated using GNUPG utility)


Steps followed

Generated a key pair using DSA and Elgamal (default) form GNUPG utility (size 1024)
Placed generated keys pubring.gpg & secring.gpg in the source directory where the code is executing but am getting the error


D:\test>c:\jdk\bin\java BouncyCastlePGPTest
Creating a temp file...
Temp file created at
D:\test\pgp
Reading the temp file to make sure that the bits were written
----------------------------
the message I want to encrypt

Get Public Key
Key Strength = 1024
Algorithm = 17
mohankumar (start) <mohan@test.com>
Key Count = 1
In Ecrypt File
creating comData...
comData created...
using PGPEncryptedDataGenerator...
111...
java.lang.IllegalArgumentException: passed in key not an encryption key!f

D:\test>



but the same code works fine if we try to encrypt using RSA generated keys

D:\test>c:\jdk\bin\java BouncyCastlePGPTest
Creating a temp file...
Temp file created at
D:\test\pgp
Reading the temp file to make sure that the bits were written
----------------------------
the message I want to encrypt

Get Public Key
Key Strength = 1024
Algorithm = 1
sriganesh (sriganesh) <ganesh@test.com>
Key Count = 1
In Ecrypt File
creating comData...
comData created...
using PGPEncryptedDataGenerator...
used PGPEncryptedDataGenerator...
wrote bOut to byte array...
Reading the encrypted file
----------------------------
-----BEGIN PGP MESSAGE-----
Version: BCPG v1.31

hIwD7qqzP41CKpUBBACOnQE265ud3AuJ8zGx9TjUFyeSwZH+PZJhjGLBTkI7gKdh
/hIF1u/sCzubw+9Mt8dbS0V2uHiqQgkCHAYIQKoVmiN65s8sUsIS0q3cTtBudUnd
xIEiyegtvB8LEpzldU/XrSglh8h6MdhhcPql46BG+0vs6p/bUAOygNv5e/DGzck2
1wNvc2/u2ffBgEP4qfrJUcF9OlvVAm03aB0S6gP8cH4LVdo5K9Bwu3d71qNKsryP
mML16rkA
=lfxf
-----END PGP MESSAGE-----



Decrypted Data= the message I want to encrypt



no message integrity check

______________

Code As follows


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.*;
import java.util.Iterator;


public class BouncyCastlePGPTest {

private static PGPPrivateKey findSecretKey(
InputStream keyIn,
long keyID,
char[] pass)
throws IOException, PGPException, NoSuchProviderException {
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));

PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
if (pgpSecKey == null) {
return null;
}
return pgpSecKey.extractPrivateKey(pass, "BC");
}

private static void decryptFile(InputStream in, InputStream keyIn, char[] passwd) throws Exception
{
in = PGPUtil.getDecoderStream(in);

try {
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc;

Object o = 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;

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();
}

if (message instanceof PGPLiteralData)
{
PGPLiteralData ld = (PGPLiteralData)message;

FileOutputStream fOut = new FileOutputStream(ld.getFileName());

InputStream unc = ld.getInputStream();
int ch;
System.out.print("\n\n\nDecrypted Data= ");
while ((ch = unc.read()) >= 0)
{
System.out.print(""+(char)ch);
fOut.write(ch);
}
System.out.println("\n\n\n");
}
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("message integrity check passed");
}
}
else
{
System.err.println("no message integrity check");
}
}
catch (PGPException e) {
System.err.println(e);
if (e.getUnderlyingException() != null) {
e.getUnderlyingException().printStackTrace();
}
}
}


public static void main(String[] args) {

// the keyring that holds the public key we're encrypting with
String publicKeyFilePath = "D:\\test\\pubring.gpg"; //D:\\test\\pubring.pkr;

// init the security provider
Security.addProvider(new BouncyCastleProvider());

try {

System.out.println("Creating a temp file...");

// create a file and write the string to it
File outputfile = new File("pgp");//File.createTempFile("pgp", null);
FileWriter writer = new FileWriter(outputfile);
writer.write("the message I want to encrypt".toCharArray());
writer.close();

System.out.println("Temp file created at ");
System.out.println(outputfile.getAbsolutePath());
System.out.println("Reading the temp file to make sure that the bits were written\n----------------------------");

BufferedReader isr = new BufferedReader(new FileReader(outputfile));
String line = "";
while ((line = isr.readLine()) != null) {
System.out.println(line + "\n");
}

// read the key
FileInputStream in = new FileInputStream(publicKeyFilePath);
PGPPublicKey key = readPublicKey(in);

// find out a little about the keys in the public key ring
System.out.println("Key Strength = " + key.getBitStrength());
System.out.println("Algorithm = " + key.getAlgorithm());

int count = 0;
for (java.util.Iterator iterator = key.getUserIDs(); iterator.hasNext();) {
count++;
System.out.println((String)iterator.next());
}
System.out.println("Key Count = " + count);
// create an armored ascii file
FileOutputStream out = new FileOutputStream(outputfile.getAbsolutePath() + ".asc");

// encrypt the file
encryptFile(outputfile.getAbsolutePath(), out, key);

System.out.println("Reading the encrypted file\n----------------------------");
BufferedReader isr2 = new BufferedReader(new FileReader(new File(outputfile.getAbsolutePath() + ".asc")));
String line2 = "";
while ((line2 = isr2.readLine()) != null) {
System.out.println(line2);
}

//FileInputStream in = new FileInputStream(args[1]);
FileInputStream in2 = new FileInputStream("d:\\test\\pgp.asc");
FileInputStream keyIn = new FileInputStream("d:\\test\\secring.gpg");
decryptFile(in2, keyIn, "test123".toCharArray());
} catch (PGPException e) {
System.out.println(e.toString());
System.out.println(e.getUnderlyingException().toString());

} catch (Exception e) {
System.out.println(e.toString());
}

}

private static PGPPublicKey readPublicKey(InputStream in) throws IOException {
System.out.println("Get Public Key");
try {
PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(in);

Iterator itr = pgpPub.getPublicKeys();
PGPPublicKey pk = null;
return pgpPub.getPublicKey();
} catch (IOException io) {
System.out.println("readPublicKey() threw an IOException");
System.out.println(io.toString());
throw io;
}

}





private static void encryptFile(String fileName, OutputStream out, PGPPublicKey encKey)
// throws IOException, NoSuchProviderException, PGPException
{

try {

System.out.println("In Ecrypt File");
out = new ArmoredOutputStream(out);

ByteArrayOutputStream bOut = new ByteArrayOutputStream();

System.out.println("creating comData...");

// get the data from the original file
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
comData.close();

System.out.println("comData created...");

System.out.println("using PGPEncryptedDataGenerator...");

// object that encrypts the data
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.CAST5, new SecureRandom(), "BC");
cPk.addMethod(encKey);
System.out.println("used PGPEncryptedDataGenerator...");

// take the outputstream of the original file and turn it into a byte array
byte[] bytes = bOut.toByteArray();

System.out.println("wrote bOut to byte array...");

// write the plain text bytes to the armored outputstream
OutputStream cOut = cPk.open(out, bytes.length);
cOut.write(bytes);

// cOut.close();
cPk.close();
out.close();

} catch (IOException ex) {
System.out.println("IOException\t" +ex.toString());
} catch (NoSuchProviderException ex1) {
System.out.println("NoSuchProviderException\t" +ex1.toString());
} catch (PGPException ex2) {
System.out.println("PGPException\t" +ex2.toString());
}
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 28 2007
Added on Feb 1 2006
2 comments
695 views