[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[iaik-jce] compilation problem
I am trying to run a simple program which encrypts and decrypts the text
from the command line. I have a problem with reading the key from the file
Server.ser. Intially when I tried to run the code without the key file,then
it works fine.It generates a new key and stores it into "Server.ser" But
after the Key file is created, if I run the program again, then it's unable
to read the Key from the keyfile "Server.ser".
It's giving me following errors:
Exception in thread "main" java.lang.ClassCastException: Assigning instance
of class [B to field iaik.security.cipher.SecretKey#a
at kava/op/PnkectOm[itStrea,/om[itc;assFields<Compiled Code>
at
java.io.ObjectInputStream.defaultReadObject<ObjectInputStream.java:502>
at java.io.ObjectInputStream.readinputObject<compiled Code>
at java.io.ObjectInputStream.readObject<ObjectInputStream.java:369>
at java.io.ObjectInputStream.readObject <ObjectInputStream.java:232>
at SecretWriting.main<SecretWriting.java:18>
THE CODE IS AS FOLLOWS:
import java.io.*;
import java.security.*;
import javax.crypto.*;
import sun.misc.*;
public class SecretWriting {
public static void main(String[]args) throws Exception {
//check arguments.
if(args.length<2){
System.out.println("Usage: SecretWriting -e|-d text");
return;
}
//Get or create key.
Key key;
try{
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("SecretKey.ser"));
key=(Key)in.readObject();
in.close();
}
catch (FileNotFoundException fnfe) {
KeyGenerator generator = KeyGenerator.getInstance("DES");
generator.init(new SecureRandom());
key=generator.generateKey();
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("SecretKey.ser"));
out.writeObject(key);
out.close();
}
//Get a cipher object.
Cipher cipher =Cipher.getInstance("DES/ECB/PKCS5Padding");
//encrypt or decrypt the input string.
if(args[0].indexOf("e") !=-1) {
cipher.init(Cipher.ENCRYPT_MODE,key);
String amalgam = args[1];
byte[] stringBytes = amalgam.getBytes("UTF8");
byte[] raw = cipher.doFinal(stringBytes);
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(raw);
System.out.println(base64);
}
else if(args[0].indexOf("d") !=-1){
cipher.init(Cipher.DECRYPT_MODE,key);
BASE64Decoder decoder = new BASE64Decoder();
byte[] raw = decoder.decodeBuffer(args[1]);
byte[] stringBytes = cipher.doFinal(raw);
String result = new String(stringBytes, "UTF8");
System.out.println(result);
}
}
}
--
Mailinglist-archive at http://jcewww.iaik.tu-graz.ac.at/mailarchive/iaik-jce/maillist.html
To unsubscribe send an email to listserv@iaik.tu-graz.ac.at with the folowing content: UNSUBSCRIBE iaik-jce