3

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)
4

2 回答 2

4

这对我有用:

@Test
public void serializeTest() throws Exception {

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = kpg.generateKeyPair();
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    ObjectOutputStream o =  new ObjectOutputStream(b);
    o.writeObject(keyPair);
    byte[] res = b.toByteArray();

    o.close();
    b.close(); 

    ByteArrayInputStream bi = new ByteArrayInputStream(res);
    ObjectInputStream oi = new ObjectInputStream(bi);
    Object obj = oi.readObject();
    assertTrue(obj instanceof KeyPair);

    oi.close();
    bi.close(); 
}
于 2012-12-16T15:36:32.067 回答
1

回答自己,以防万一有人遇到同样的问题:

不知道它是什么,但使用 BouncyCastle SPI 而不是默认的 JDK 似乎可以解决我的问题,它现在可以正常工作。

于 2012-12-16T15:28:55.787 回答