Java - 使用现有PublicKey.sql加密字符串

时间:2015-10-29 09:37:30

标签: java encryption

我不想生成新的公钥,有人向我发送他的公钥(类型PublicKey.sql),然后我用这个密钥加密一些文本并将其保存在Oracle DataBase中。

我找到了一种阅读公钥的方法,但我得到了这个Exception

java.io.StreamCorruptedException: invalid stream header: 33303832
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at ge.georgiancard.app.main.App.readKeyFromFile(App.java:36)
at ge.georgiancard.app.main.App.rsaEncrypt(App.java:67)

读取密钥的方法:

public static Key readKeyFromFile() throws IOException {
    InputStream in = new FileInputStream(PUBLIC_KEY_FILE);
    ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
    try {
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        KeyFactory fact = KeyFactory.getInstance("RSA");
        return fact.generatePublic(new RSAPublicKeySpec(m, e));
    } catch (Exception e) {
        throw new RuntimeException("Spurious serialisation error", e);
    } finally {
        oin.close();
        System.out.println("Closed reading file.");
    }
}

1 个答案:

答案 0 :(得分:0)

当使用stream读取和写入数据存在差异时,会发生这种情况。似乎除了ObjectOutputStream之外还写了密钥。

参见本

java.io.StreamCorruptedException: invalid stream header: 54657374