I wanted to implement some VERY basic security in my Java application, but I'm getting stuck at the very beginning.
What I want to do is this: 1-Generate a RSA keypair 2-Store those keys in my DB in serialized form, so I can re-create them on the next run of the application 3-De-serialize them so I can get them back into object form and can use them to encrypt/decrypt stuff.
The problem is, I can't find a straightforward explanation on how to do this anywhere. I tried the standard Java serialization/deserialization methods, but they don't work. My code is as follows:
public static KeyPair Bin2KeyPair(byte[] data){
try{
ByteArrayInputStream b = new ByteArrayInputStream(data);
ObjectInputStream o = new ObjectInputStream(b);
Object obj =o.readObject();
return((KeyPair)obj);
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] KeyPair2Bin(KeyPair kp){
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o;
try {
o = new ObjectOutputStream(b);
o.writeObject(kp);
return b.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The problem I'm having is that the second method works fine (serializes the key to a byte array) but the first one fails, throwing a ClassCastException, telling me I can't cast the object to "KeyPair".
Any tips on how to do this properly?
EDIT: here's the exception (it gets thrown at "return((KeyPair)obj);" in the first method):
java.lang.ClassCastException: [B cannot be cast to java.security.KeyPair
at DARCOServer.security.SecurityManager.String2KeyPair(SecurityManager.java:34)
at DARCOServer.security.SecurityManager.GenerateServerKeys(SecurityManager.java:122)
at DARCOServer.MainClass.main(MainClass.java:13)