2014-05-08 24 views
2

我想從一個字符串建立一個ObjectInputStream的,但我發現一個java.io.StreamCorruptedException:Android的字符串轉換爲ObjectInputStream的

我的代碼:

public static final String PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7bO/38XhXYLJikoEEQ7s\naHKYcrrkD2Q+IWS6P0GOOvoX0rfRI6Hb30ETBE/ySzV6F9tpgtCbjU/w7tE8vmOy\nxQDwToUobbS+uZDi+F72PAY9NRKRogtY7YCwJuvAxNVmsTu9i/P/oA3qO3l0ge61\nZu3lMf4ujh969T9Dj0fjIdXQGewqk+ROB6UqoIEHTYi9wRdPlxDGnKTrORu5I5hH\n1xQfM0l49ME36G4u3Ipg5Y9Tqr1F8EL82GYeRoSX+xG+brQAdbjnQGrmrW/VFRkT\n9uL327vrRjiOit9yoTNtP3HYk1g5+Db7XdSNi+8KHZOQ3T2xcYFseXNnd7nIGj97\nBwIDAQAB\n-----END PUBLIC KEY-----"; 
public static final String PRIVATE_KEY_FILE = "C:/keys/private.key"; 


public static void test() { 


Log.d("DEBUG","Original Text: "); 
try { 

    final String originalText = "top secret text"; 
    ObjectInputStream inputStream = null; 

    InputStream is = new ByteArrayInputStream(PUBLIC_KEY.getBytes()); 


    //Log.d("DEBUG","Original Text:3 " + convertStreamToString(is)); 
    // Encrypt the string using the public key 
    inputStream = new ObjectInputStream(is); 
    final PublicKey publicKey = (PublicKey) inputStream.readObject(); 
    final byte[] cipherText = encrypt(originalText, publicKey); 

    // Decrypt the cipher text using the private key. 
    inputStream = new ObjectInputStream(new ByteArrayInputStream(PRIVATE_KEY.getBytes())); 
    final PrivateKey privateKey = (PrivateKey) inputStream.readObject(); 
    final String plainText = decrypt(cipherText, privateKey); 

    // Printing the Original, Encrypted and Decrypted Text 
    Log.d("DEBUG","Original Text: " + originalText); 
    Log.d("DEBUG","Encrypted Text: " +cipherText.toString()); 
    Log.d("DEBUG","Decrypted Text: " + plainText); 

} catch (Exception e) { 
    e.printStackTrace(); 
} 
    } 

有人能解釋我是什麼我做錯了?

+0

哪裏例外? – james

+0

我不確定你可以做'(PublicKey)inputStream.readObject();'那個 – njzk2

回答

3

你寫出來的序列化對象(一個或多個),字符串是序列化,首先使用ObjectOutputStream到您的存儲和使用ObjectInputStream閱讀對象(S)

您的字節數組存儲中沒有任何對象。這就是你遇到流損壞異常的原因。

下面是一個非常基本的代碼片段演示 -

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
ObjectOutputStream oos = new ObjectOutputStream(baos); 
String myStrObj = "Hello World"; 
oos.writeObject(myStrObj); //write the string as object 
oos.close(); 


ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); 
String readStrObj = (String) ois.readObject(); //read the string as object 
ois.close(); 
System.out.println(readStrObj); 

你可以用你的公鑰替換Hello World,看看它打印出來。