【问题标题】:Android convert string to ObjectInputStreamAndroid将字符串转换为ObjectInputStream
【发布时间】:2014-05-08 16:03:42
【问题描述】:

我正在尝试从字符串构造 ObjectInputStream,但我得到了 java.io.StreamCorruptedException:

我的代码:

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();
}
  }

谁能解释一下我做错了什么?

【问题讨论】:

  • 哪里有异常?
  • 我不确定你是否可以这样做(PublicKey) inputStream.readObject();

标签: java android string objectinputstream


【解决方案1】:

你写出可序列化的object(s),字符串是可序列化的,首先使用ObjectOutputStream到你的存储中并在使用@读取object(s) 987654322@.

您的字节数组存储中没有任何对象。这就是您收到流损坏异常的原因。

下面是一个非常基础的sn-p演示-

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 替换为您的公钥,然后查看它的打印结果。

【讨论】:

    猜你喜欢
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多