Solved

while ( (line = isr.readLine()) != null ) Error Message - nbsp cannot be resolved to a variable

Posted on 2011-03-06
14
854 Views
Last Modified: 2012-05-11
Hi All,

    I am trying to build the Bouncycastle - SingleSingOnTest example in Eclipse.

    But I have several error messages on &nsbp and &gt etc that is stopping the program from compiling.

e.g.

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

where I get the error message - nbsp cannot be resolved to a variable
and

while (sKey == null && it.hasNext()) {
                             pbe = (PGPPublicKeyEncryptedData) it.next();
                             System.out.println("pbe id=" + pbe.getKeyID());
                             sKey = findSecretKey(keyIn, pbe.getKeyID(), passwd);
                     }

with the error message - amp cannot be resolved to a variable

    Is there a class or eclipse setting that I need to use to allow eclipse to interpret this code

0
Comment
Question by:ericdavidsonca
  • 5
  • 4
  • 3
  • +2
14 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 35046408
Looks like your source code is full of html entities: you need to get rid of them
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35046411
Should be
while (sKey == null && it.hasNext()) { // etc

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35046417
And
while ((line = isr.readLine()) != null )

Open in new window

0
 

Author Comment

by:ericdavidsonca
ID: 35046438
This is a example sourecode for using bouncycastle.

and can be found here
http://wiki.service-now.com/index.php?title=Sample_Java_BouncyCastle_Algorithm_for_Encryption

I would prefer not to have to rewrite the code.
0
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 35046479
what you check here ?  
0
 
LVL 17

Expert Comment

by:Dejan Pažin
ID: 35046496


Its like CEHJ says, the code is corrupted already on the hosted site. You have to fix the   occurances - its not that difficult, just replace the   with blank space, thats it.
0
 

Author Comment

by:ericdavidsonca
ID: 35046503
This is a pre-canned code example I downloaded and I am trying to work out why it will not complie.

This issue appears that eclipse is trying to translate &nsbp into a variable.

I am not sure how to fix this without having to change the code which I am trying to avoid.

I am asumming that there is some eclipse parameter or class that needs to be set so that the compiler and understand how to process &nsbp etc.
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 35046514
Here we are
// Bouncy castle imports
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPOnePassSignatureList;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPUtil;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;

// Java imports import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
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 java.util.Iterator;


//
public class SingleSignOnTest {
    private static File publicKeyFile = new File(
            "/Development/Java/Single Sign On with Encryption(PGP)/PGP1D0.pkr");
    private static File privateKeyFile = new File(
            "/Development/Java/Single Sign On with Encryption(PGP)/PGP1D0.skr");
    private static String privateKeyPassword = "passphrase";

    //
    // Public class method decrypt
    //
    public static String decrypt(byte[] encdata) {
        System.out.println("decrypt(): data length=" + encdata.length);

        // ----- Decrypt the file
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(encdata);
            FileInputStream privKey = new FileInputStream(privateKeyFile);

            return _decrypt(bais, privKey, privateKeyPassword.toCharArray());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

    //
    // Public class method encrypt
    //
    public static byte[] encrypt(byte[] data) {
        try {
            // ----- Read in the public key
            PGPPublicKey key = readPublicKeyFromCol(new FileInputStream(
                        publicKeyFile));
            System.out.println("Creating a temp file...");

            // create a file and write the string to it
            File tempfile = File.createTempFile("pgp", null);
            FileOutputStream fos = new FileOutputStream(tempfile);
            fos.write(data);
            fos.close();
            System.out.println("Temp file created at ");
            System.out.println(tempfile.getAbsolutePath());
            System.out.println(
                "Reading the temp file to make sure that the bits were written\n--------------");

            BufferedReader isr = new BufferedReader(new FileReader(tempfile));
            String line = "";

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

            // 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());
            System.out.println("Bit strength = " + key.getBitStrength());
            System.out.println("Version = " + key.getVersion());
            System.out.println("Encryption key = " + key.isEncryptionKey() +
                ", Master key = " + key.isMasterKey());

            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);
            // encrypt the file
            // encryptFile(tempfile.getAbsolutePath(), out, key);
            // Encrypt the data
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            _encrypt(tempfile.getAbsolutePath(), baos, key);
            System.out.println("encrypted text length=" + baos.size());
            tempfile.delete();

            return baos.toByteArray();
        } catch (PGPException e) {
            // System.out.println(e.toString());
            System.out.println(e.getUnderlyingException().toString());
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    //
    // Private class method readPublicKeyFromCol
    //
    private static PGPPublicKey readPublicKeyFromCol(InputStream in)
        throws Exception {
        PGPPublicKeyRing pkRing = null;
        PGPPublicKeyRingCollection pkCol = new PGPPublicKeyRingCollection(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.isEncryptionKey()) {
                    return key;
                }
            }
        }

        return null;
    }

    //
    // Private class method _encrypt
    //
    private static void _encrypt(String fileName, OutputStream out,
        PGPPublicKey encKey)
        throws IOException, NoSuchProviderException, PGPException {
        out = new DataOutputStream(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);
        cPk.close();
        out.close();
    }

    //
    // Private class method _decrypt
    //
    private static String _decrypt(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();
                System.out.println("pbe id=" + pbe.getKeyID());
                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("message integrity check passed");
                }
            } else {
                System.err.println("no message integrity check");
            }

            return baos.toString();
        } catch (PGPException e) {
            System.err.println(e);

            if (e.getUnderlyingException() != null) {
                e.getUnderlyingException().printStackTrace();
            }
        }

        return null;
    }

    //
    // Private class method findSecretKey
    //
    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");
    }

    //
    // Public class method readFile
    //
    public byte[] readFile(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        byte[] buf = new byte[4096];
        int numRead = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        while ((numRead = fis.read(buf)) > 0) {
            baos.write(buf, 0, numRead);
        }

        fis.close();

        byte[] returnVal = baos.toByteArray();
        baos.close();

        return returnVal;
    }

    //
    // Public main method
    //
    public static void main(String[] args) {
        Security.addProvider(new BouncyCastleProvider());

        String TOKEN = "aamine";

        // ----- Encrypt the message to a file
        // them
        byte[] encdata = encrypt(TOKEN.getBytes());
        System.out.println("Encrypted: " + encdata);

        // Encode the byte array to a string
        BASE64Encoder en = new BASE64Encoder();
        String temp = en.encode(encdata);
        System.out.println("Temp: " + temp);

        // us
        byte[] newB = null;
        BASE64Decoder en1 = new BASE64Decoder();

        try {
            newB = en1.decodeBuffer(temp);
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }

        System.out.println("byte array" + newB.length);

        // ----- Decrypt the token that
        String result = decrypt(newB);
        System.out.println("Decrypted: " + result);
    }
}

Open in new window

0
 
LVL 92

Expert Comment

by:objects
ID: 35048267
> This is a pre-canned code example I downloaded and I am trying to work out why it will not complie.
> This issue appears that eclipse is trying to translate &nsbp into a variable.

The issue is not with the original code. The nbsp was inserted when you copied and posted the code from the site as dejanpazin pointed out above (it is not a part of the original code as you can see by looking at the example page). All you need to do is delete it and other escaped entities
0
 
LVL 92

Expert Comment

by:objects
ID: 35048387
have posted a copy friendly version of the code for anyone interested in the future (no points needed)
0
 

Author Closing Comment

by:ericdavidsonca
ID: 35056449
The solution allowed me to run the code and get arround the issue with code containing &nsbp etc. but did not explain how to compile code that contains this type of coding.
0
 

Author Comment

by:ericdavidsonca
ID: 35056469
Sorry Savant,

    Just seen your second to last comment. I will have to keep an eye for this infuture.

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35059936
>>... but did not explain how to compile code that contains this type of coding.

My first comment ( http:#35046408 ) explains what the problem is: the html entities in the pasted code need to be corrected into what they represent. You can do it by hand, which i did with the corrected code i posted for you
0
 
LVL 92

Expert Comment

by:objects
ID: 35061508
>     Just seen your second to last comment. I will have to keep an eye for this infuture.

That was my comment. Let me know if you need help reopening the question to correctly award the points
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now