I have an existing PGP v 1.60 code in project. now I need to update to 1.70 and it's throwing following error while compiling the code after update.
incompatible types: java.util.Iterator<org.bouncycastle.openpgp.PGPEncryptedData> cannot be converted to java.util.Iterator<org.bouncycastle.openpgp.PGPPublicKeyEncryptedData>
Getting the error exactly in this line -> Iterator<PGPPublicKeyEncryptedData> it = enc.getEncryptedDataObjects();
Kindly find the code sample below
public static void decryptFile(Input in, Output out,Input keyIn, char[] password) {
Security.addProvider(new BouncyCastleProvider());
in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in);
KeyFingerPrintCalculator calc = new JcaKeyFingerprintCalculator();
PGPObjectFactory pgpF = new PGPObjectFactory(in,calc);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
Iterator<PGPPublicKeyEncryptedData> it = enc.getEncryptedDataObjects(); //getting error here
PGPPrivateKey key1 = null;
PGPPublicKeyEncryptedData key2 = null;
}
can someone help me here please.
The return type of getEncryptedDataObjects
has changed apparently. The line with the error should be changed to:
Iterator<PGPEncryptedData> it = enc.getEncryptedDataObjects();
PGPPublicKeyEncryptedData
is one type (i.e. subclass) of PGPEncryptedData
but later versions of the API support also returning data of type PGPSymmetricKeyEncryptedData
(with two further subtypes), so the iterator allows both types to be returned.
If you want to then process only the PGPPublicKeyEncryptedData
entries from the iterator (to follow your old code's functionality), you can use instanceof
e.g.:
Iterator<PGPEncryptedData> it = enc.getEncryptedDataObjects();
while (it.hasNext())
{
PGPEncryptedData encryptedData = it.next();
if (encryptedData instanceof PGPPublicKeyEncryptedData)
{
PGPPublicKeyEncryptedData pkEncryptedData = (PGPPublicKeyEncryptedData)encryptedData;
// Process pkEncryptedData as needed.
}
}