Solved

Tales from the javax.Crypto

Posted on 2004-10-03
77
666 Views
Last Modified: 2008-01-09
okay, I want people to be able to push a button, this button will encrypt the contents of a file, say C:\oogyboogey.txt
then I want them to be able to decrypt the file using a, guess what. decrypt button.
So while this seems utterly obvious and trivial, I'm confused about the whole dam javax.crypto thing , or cipher or something.
I do understand one thing, you need a key to do it. so here is my 30 digit sample key:
907604333809348636348526830901

STREAMLINED OUTLINE:
Push Encrypt button
- open encryption dialog (so they can choose form of encryption)
  - load contents of file to String 'fileContents'
   - encrypt String (create new encrypted string 'file-enc')
   - save new String to file

Push Decrypt button
- open decryption dialog (so they can choose form of decryption)
  - load contents of file to String 'fileContents-dec'
   - encrypt String (create new encrypted string 'file-dec')
   - open string in JEditorPane 'contentarea'

HOW YOU CAN HELP:
Simply hand over some source code.
No need to add the Action Listeners for the buttons, just what I should put inside them.

EXTRAS:
Well, I want to prevent people from pushing the 'Encrypt' button twice and messing the whole file up.
I'm just wonderimg, if you encrypt 2 times and then decrypt 2 times, do you get the same thing back? If you can answer this too, I may favor your solution :)
0
Comment
Question by:billyea
  • 44
  • 29
  • 4
77 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 12213293
0
 
LVL 3

Accepted Solution

by:
CI-Ia0s earned 310 total points
ID: 12213927
First, your key and cipher will probably be generated by the computer, not by you. Second, the encryption part of the code will probably look like this:

//Remember to import javax.crypto.*, javax.crypto.spec.*, and java.security.*.

//Encrypt button was pushed (use "encryptButton.setEnabled(false)" to insure it's only pushed once), data was inputted, now we're encrypting
try{
Cipher yourCipher = Cipher.getInstance("AES"); //You'd put your parameters, such as encryption type in the parentheses
KeyGenerator yourGen = KeyGenerator.getInstance("AES"); //Needs to match your cipher
Key yourKey = yourGen.generateKey();

//Now, encrypting
Cipher yourCipher.init(Cipher.ENCRYPT_MODE, yourKey);
byte[] encryptedData = yourCipher.doFinal(byteArrayOfData);
}
catch (Exception e){System.exit(1);}

//You may want to just output the data as bytes... if not, though:
String encString = new String(encryptedData);

//Data is output in string or byte from

//Decrypt button is pushed
try{
Cipher otherCipher = Cipher.getInstance("AES"); //Like the one above...
Cipher otherCipher.init(Cipher.ENCRYPT_MODE, yourKey); //Note that you use the same key
byte[] decrytedData = yourCipher.doFinal(encryptedData);
}
catch (Exception e){System.exit(1);}

//String is displayed in JEditorPane
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12213928
Did that cover everything? (it was a lot of writing ;) ).
0
 
LVL 2

Author Comment

by:billyea
ID: 12268677
anything other than AES, or is it difficult to change?
0
 
LVL 2

Author Comment

by:billyea
ID: 12268687
actually the better question is ,what choice is more secure than AES? You see, I want to make an impression on my clients and make them say 'wow, my data really IS that secure' (please not , I'm using clients as a vage term for 'people who see my software' as I am only just 12 yrs old, way too young to actually market stuff :)
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12268965
Lot's of stuff... In fact, you can find a whole listing here: http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/JCERefGuide.html#AppA

If you use AES, you get from 128 to 256 bit. That is hard to crack, trust me. Even standard DES 64 bit looks like gibberish when viewed as text and that's supposed to be only mid-strength. ;) Good luck!
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 90 total points
ID: 12270464
>>You see, I want to make an impression on my clients and make them say 'wow, my data really IS that secure'

Is not the algos you need to worry about (unless you're using rot13 or something). Most of the time, encryption systems are rendered insecure not by weak algos, but by poor key management.
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12272699
Yup, CEHJ is right. I've been developing my own program recently and keeping the key safe is hard! The best thing is to put it on a server and limit access in some way, but if the key must be with the data, use other methods to keep it safe. Take a look at this thread where I'm working on strengthening my own app for some ideas (thanks to DrWarezz and MathewSchlabaugh for their help): http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21161616.html
0
 
LVL 2

Author Comment

by:billyea
ID: 12273721
Oh yes, I guess. I mean this is only a diary program. I guess that nobody's going to hack more than 64 bits of encryption just to read some stupid diary by a 4 year old (unless it was from the government, the government doesn't hire 4 year olds though).

Being a 12 year old, here are a few things I do not understand:
- I thought that the key was generated by the conputer, is it a concern of the key being hacked while it's being processed in a program, or saved as an external file? Does it have to be saved somewhere due to un-static like randomization of the key? I probably sound stupid even with all those big words. I'm not expecting my end-consumers to actually know what a key IS, but, hey, who knows?
0
 
LVL 2

Author Comment

by:billyea
ID: 12273726
anyway, thanks CI-Ia0s, I am implementing your code right now (I wanna try BlowFish and see how it stands up to the test of random big-a-bytes)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12274785
>>Does it have to be saved somewhere due to un-static like randomization of the key?

If you're doing symmetric encryption, then yes it does, or you wouldn't be able to decrypt it later if it were randomly generated each time in different sessions.

Often it's done as if you were lending your house to a relation: 'you'll find the key in a plant pot inside the porch'. The trouble is, someone else can too.
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12283507
Yes. Unless the code is just a demo and the data will be decrypted and encrypted in the same program (doesn't sound like what you're doing ;) ), the key will need to be stored somewhere. You can output it in bytes as an object:
try{
ObjectOutputStream keyOutputStream = new ObjectOutputStream(new FileOutputStream("key.dat")); //The file name you want in quotes. If it exists it will be overwritten (if possible)
keyOutputStream.writeObject(theKey); //The key object itself, mind you...
keyOutputStream.close();
}
catch (Exception e){System.out.println("You screwed my program up, foolish user!"); //If you're feeling mean... For image purposes, you'd probably want a nicer error message :P
System.exit(1);
}

and input:

try{
ObjectInputStream keyInputStream = new ObjectInputStream(new FileInputStream("key.dat"));
Key theKey = (Key)keyInputStream.readObject();
keyInputStream.close();
}
catch (Exception e){System.out.println("Error importing key. Decrypting can not proceed."); //That's more like a normal error message ;)
System.exit(1);
}

Good luck!
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12283604
P.S. Make sure to import java.io.* :)
0
 
LVL 2

Author Comment

by:billyea
ID: 12325600
Thanks everybody, once I get version 1.1 ("NOW with ENCRYPTION" is what I'll say) I will hand out points, especially to CI-Ia0s (CEHJ will gat a bit too, it's split 225:175), but i may have to add a few new features (if I have to, I'll notify you RIGHT AWAY!) before it's released.
 
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12325853
Thanks you. I'll try to help you with anything further if I can. :)
0
 
LVL 2

Author Comment

by:billyea
ID: 12378109
dum de dum, 4 new implementations
0
 
LVL 2

Author Comment

by:billyea
ID: 12378148
byte[] encryptedData = yourCipher.doFinal(byteArrayOfData);
doesn't seem to work, it can't recognize byteArrayOfData

Sorry if that was a mistake, the problem is I'M using NETBEANS 3.6 and it doesn't recognize crypto, security, or anything. (Netbeans is actually pretty darn good at everything else though)
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12386731
I'm using NetBeans too. I'd suggest you compile and run your programs via the command line as I've had issues with NetBeans as well...

P.S. You are using SDK 1.4.2 or later, right?
P.P.S. You did use a FileInputStream to fill byteArrayOfData full of juicy bytes to encrypt, right?
0
 
LVL 2

Author Comment

by:billyea
ID: 12387443
PPPS I just downloaded JDK (or SDK, whatever) 1.5, it didn't solve the problem, neither has NetBeans 4.0 Beta 2
I will follow your instructions.

THINGS STILL REMAINING IN THE PROGRAM (you don't need to help me with these, but it could only be better if you did):
- Multi-user support in program
- Add entries to diary (but encrypt it first, exactly what we're doing) <<<
- Open and decrypt diaries (also what we're doing)                        <<<
- Update feature (but that might have to wait till I have a secure server)
- JavaScript support (unfortunately Java does not provide JavaScript support by default)
- Find some nice free Icons to use in my application.
- Give the DAMN thing a LICENSE (I'm thinking GNU/GPL but I heard Java wasn't too suitable with that license, can you reccomend me one?)

It's quite alot to do for a 12 yr old! Oh well, I like to program.
0
 
LVL 2

Author Comment

by:billyea
ID: 12390828
and secondly, no, I'm not using FileInputStream, I use the classic BufferedReader for my text puposes, and for unexplained reasons, I dare not venture into territory not known.
Any way to convert a string to bytes so that this will work, 'cause i'm encrypto-phobic
0
 
LVL 2

Author Comment

by:billyea
ID: 12390848
oops, stupid me, just use byte[] and cast
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12391024
Do this (replace inputString with whatever string you got with BufferedReader):

byte[] byteArrayOfData = inputString.getBytes();
0
 
LVL 2

Author Comment

by:billyea
ID: 12391314
Hmmm, ObjectOutputStream doesn't seem to save the key to key.dat (it is 0 KB and thus, EMPTY)
Yet it reports not exceptions saving, drat, a logical error.

I'm sure I'm doing everything as you said, the Cipher was coded in without complier errors but if I can't read or write the key, it's next to useless.

AAAH!
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12391329
Could you post exactly the code you used? (And make sure you have read/write privileges in the directory you're writing the key to...
0
 
LVL 2

Author Comment

by:billyea
ID: 12391389
Here's a snippet of the key import and export code, remember that the key.dat file DID NOT CHANGE! It remained 0 KB!!! AAAH!
       
        System.out.println("Reading Key...");
        if (ntpint > 1)
        //confused? ntpint is basically how many times the program has run. This expression means launch the code if it's not the first time.
        {
        try{
        ObjectInputStream keyInputStream = new ObjectInputStream(new FileInputStream(classpath +"//key.dat"));
        System.out.print("GO!");    
        //These GOs are for debugging purposes. None of them were displayed which signifies that an ObjectInputStream couldn't be created
        theKey = (Key)keyInputStream.readObject();
        System.out.print("GO!");
        keyInputStream.close();
        System.out.print("GO!\n");
        }
        catch (Exception e){System.out.println("Error importing key."); //I got this exception when importing the key.
        }
        }
        else{ //if the user has played for the first time
        System.out.println("This is your first key:\nGenerating Key...");
        try{
        KeyGenerator yourGen = KeyGenerator.getInstance("AES");
        Key theKey = yourGen.generateKey();
        FileOutputStream fos = new FileOutputStream("key.dat"); //key.dat is in the program directory
        ObjectOutputStream keyOutputStream = new ObjectOutputStream(fos);
        keyOutputStream.writeObject(theKey);
        keyOutputStream.close();
        }
        catch (Exception e){System.out.println("Error Creating Key"); //huh? no exceptions here
        }
        }

And that's it, it's just a snippet though, if you wan't I will send you a copy of the software to test (including all plugin modules and configuration files).
This snippet comes after the initComponents() method

P.S. You are welcome to spyware, adware, virus, and of course bug check the software if you're suspicious of a baddie :) I don't do those things BTW.

Hope it helps....me....
0
 
LVL 2

Author Comment

by:billyea
ID: 12391410
By the Way, do you use that cute EE posting tool too???

Anyway, to business. I do have permissions to every file and folder on the computer, dat file is not write-protected.
Sigh.......
0
 
LVL 2

Author Comment

by:billyea
ID: 12391572
Sorry if I'm stressing you and you really want points, but I need help to get this up and running. Whence it runs successfully I will distribute points.
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12391617
Hrmm... That code *looks* fine...
It seems to me that the key is never created or output due a logic error in your if-else statement... (I can't see one, but that's the only thing I can come up with)> Try throwing some System.out.printlns into the key creation and output block of code and see if those things actually run.
0
 
LVL 2

Author Comment

by:billyea
ID: 12391714
Ok, so here's the lowdown.

I decided to abandon the .dat file. Intstead I reverted the stream to a non-existent file 'key.txt' (thus, creating that file). and it ends up that it works.
So my diagnosis is that ObjectOutputStream CANNOT overwrite a file. It can create a NEW one with the data, but not replace an old one. Anyway, thanks on this issue.
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12394137
Alright, sounds good. You all set then?
0
 
LVL 2

Author Comment

by:billyea
ID: 12395876
One more thing.

yourCipher.init(Cipher.ENCRYPT_MODE, theKey); //8888 (for marking purposes)
does not work, not sure why....
the key is loading properly but...why?
0
 
LVL 2

Author Comment

by:billyea
ID: 12395914
here is the whole method of the 'add' button

       int returnval = selectfile.showDialog(null, "Add");//opens dialog to select file
       
        if (returnval == JFileChooser.APPROVE_OPTION)
        {
            File newfl = selectfile.getSelectedFile(); //gets the file
            String diary = newfl.getAbsolutePath(); //finds the path
            String contents = reader(diary); //reads the contents already in diary
            String subj = subjectfield.getText(); //gets the subject from subjectfield
            java.util.Date d = new java.util.Date(); //creates new date
            java.text.DateFormat datef = new java.text.SimpleDateFormat(); //new dateformat
            datef.setTimeZone(java.util.TimeZone.getDefault()); //sets timezone
            String datezone = datef.format(d); //formats
            String body = editorpanel.getText(); //gets body from editorpanel
            String compiledver = contents + "\n\n" + datezone + "\n" + subj + "\n"+ body;
            //puts it all together
            byte[] byteArrayOfData = compiledver.getBytes(); //extracts the bytes
            try
            {
            yourCipher.getInstance("AES"); // creates a new CIPHER with AES
            yourCipher.init(Cipher.ENCRYPT_MODE, theKey); //now here is where I get the error <<< aah
            byte[] encryptedData = yourCipher.doFinal(byteArrayOfData); //and the rest
            String encString = new String(encryptedData);
            writer(diary, encString);
            }catch (Exception e){}

Please help!
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12396013
When you declare yourCipher, initialize it to null:
Cipher yourCipher = null;
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12396020
What's the error you're getting, by the way?
0
 
LVL 2

Author Comment

by:billyea
ID: 12396102
I'm getting a NullPointerException but it's on THIS line, I checked to see if all the output streams and writers were pointing to the correct file and they were.
0
 
LVL 2

Author Comment

by:billyea
ID: 12396118
nulling the Ciphers don't work either
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12396218
Ooooh. I got it:
yourCipher.getInstance("AES");
should be
yourCipher = Cipher.getInstance("AES");
0
 
LVL 2

Author Comment

by:billyea
ID: 12396409
Thanks everyone, now for points!
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12396943
Thank you.
0
 
LVL 2

Author Comment

by:billyea
ID: 12397511
Before you completely leave me.

The thing is beeping when I encrypt it with AES and then try to decrypt it, it says IllegaBlockSize or something and it has to be '16' bits or characters or multiples. I have no Idea, but it's definitely preventing me from doing testing.

Can you gave me some reccomendations/code on how to fix it?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12398331
8-)

>>... something and it has to be '16' bits or characters or multiples.

Take that just as read. You should make sure both sides are using the same padding and block size

0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12404203
Yea. When you read in the bytes to decrypt the size of the array to decrypt must be the size of the initial array + padding (16, in your case).
0
 
LVL 2

Author Comment

by:billyea
ID: 12406944
I'm not using any padding, or mode, i'm just putting in 'AES' and not 'AES/NONE/NoPadding' in fact both sides are using the smae system, they both are set for 'AES' and both draw from 'key.dat'
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12406960
Please look at my comment. Note that when you select only an algorithm, a default padding and block size is selected for you.
0
 
LVL 2

Author Comment

by:billyea
ID: 12406983
I know, but it's not working. I input AES on one side and a padding error comes with the AES.

How do I change the byte array to be 16 anyway.
0
 
LVL 2

Author Comment

by:billyea
ID: 12406995
this may sound dumb but for the decrypting cipher (otherCipher) , it should be set to 'decrypt_mode' right, because in your code it is on encrypt_mode
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12407087
Yes. Sorry. I was copy/pasting and in a rush (always am these days :( ). As for the padding error, simply make sure that you declare the array with the encrypted data to be decrypted (encryptedData in my example) to be the same size as the array with not-encrypted data (byteArrayOfData in my example) PLUS 16.
0
 
LVL 2

Author Comment

by:billyea
ID: 12407109
> PLUS 16

 what's that supposed to mean, add 16 to the array> or to...huh?
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12417009
Add 16 to byteArrayOfData.length and you have the length of the encrypted data array. If the encrypted data array is smaller than this you will NOT get an error, however, all of the data will not be there and you will get the BadPaddingException (or IllegalBlockSizeException) when decrypting.
0
 
LVL 2

Author Comment

by:billyea
ID: 12417249
so I should use
byteArrayOfData.length += 16
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12417485
For the length of the array that the encrypted data goes into when you import it from the text file, yes.
0
 
LVL 2

Author Comment

by:billyea
ID: 12418624
so what should be the code?

DECRYPTION
Encryption remains the same

        \/
byte[16] encryptedData = contents.getBytes();
            try{
            otherCipher = Cipher.getInstance("AES");
            otherCipher.init(Cipher.DECRYPT_MODE, theKey);
            byte[] decryptedData = otherCipher.doFinal(encryptedData);
            String encString = new String(decryptedData);
0
 
LVL 2

Author Comment

by:billyea
ID: 12418634
I'm sure this is not correct, so can you revise this? PLEASE!
I prefer code and I'll figure out the rest.
0
 
LVL 2

Author Comment

by:billyea
ID: 12418643
Because I have no idea how to do this!!!!!
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12428709
Decrypt code (I assume contents is a String with the data, right?):

byte[] encryptedData = contents.getBytes();

try{
otherCipher = Cipher.getInstance("AES");
otherCipher.init(Cipher.DECRYPT_MODE, theKey);
byte[] decryptedData = otherCipher.doFinal(encryptedData);
String encString = new String(decryptedData);
}

That should work. If not, try using FileInputStream and reading in the bytes directly! P.S. I also suggest you use FileOutputStream...

In encryption program:
try{
FileOutputStream outStream = new FileOutputStream("encrypted.txt");
outStream.write(encryptedData);
outStream.close();
}
catch (Exception e){System.out.println("Error.");

In decryption program:
try{
FileInputStream inStream = new FileInputStream("encrypted.txt");
inStream.read(encryptedData);
inStream.close();
}
catch (Exception e){System.out.println("Error.");
0
 
LVL 2

Author Comment

by:billyea
ID: 12429812
great!

Now I've decided to switch to SecretKey and DES (along with DES specs and Factory)

I'm getting a null pointerexception with this code run:

int returnval = selectfile.showDialog(null, "Add");
       
        if (returnval == JFileChooser.APPROVE_OPTION)
        {
            try
            {
            File newfl = selectfile.getSelectedFile();
            String diary = newfl.getAbsolutePath();
            System.out.println("Decrypting Contents");
            byte[] data = null;
            otherCipher = Cipher.getInstance("DES");
            otherCipher.init(Cipher.DECRYPT_MODE, theKey);
            FileInputStream fis = new FileInputStream(diary);
            ObjectInputStream cis = new ObjectInputStream(fis);
            try{
            cis.readFully(data);
            }catch(EOFException eof){cis.close();}
            byte[] decryptedMessage = otherCipher.doFinal(data);
            String contents = decryptedMessage.toString();
            System.out.println("Assembling Message");
            String subj = subjectfield.getText();
            Date d = new Date();
            DateFormat datef = new SimpleDateFormat();
            datef.setTimeZone(TimeZone.getDefault());
            String datezone = datef.format(d);
            String body = editorpanel.getText();
            String compiledver = contents + "\n\n" + datezone + "\n" + subj + "\n"+ body;
            System.out.println("Encrypting Message");
            byte[] byteArrayOfData = compiledver.getBytes();
            yourCipher = Cipher.getInstance("DES");
            yourCipher.init(Cipher.ENCRYPT_MODE, theKey); //8888
            byte[] encData = yourCipher.doFinal(byteArrayOfData);
            System.out.println("Writing Message");
            yourCipher = Cipher.getInstance("DES");
            yourCipher.init(Cipher.ENCRYPT_MODE, theKey);
            byte[] encryptedMessage = yourCipher.doFinal(encData);
            FileOutputStream fos = new FileOutputStream(diary);
            ObjectOutputStream cos = new ObjectOutputStream(fos);
            cos.writeObject(encryptedMessage);
           
            }catch (Exception e){JOptionPane.showMessageDialog(null,"Error Saving:\n"+e, "ERROR",JOptionPane.ERROR_MESSAGE);}
        }

Unfortuantely, I can't track it odwn, but it seems to be somewhere between 'DECRYPTING' and 'ASSEMBLING'
so here is that code cropped

            byte[] data = null;
            otherCipher = Cipher.getInstance("DES");
            otherCipher.init(Cipher.DECRYPT_MODE, theKey);
            FileInputStream fis = new FileInputStream(diary);
            ObjectInputStream cis = new ObjectInputStream(fis);
            try{
            cis.readFully(data);
            }catch(EOFException eof){cis.close();}
            byte[] decryptedMessage = otherCipher.doFinal(data);
            String contents = decryptedMessage.toString();

AAAH!
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12429940
Whoa... back up. That ObjectInputStream has no business being in there. ;) You want to import the BYTES for decrypting, not an object. Kill the ObjectInputStream and do fis.read(data).
0
 
LVL 2

Author Comment

by:billyea
ID: 12430055
well that didn't solve the problem

        byte[] rawDesKey = null;
        System.out.println("GO!");
        FileInputStream fis = new FileInputStream("key.dat");
        System.out.println("GO!");
        try{
        fis.read(rawDesKey);
        System.out.println("GO!");
        }catch(EOFException eof){fis.close();}
        DESKeySpec keyspec = new DESKeySpec(rawDesKey);
        System.out.println("GO!");
        SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES");
        System.out.println("GO!");
        theKey = desFactory.generateSecret(keyspec);
        System.out.println("GO!");

This is where I get my key, but it get's an error after 2 GO!s, the file exisits in the program directory. What's going on?
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12439279
Ok, miscommunication:

I meant the ObjectInputStream here:
FileInputStream fis = new FileInputStream(diary);
ObjectInputStream cis = new ObjectInputStream(fis);


You do need an ObjectInputStream for the key.
0
 
LVL 2

Author Comment

by:billyea
ID: 12439809
added ObjectStreams but still null pointer exception on xxx..read(rawDesKey);
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12441271
Here's what you should have:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("key.dat"));
DESKeySpec = (DESKeySpec)ois.readObject();

Put it in a try of course, and make sure to close the stream too. ;)
0
 
LVL 2

Author Comment

by:billyea
ID: 12441411
Great!

BUT
Now I'm getting an EOF Exception. How do I deal with THAT? Just close the streams?
Actually, I do that already, but since all my code is buggy, I'm gonna trust you.
0
 
LVL 2

Author Comment

by:billyea
ID: 12441427
Oops, oops, sorry, my code works. Now ican import keys. Let's test the rest shall we...
0
 
LVL 2

Author Comment

by:billyea
ID: 12441452
Well, it turns up it's not IMPORTING anything but NULL!!! AAHH!
I know I will regret this later, but i'm gonna give you the whole friggin source for the program and have you examine it. I'm tho THAT scared of it being hacked, I intend to make it Open Source. Just don't tell everybody that it's 'YOURS', especially if it doesn't work. ;)

Code is in the next comment...
0
 
LVL 2

Author Comment

by:billyea
ID: 12441459
/**
 *
 * @author  Billy E
 */

import java.awt.BorderLayout;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.TimeZone;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import plugins.*;

public class exec extends JFrame{
   
    /** Creates new form exec */
    public exec() {
        System.out.println("Setting Look and Feel...");
        try{
            //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            //SwingUtilities.updateComponentTreeUI(this);
        }
        catch(Exception e){}  
        try{
        initComponents();
        System.out.println("Reading Configuration...");
        String configIO = reader(classpath +"//config.txt");
        StringTokenizer configtk = new StringTokenizer(configIO, ":");
       
        String ntp = configtk.nextToken();
        int ntpint = Integer.parseInt(ntp);
        ntpint++;
        ntpdt = Integer.toString(ntpint);
        System.out.println("Times run:" + ntpdt);
        System.out.println("Reading Key...");
        if (ntpint > 1)
        {
        try{
       
        System.out.println("GO!");
        FileInputStream fis = new FileInputStream("key.dat");
        System.out.println("GO!");
        ObjectInputStream cis = new ObjectInputStream(fis);
        System.out.println("GO!");
        try{
        DESKeySpec keyspec = (DESKeySpec)cis.readObject();
        System.out.println("GO!");
        fis.close();
        System.out.println("GO!");
        SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES");
        System.out.println("GO!");
        theKey = desFactory.generateSecret(keyspec);
        System.out.println("GO!");
        }catch(EOFException eof){cis.close();}
       
        }
        catch (Exception e){System.out.println("Error importing key. "+e); //That's more like a normal error message ;)
        }
        }
        else if (ntpint == 1){
        System.out.println("This is your first key:\nGenerating Key...");
        try{
        KeyGenerator yourGen = KeyGenerator.getInstance("DES");
        theKey = yourGen.generateKey();
        SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES");
        DESKeySpec desSpec = (DESKeySpec)
          desFactory.getKeySpec(theKey, DESKeySpec.class);
        rawDesKey = desSpec.getKey();
        FileOutputStream fos = new FileOutputStream("key.dat");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.write(rawDesKey);
        }
        catch (Exception e){System.out.println("Error Creating Key. "+e);
        }
        }
        this.setBounds(0,0, 450, 350);
        importdialog.setBounds(50,50,250, 150);
        panepanel.add(editor,BorderLayout.CENTER );
        panepanel.updateUI();
        System.out.println("Reading Notes...");
        String notes = reader(classpath + "//notes.txt");
        notesarea.setText(notes);
        System.out.println("Intitalizing Plugin Panels:");
        System.out.print("Panel 1...");
        JPanel plugin1 = new pluginpanel1();
        plug1.getContentPane().add(plugin1,BorderLayout.CENTER); plug1.updateUI();
        plug1.setTitle(pluginpanel1.displayname());
        System.out.print("Panel 2...");
        JPanel plugin2 = new pluginpanel2();
        plug2.getContentPane().add(plugin2,BorderLayout.CENTER); plug2.updateUI();
        plug2.setTitle(pluginpanel2.displayname());
        System.out.print("Panel 3...");
        JPanel plugin3 = new pluginpanel3();
        plug3.getContentPane().add(plugin3,BorderLayout.CENTER); plug3.updateUI();
        plug3.setTitle(pluginpanel3.displayname());
        System.out.print("Panel 4...\n");
        JPanel plugin4 = new pluginpanel4();
        plug4.getContentPane().add(plugin4,BorderLayout.CENTER); plug4.updateUI();    
        plug4.setTitle(pluginpanel4.displayname());
        }catch(Exception e){JOptionPane.showMessageDialog(null,"The program failed to intialize because of a\n"+e+"\nNow reverting to default configuration.","ERROR", JOptionPane.ERROR_MESSAGE);}
    }
       
   
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {
        mainGroup = new javax.swing.ButtonGroup();
        notes = new javax.swing.JPanel();
        notesscroll = new javax.swing.JScrollPane();
        notesarea = new javax.swing.JTextArea();
        notesentrypanel = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        notefield = new javax.swing.JTextField();
        stickbutton = new javax.swing.JButton();
        clrnotesbutton = new javax.swing.JButton();
        editor = new javax.swing.JPanel();
        subjpanel = new javax.swing.JPanel();
        subjectfield = new javax.swing.JTextField();
        subjectlbl = new javax.swing.JLabel();
        jToolBar2 = new javax.swing.JToolBar();
        addbutton = new javax.swing.JButton();
        clearbutton = new javax.swing.JButton();
        imprtbutton = new javax.swing.JButton();
        htmlbutton = new javax.swing.JToggleButton();
        cutbutton = new javax.swing.JButton();
        copybutton = new javax.swing.JButton();
        pastebutton = new javax.swing.JButton();
        typane = new javax.swing.JSplitPane();
        HTMLPane = new javax.swing.JPanel();
        htmlscroll = new javax.swing.JScrollPane();
        htmlpreview = new javax.swing.JEditorPane();
        jLabel1 = new javax.swing.JLabel();
        NormPane = new javax.swing.JPanel();
        normscroll = new javax.swing.JScrollPane();
        editorpanel = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        htmltoolbar = new javax.swing.JToolBar();
        paragraphbutton = new javax.swing.JButton();
        boldbutton = new javax.swing.JButton();
        underlinebutton = new javax.swing.JButton();
        italicbutton = new javax.swing.JButton();
        imagebutton = new javax.swing.JButton();
        newfile = new javax.swing.JFileChooser();
        selectfile = new javax.swing.JFileChooser();
        plugintabs = new javax.swing.JDesktopPane();
        plug1 = new javax.swing.JInternalFrame();
        plug2 = new javax.swing.JInternalFrame();
        plug3 = new javax.swing.JInternalFrame();
        plug4 = new javax.swing.JInternalFrame();
        importdialog = new javax.swing.JDialog();
        jLabel5 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        edffile = new javax.swing.JButton();
        otffile = new javax.swing.JButton();
        manager = new javax.swing.JPanel();
        managerpanel = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        currentfilefield = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        modefield = new javax.swing.JTextField();
        contentscroll = new javax.swing.JScrollPane();
        contentpane = new javax.swing.JEditorPane();
        jToolBar1 = new javax.swing.JToolBar();
        newbutton = new javax.swing.JButton();
        openbutton = new javax.swing.JButton();
        exportbutton = new javax.swing.JButton();
        deletebutton = new javax.swing.JButton();
        printbutton = new javax.swing.JButton();
        refreshbutton = new javax.swing.JButton();
        unmountbutton = new javax.swing.JButton();
        plainmode = new javax.swing.JButton();
        htmlmode = new javax.swing.JButton();
        normfile = new javax.swing.JFileChooser();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        mainpanel = new javax.swing.JPanel();
        screenselectpanel = new javax.swing.JPanel();
        editorradio = new javax.swing.JRadioButton();
        managerradio = new javax.swing.JRadioButton();
        notesradio = new javax.swing.JRadioButton();
        pluginbutton = new javax.swing.JRadioButton();
        panepanel = new javax.swing.JPanel();
        optionspanel = new javax.swing.JPanel();
        abtpanel = new javax.swing.JPanel();

        notes.setLayout(new java.awt.BorderLayout());

        notesscroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        notesscroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        notesscroll.setViewportView(notesarea);

        notes.add(notesscroll, java.awt.BorderLayout.CENTER);

        notesentrypanel.setLayout(new java.awt.BorderLayout());

        jLabel7.setText("Note:   ");
        notesentrypanel.add(jLabel7, java.awt.BorderLayout.WEST);

        notefield.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                notefieldKeyPressed(evt);
            }
        });

        notesentrypanel.add(notefield, java.awt.BorderLayout.CENTER);

        stickbutton.setText("Stick Note");
        stickbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stickbuttonActionPerformed(evt);
            }
        });

        notesentrypanel.add(stickbutton, java.awt.BorderLayout.EAST);

        notes.add(notesentrypanel, java.awt.BorderLayout.NORTH);

        clrnotesbutton.setText("Clear All Notes");
        clrnotesbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clrnotesbuttonActionPerformed(evt);
            }
        });

        notes.add(clrnotesbutton, java.awt.BorderLayout.SOUTH);

        editor.setLayout(new java.awt.BorderLayout());

        subjpanel.setLayout(new java.awt.BorderLayout());

        subjpanel.add(subjectfield, java.awt.BorderLayout.CENTER);

        subjectlbl.setText("Subject:    ");
        subjpanel.add(subjectlbl, java.awt.BorderLayout.WEST);

        jToolBar2.setFloatable(false);
        addbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Save24.gif")));
        addbutton.setText("Add");
        addbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addbuttonActionPerformed(evt);
            }
        });

        jToolBar2.add(addbutton);

        clearbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Remove24.gif")));
        clearbutton.setText("Clear");
        clearbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearbuttonActionPerformed(evt);
            }
        });

        jToolBar2.add(clearbutton);

        imprtbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Import24.gif")));
        imprtbutton.setText("Import");
        imprtbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                imprtbuttonActionPerformed(evt);
            }
        });

        jToolBar2.add(imprtbutton);

        htmlbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Html24.gif")));
        htmlbutton.setText("HTML");
        htmlbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                htmlbuttonActionPerformed(evt);
            }
        });

        jToolBar2.add(htmlbutton);

        cutbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Cut24.gif")));
        cutbutton.setText("Cut");
        cutbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cutbuttonActionPerformed(evt);
            }
        });

        jToolBar2.add(cutbutton);

        copybutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Copy24.gif")));
        copybutton.setText("Copy");
        copybutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copybuttonActionPerformed(evt);
            }
        });

        jToolBar2.add(copybutton);

        pastebutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Paste24.gif")));
        pastebutton.setText("Paste");
        pastebutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pastebuttonActionPerformed(evt);
            }
        });

        jToolBar2.add(pastebutton);

        subjpanel.add(jToolBar2, java.awt.BorderLayout.SOUTH);

        editor.add(subjpanel, java.awt.BorderLayout.NORTH);

        typane.setDividerLocation(200);
        HTMLPane.setLayout(new java.awt.BorderLayout());

        htmlscroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        htmlscroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        htmlpreview.setEditable(false);
        htmlpreview.setContentType("text/html");
        htmlscroll.setViewportView(htmlpreview);

        HTMLPane.add(htmlscroll, java.awt.BorderLayout.CENTER);

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("HTML Preview");
        HTMLPane.add(jLabel1, java.awt.BorderLayout.NORTH);

        typane.setRightComponent(HTMLPane);

        NormPane.setLayout(new java.awt.BorderLayout());

        normscroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        normscroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        editorpanel.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
                editorpanelCaretPositionChanged(evt);
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
            }
        });

        normscroll.setViewportView(editorpanel);

        NormPane.add(normscroll, java.awt.BorderLayout.CENTER);

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Editor View");
        NormPane.add(jLabel2, java.awt.BorderLayout.NORTH);

        typane.setLeftComponent(NormPane);

        editor.add(typane, java.awt.BorderLayout.CENTER);

        htmltoolbar.setFloatable(false);
        paragraphbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Paragraph24.gif")));
        paragraphbutton.setText("Paragraph");
        htmltoolbar.add(paragraphbutton);

        boldbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Bold24.gif")));
        boldbutton.setText("Bold");
        htmltoolbar.add(boldbutton);

        underlinebutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Underline24.gif")));
        underlinebutton.setText("Underline");
        htmltoolbar.add(underlinebutton);

        italicbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Italic24.gif")));
        italicbutton.setText("Italics");
        htmltoolbar.add(italicbutton);

        imagebutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Picture24.gif")));
        imagebutton.setText("Image");
        htmltoolbar.add(imagebutton);

        newfile.setApproveButtonText("");
        newfile.setCurrentDirectory(new java.io.File("C:\\"));
            newfile.setDialogTitle("New");
            newfile.setDialogType(javax.swing.JFileChooser.CUSTOM_DIALOG);
            selectfile.setApproveButtonText("OK");
            selectfile.setCurrentDirectory(new java.io.File("C:\\"));
                selectfile.setDialogTitle("Select Diary");
                selectfile.setDialogType(javax.swing.JFileChooser.CUSTOM_DIALOG);
                plug1.setIconifiable(true);
                plug1.setMaximizable(true);
                plug1.setResizable(true);
                plug1.setTitle("Plugin 1");
                plug1.setVisible(true);
                plug1.setBounds(0, 0, 270, 120);
                plugintabs.add(plug1, javax.swing.JLayeredPane.DEFAULT_LAYER);

                plug2.setIconifiable(true);
                plug2.setMaximizable(true);
                plug2.setResizable(true);
                plug2.setTitle("Plugin 2");
                plug2.setVisible(true);
                plug2.setBounds(270, 0, 270, 120);
                plugintabs.add(plug2, javax.swing.JLayeredPane.DEFAULT_LAYER);

                plug3.setIconifiable(true);
                plug3.setMaximizable(true);
                plug3.setResizable(true);
                plug3.setTitle("Plugin 3");
                plug3.setVisible(true);
                plug3.setBounds(270, 120, 270, 130);
                plugintabs.add(plug3, javax.swing.JLayeredPane.DEFAULT_LAYER);

                plug4.setIconifiable(true);
                plug4.setMaximizable(true);
                plug4.setResizable(true);
                plug4.setTitle("Plugin 4");
                plug4.setVisible(true);
                plug4.setBounds(0, 120, 270, 130);
                plugintabs.add(plug4, javax.swing.JLayeredPane.DEFAULT_LAYER);

                importdialog.setTitle("Select Type");
                jLabel5.setText("Select a file type:");
                importdialog.getContentPane().add(jLabel5, java.awt.BorderLayout.NORTH);

                jPanel1.setLayout(new java.awt.GridLayout(1, 2, 5, 0));

                edffile.setText("Encrypted Diary");
                edffile.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        edffileActionPerformed(evt);
                    }
                });

                jPanel1.add(edffile);

                otffile.setText("Other File");
                otffile.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        otffileActionPerformed(evt);
                    }
                });

                jPanel1.add(otffile);

                importdialog.getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

                manager.setLayout(new java.awt.BorderLayout());

                managerpanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 51, 204), 2, true));
                jLabel3.setText("    Current File:    ");
                managerpanel.add(jLabel3);

                currentfilefield.setColumns(20);
                currentfilefield.setEditable(false);
                managerpanel.add(currentfilefield);

                jLabel4.setText("    Mode:    ");
                managerpanel.add(jLabel4);

                modefield.setColumns(5);
                modefield.setEditable(false);
                modefield.setText("Plain");
                managerpanel.add(modefield);

                manager.add(managerpanel, java.awt.BorderLayout.SOUTH);

                contentscroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
                contentscroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
                contentpane.setEditable(false);
                contentscroll.setViewportView(contentpane);

                manager.add(contentscroll, java.awt.BorderLayout.CENTER);

                jToolBar1.setFloatable(false);
                jToolBar1.setRollover(true);
                newbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/New24.gif")));
                newbutton.setToolTipText("New: Creates a new .diary file.");
                newbutton.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        newbuttonActionPerformed(evt);
                    }
                });

                jToolBar1.add(newbutton);

                openbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Open24.gif")));
                openbutton.setToolTipText("Open: Opens (mounts) the file and displays the contents.");
                openbutton.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        openbuttonActionPerformed(evt);
                    }
                });

                jToolBar1.add(openbutton);

                exportbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Export24.gif")));
                exportbutton.setToolTipText("Export: Saves the contents of the current file to a separate file.");
                exportbutton.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        exportbuttonActionPerformed(evt);
                    }
                });

                jToolBar1.add(exportbutton);

                deletebutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Delete24.gif")));
                deletebutton.setToolTipText("Delete: Removes the current file from your drive.");
                deletebutton.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        deletebuttonActionPerformed(evt);
                    }
                });

                jToolBar1.add(deletebutton);

                printbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Print24.gif")));
                printbutton.setToolTipText("Print: 'Copies' the contents to hard paper.");
                printbutton.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        printbuttonActionPerformed(evt);
                    }
                });

                jToolBar1.add(printbutton);

                refreshbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Refresh24.gif")));
                refreshbutton.setToolTipText("Reload: Refreshes the viewer with updated file contents.");
                refreshbutton.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        refreshbuttonActionPerformed(evt);
                    }
                });

                jToolBar1.add(refreshbutton);

                unmountbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/unmount24.gif")));
                unmountbutton.setToolTipText("Unload: Clears the file information and contents from the manager.");
                unmountbutton.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        unmountbuttonActionPerformed(evt);
                    }
                });

                jToolBar1.add(unmountbutton);

                plainmode.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/plain.GIF")));
                plainmode.setToolTipText("Plain Mode: Changes the viewer mode to accept neat and organized plain text.");
                plainmode.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        plainmodeActionPerformed(evt);
                    }
                });

                jToolBar1.add(plainmode);

                htmlmode.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/html.GIF")));
                htmlmode.setToolTipText("HTML Mode: Changes the viewer mode to accept stylish HTML text.");
                htmlmode.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        htmlmodeActionPerformed(evt);
                    }
                });

                jToolBar1.add(htmlmode);

                manager.add(jToolBar1, java.awt.BorderLayout.NORTH);

                normfile.setApproveButtonText("Accept");
                normfile.setCurrentDirectory(new java.io.File("C:\\"));
                    normfile.setDialogTitle("Select File");
                    normfile.setDialogType(javax.swing.JFileChooser.CUSTOM_DIALOG);

                    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
                    setTitle("WOW!Diary 2.0");
                    addWindowListener(new java.awt.event.WindowAdapter() {
                        public void windowClosing(java.awt.event.WindowEvent evt) {
                            exitForm(evt);
                        }
                    });

                    mainpanel.setLayout(new java.awt.BorderLayout());

                    screenselectpanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 2, true));
                    editorradio.setSelected(true);
                    editorradio.setText("Editor");
                    mainGroup.add(editorradio);
                    editorradio.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                            editorradioActionPerformed(evt);
                        }
                    });

                    screenselectpanel.add(editorradio);

                    managerradio.setText("Manager");
                    mainGroup.add(managerradio);
                    managerradio.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                            managerradioActionPerformed(evt);
                        }
                    });

                    screenselectpanel.add(managerradio);

                    notesradio.setText("Notes");
                    mainGroup.add(notesradio);
                    notesradio.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                            notesradioActionPerformed(evt);
                        }
                    });

                    screenselectpanel.add(notesradio);

                    pluginbutton.setText("Plugins");
                    mainGroup.add(pluginbutton);
                    pluginbutton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                            pluginbuttonActionPerformed(evt);
                        }
                    });

                    screenselectpanel.add(pluginbutton);

                    mainpanel.add(screenselectpanel, java.awt.BorderLayout.NORTH);

                    panepanel.setLayout(new java.awt.BorderLayout());

                    mainpanel.add(panepanel, java.awt.BorderLayout.CENTER);

                    jTabbedPane1.addTab("Main", mainpanel);

                    jTabbedPane1.addTab("Options", optionspanel);

                    jTabbedPane1.addTab("About", abtpanel);

                    getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER);

                    pack();
                }

    private void editorpanelCaretPositionChanged(java.awt.event.InputMethodEvent evt) {
        // TODO add your handling code here:
        String htmltext = editorpanel.getText();
        htmlpreview.setText(htmltext);
    }

    private void otffileActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        int returnval = normfile.showDialog(null, "Import");
        if (returnval == JFileChooser.APPROVE_OPTION)
        {
            try{
            File newfl = normfile.getSelectedFile();
            String diary = newfl.getAbsolutePath();
            String contents = reader(diary);
            editorpanel.insert(contents, editorpanel.getCaretPosition());

            }catch (Exception e){JOptionPane.showMessageDialog(null,"Error Importing:\n"+e+"\nPlease make sure:\n" +
            "- File is NOT Corrupted\n", "ERROR",JOptionPane.ERROR_MESSAGE);}
        }
    }

    private void edffileActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        if (alreadyfilter == false)
        {
        selectfile.setFileFilter( new diaryFileFilter() );
        alreadyfilter = true;
        }
        int returnval = selectfile.showDialog(null, "Import");
        if (returnval == JFileChooser.APPROVE_OPTION)
        {
            File newfl = selectfile.getSelectedFile();
            String diary = newfl.getAbsolutePath();
            try{
            byte[] data = null;
            otherCipher = Cipher.getInstance("DES");
            otherCipher.init(Cipher.DECRYPT_MODE, theKey);
            FileInputStream fis = new FileInputStream(diary);
            try{
            fis.read(data);
            }catch(EOFException eof){fis.close();}
            byte[] decryptedMessage = otherCipher.doFinal(data);
            String contents = decryptedMessage.toString();
            editorpanel.insert(contents, editorpanel.getCaretPosition());
            }
            catch (Exception e){JOptionPane.showMessageDialog(null,"Error Importing:\n"+e+"\nPlease make sure:\n" +
            "- File is NOT Corrupted\n" +
            "- You are using the same Key", "ERROR",JOptionPane.ERROR_MESSAGE);}
        }
    }

    private void unmountbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        contentpane.setText(null);
        currentfilefield.setText(null);
    }

    private void openbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        if (alreadyfilter == false)
        {
        selectfile.setFileFilter( new diaryFileFilter() );
        alreadyfilter = true;
        }
        int returnval = selectfile.showDialog(null, "Open");
       
        if (returnval == JFileChooser.APPROVE_OPTION)
        {
           
            File newfl = selectfile.getSelectedFile();
            String diary = newfl.getAbsolutePath();
         
            try{
            byte[] data = null;
            otherCipher = Cipher.getInstance("DES");
            otherCipher.init(Cipher.DECRYPT_MODE, theKey);
            FileInputStream fis = new FileInputStream(diary);
            try{
            fis.read(data);
            }catch(EOFException eof){fis.close();}
            byte[] decryptedMessage = otherCipher.doFinal(data);
            String contents = decryptedMessage.toString();
            contentpane.setText(contents);
            currentfilefield.setText(diary);
            }
            catch (Exception e){JOptionPane.showMessageDialog(null,"Error Loading:\n"+e+"\nPlease make sure:\n" +
            "- File is NOT Corrupted\n" +
            "- You are using the same Key", "ERROR",JOptionPane.ERROR_MESSAGE);}
        }
    }

    private void exportbuttonActionPerformed(java.awt.event.ActionEvent evt) {
       
    }

    private void refreshbuttonActionPerformed(java.awt.event.ActionEvent evt) {
            String diary = currentfilefield.getText();
            try{
            byte[] data = null;
            otherCipher = Cipher.getInstance("DES");
            otherCipher.init(Cipher.DECRYPT_MODE, theKey);
            FileInputStream fis = new FileInputStream(diary);
            try{
            fis.read(data);
            }catch(EOFException eof){fis.close();}
            byte[] decryptedMessage = otherCipher.doFinal(data);
            String contents = decryptedMessage.toString();
            contentpane.setText(contents);
            }
            catch (Exception e){JOptionPane.showMessageDialog(null,"Error Reloading:\n"+e+"\nPlease make sure:\n" +
            "- File Exists\n" +
            "- File is NOT Corrupted\n" +
            "- You are using the same Key", "ERROR",JOptionPane.ERROR_MESSAGE);}
    }

    private void addbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        if (alreadyfilter == false)
        {
        selectfile.setFileFilter( new diaryFileFilter() );
        alreadyfilter = true;
        }
        int returnval = selectfile.showDialog(null, "Add");
       
        if (returnval == JFileChooser.APPROVE_OPTION)
        {
            try
            {
            File newfl = selectfile.getSelectedFile();
            String diary = newfl.getAbsolutePath();
            System.out.println("Decrypting Contents");
            byte[] data = null;
            otherCipher = Cipher.getInstance("DES");
            otherCipher.init(Cipher.DECRYPT_MODE, theKey);
            FileInputStream fis = new FileInputStream(diary);
            try{
            fis.read(data);
            }catch(EOFException eof){fis.close();}
            byte[] decryptedMessage = otherCipher.doFinal(data);
            String contents = decryptedMessage.toString();
            System.out.println("Assembling Message");
            String subj = subjectfield.getText();
            Date d = new Date();
            DateFormat datef = new SimpleDateFormat();
            datef.setTimeZone(TimeZone.getDefault());
            String datezone = datef.format(d);
            String body = editorpanel.getText();
            String compiledver = contents + "\n\n" + datezone + "\n" + subj + "\n"+ body;
            System.out.println("Encrypting Message");
            byte[] byteArrayOfData = compiledver.getBytes();
            yourCipher = Cipher.getInstance("DES");
            yourCipher.init(Cipher.ENCRYPT_MODE, theKey); //8888
            byte[] encData = yourCipher.doFinal(byteArrayOfData);
            System.out.println("Writing Message");
            yourCipher = Cipher.getInstance("DES");
            yourCipher.init(Cipher.ENCRYPT_MODE, theKey);
            byte[] encryptedMessage = yourCipher.doFinal(encData);
            FileOutputStream fos = new FileOutputStream(diary);
            ObjectOutputStream cos = new ObjectOutputStream(fos);
            cos.writeObject(encryptedMessage);
           
            }catch (Exception e){JOptionPane.showMessageDialog(null,"Error Saving:\n"+e, "ERROR",JOptionPane.ERROR_MESSAGE);}
        }
    }

    private void imprtbuttonActionPerformed(java.awt.event.ActionEvent evt) {
            importdialog.show();
    }

    private void htmlmodeActionPerformed(java.awt.event.ActionEvent evt) {
        String s = contentpane.getText();
        contentpane.setContentType("text/html");
        modefield.setText("HTML");
        contentpane.setText(s);
    }

    private void plainmodeActionPerformed(java.awt.event.ActionEvent evt) {
        String s = contentpane.getText();
        contentpane.setContentType("text/plain");
        modefield.setText("Plain");
        contentpane.setText(s);
    }

    private void copybuttonActionPerformed(java.awt.event.ActionEvent evt) {
        editorpanel.copy();
    }

    private void pastebuttonActionPerformed(java.awt.event.ActionEvent evt) {
       editorpanel.paste();
    }

    private void cutbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        editorpanel.cut();
    }

    private void clearbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        editorpanel.setText(null);
        htmlpreview.setText(null);
    }

    private void pluginbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        panepanel.remove(manager);
        panepanel.remove(editor);
        panepanel.remove(notes);
        panepanel.add(plugintabs,BorderLayout.CENTER);
        panepanel.updateUI();
    }

    private void deletebuttonActionPerformed(java.awt.event.ActionEvent evt) {
        int delete = JOptionPane.showConfirmDialog(null, "This will delete your file.\nContinue?", "Delete Confirm", JOptionPane.YES_NO_OPTION);
        if (delete == 0)
        {
        try{
        diaryfile = new File(currentfilefield.getText());
        diaryfile.delete();
        }catch(Exception e){JOptionPane.showMessageDialog(null,"Could not delete current file.", "ERROR", JOptionPane.ERROR_MESSAGE);}
        }
    }

    private void printbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        print print = new
        print();
        print.print(contentpane);
    }

    private void newbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        int returnval = newfile.showDialog(null, "Create");
       
        if (returnval == JFileChooser.APPROVE_OPTION)
        {
            try{
            File newfl = newfile.getSelectedFile();
            String diary = newfl.getAbsolutePath() + ".diary";
            diaryfile = new File(diary);
            diaryfile.createNewFile();
            }catch(Exception e){JOptionPane.showMessageDialog(null, "There was an error creating your file.\n"+e, "ERROR", JOptionPane.ERROR_MESSAGE);}
        }
    }

    private void clrnotesbuttonActionPerformed(java.awt.event.ActionEvent evt) {
       
        int delete = JOptionPane.showConfirmDialog(null,"This action will delete all notes.\nContinue?","Delete Confirm",JOptionPane.YES_NO_OPTION);
        if (delete == 0)
        {
        writer(classpath + "//notes.txt", "");
        String currentnotes = reader(classpath + "//notes.txt");
        notesarea.setText(currentnotes);
        }
    }

    private void notefieldKeyPressed(java.awt.event.KeyEvent evt) {
        int keyID = evt.getKeyCode();
        if (keyID == evt.VK_ENTER)
        {
        String currentnotes = reader(classpath + "//notes.txt");
        writer(classpath + "//notes.txt", notefield.getText() + "\n" +currentnotes);
        notesarea.setText((reader(classpath + "//notes.txt")));
        notefield.setText("");
        }
    }

    private void stickbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        String currentnotes = reader(classpath + "//notes.txt");
        writer(classpath + "//notes.txt", notefield.getText() + "\n" +currentnotes);
        notesarea.setText((reader(classpath + "//notes.txt")));
        notefield.setText("");
    }

    private void htmlbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        if (htmlbarenabled == true)
        {
            htmlbarenabled = false;
            htmlbutton.setSelected(false);
            editor.remove(htmltoolbar);
            editor.updateUI();
        }
        else
        {
            htmlbarenabled = true;
            htmlbutton.setSelected(true);
            editor.add(htmltoolbar, BorderLayout.SOUTH);
            editor.updateUI();
        }
    }

    private void notesradioActionPerformed(java.awt.event.ActionEvent evt) {
       
        panepanel.remove(manager);
        panepanel.remove(editor);
        panepanel.remove(plugintabs);
        panepanel.add(notes,BorderLayout.CENTER );
        panepanel.updateUI();
    }

    private void managerradioActionPerformed(java.awt.event.ActionEvent evt) {
        panepanel.remove(notes);
        panepanel.remove(editor);
        panepanel.remove(plugintabs);
        panepanel.add(manager,BorderLayout.CENTER );
        panepanel.updateUI();
    }

    private void editorradioActionPerformed(java.awt.event.ActionEvent evt) {
        panepanel.remove(manager);
        panepanel.remove(notes);
        panepanel.remove(plugintabs);
        panepanel.add(editor,BorderLayout.CENTER );
        panepanel.updateUI();
    }
   
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
        try{
        System.out.println("Saving options...");
        writer(classpath + "//config.txt",ntpdt+":");
        }catch(Exception e){System.exit(0);}
        System.exit(0);
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        new exec().show();
    }
   
    public String reader(String filename)
    {try{
    fileContents = "";
    fin = new BufferedReader(new FileReader(filename));
    String currentLine;
    while ((currentLine = fin.readLine()) != null)
    {
    fileContents = fileContents + currentLine;
    fileContents = fileContents + "\n";
    }
    }catch(IOException e){JOptionPane.showMessageDialog(null, "There was an error reading:\n"+ filename,"ERROR", JOptionPane.ERROR_MESSAGE);}
    return fileContents;
    }
    public void writer(String filename, String text)
    {
    try
    {
    fout = new BufferedWriter(new FileWriter(filename));
    fout.write(text);
    fout.close();
    }catch(IOException e){JOptionPane.showMessageDialog(null, "There was an error writing to:\n"+ filename,"ERROR", JOptionPane.ERROR_MESSAGE);}
    }
    public void unlockcomponents()
    {
       
    }
    public void lockcomponents()
    {
       
    }
    public class diaryFileFilter extends FileFilter
    {
    public boolean accept( File diaryfile ) {
        return diaryfile.getName().toLowerCase().endsWith(".diary") || diaryfile.isDirectory();
    }

    public String getDescription() {
        return "Encrypted Diary file (*.diary)";
    }
    }
    // Variables declaration - do not modify
    private javax.swing.JPanel HTMLPane;
    private javax.swing.JPanel NormPane;
    private javax.swing.JPanel abtpanel;
    private javax.swing.JButton addbutton;
    private javax.swing.JButton boldbutton;
    private javax.swing.JButton clearbutton;
    private javax.swing.JButton clrnotesbutton;
    private javax.swing.JEditorPane contentpane;
    private javax.swing.JScrollPane contentscroll;
    private javax.swing.JButton copybutton;
    private javax.swing.JTextField currentfilefield;
    private javax.swing.JButton cutbutton;
    private javax.swing.JButton deletebutton;
    private javax.swing.JButton edffile;
    private javax.swing.JPanel editor;
    private javax.swing.JTextArea editorpanel;
    private javax.swing.JRadioButton editorradio;
    private javax.swing.JButton exportbutton;
    private javax.swing.JToggleButton htmlbutton;
    private javax.swing.JButton htmlmode;
    private javax.swing.JEditorPane htmlpreview;
    private javax.swing.JScrollPane htmlscroll;
    private javax.swing.JToolBar htmltoolbar;
    private javax.swing.JButton imagebutton;
    private javax.swing.JDialog importdialog;
    private javax.swing.JButton imprtbutton;
    private javax.swing.JButton italicbutton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.ButtonGroup mainGroup;
    private javax.swing.JPanel mainpanel;
    private javax.swing.JPanel manager;
    private javax.swing.JPanel managerpanel;
    private javax.swing.JRadioButton managerradio;
    private javax.swing.JTextField modefield;
    private javax.swing.JButton newbutton;
    private javax.swing.JFileChooser newfile;
    private javax.swing.JFileChooser normfile;
    private javax.swing.JScrollPane normscroll;
    private javax.swing.JTextField notefield;
    private javax.swing.JPanel notes;
    private javax.swing.JTextArea notesarea;
    private javax.swing.JPanel notesentrypanel;
    private javax.swing.JRadioButton notesradio;
    private javax.swing.JScrollPane notesscroll;
    private javax.swing.JButton openbutton;
    private javax.swing.JPanel optionspanel;
    private javax.swing.JButton otffile;
    private javax.swing.JPanel panepanel;
    private javax.swing.JButton paragraphbutton;
    private javax.swing.JButton pastebutton;
    private javax.swing.JButton plainmode;
    private javax.swing.JInternalFrame plug1;
    private javax.swing.JInternalFrame plug2;
    private javax.swing.JInternalFrame plug3;
    private javax.swing.JInternalFrame plug4;
    private javax.swing.JRadioButton pluginbutton;
    private javax.swing.JDesktopPane plugintabs;
    private javax.swing.JButton printbutton;
    private javax.swing.JButton refreshbutton;
    private javax.swing.JPanel screenselectpanel;
    private javax.swing.JFileChooser selectfile;
    private javax.swing.JButton stickbutton;
    private javax.swing.JTextField subjectfield;
    private javax.swing.JLabel subjectlbl;
    private javax.swing.JPanel subjpanel;
    private javax.swing.JSplitPane typane;
    private javax.swing.JButton underlinebutton;
    private javax.swing.JButton unmountbutton;
    // End of variables declaration
    BufferedReader fin;
    BufferedWriter fout;
    String fileContents = "";
    boolean htmlbarenabled;
    String classpath = System.getProperty("user.dir");
    boolean alreadyfilter;
    File diaryfile;
    String ntpdt;
    SecretKey theKey;
    Cipher yourCipher = null;
    Cipher otherCipher = null;
    byte[] rawDesKey;
}

//PLEASE COMPILE WITH NETBEANS!!!! IT SHOULD UNDERSTAND EVERYTHING PERFECTLY!
//EXCEPT PACKAGE DECLARATIONS, IN THAT CASE, IF IT INVOLVES a PLUGINPANEL OBJECT, REMOVE IT AND COMPILE.
0
 
LVL 2

Author Comment

by:billyea
ID: 12441470
PLEASE ALSO NOTE THAT IF IT INVOLVES CONFIG.TXT, PUT THAT IN PROGRAM DIRECTORY. and WRITE IN IT:

0:

That is a zero with a colon. It means the number of times.
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12444821
You need to use ois.writeObject(keyspec) when outputting the key. Also, make sure that you output before you input. ;)
0
 
LVL 2

Author Comment

by:billyea
ID: 12449670
Would it be better if I simply used String Encrypter?
I mean it looks easy. Do you have any concerns about it?
0
 
LVL 2

Author Comment

by:billyea
ID: 12450066
Sorry. I meant String Digests.
0
 
LVL 2

Author Comment

by:billyea
ID: 12450071
Is it possible to use a custom key. I'm tired of all these errors so I'll just make a randomly generated 100 digit numrerical key (which is processed in a second).
0
 
LVL 2

Author Comment

by:billyea
ID: 12450084
The new numerical key will be easy to save and process in a file.
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12450403
I haven't had any error issues using encryption with Cipher and Key, but the decision is really up to you...
0
 
LVL 2

Author Comment

by:billyea
ID: 12450696
Yes it is. Now how do you use a custom key?
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12451981
Unfortunately, I don't have any idea. :(
0
 
LVL 2

Author Comment

by:billyea
ID: 12455067
That's OK, teach me how to use StringDigests
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12455091
Don't know them either. :( My encryption knowledge is limited to basic Cipher/Key encryption. I suggest you open a new thread on the subject...
0
 
LVL 2

Author Comment

by:billyea
ID: 12455995
Okay, here is the new thread. If you can, please visit by and check it out. Otherwise, sayonora!
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21189210.html
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

760 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

19 Experts available now in Live!

Get 1:1 Help Now