将字符串转换为公钥时获取公钥null

时间:2017-11-24 05:16:49

标签: java android

public static PublicKey strToPublicKey(String s) {

    PublicKey pbKey = null;
    try {

        BufferedReader br = new BufferedReader(new StringReader(s));
        PEMReader pr = new PEMReader(br);
        Object obj = pr.readObject();

        if (obj instanceof PublicKey) {
            pbKey = (PublicKey) pr.readObject();
        } else if (obj instanceof KeyPair) {
            KeyPair kp = (KeyPair) pr.readObject();
            pbKey = kp.getPublic();
        }
        pr.close();

    } catch (Exception e) {
        Log.d("CIPHER", e.getMessage());
    }
    return pbKey;
}

此行返回空值

pbKey = (PublicKey) pr.readObject();
    Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");

当我尝试将服务器密钥转换为rsa公钥类型时 它在此行重新生成空值

pbKey = (PublicKey) pr.readObject();

1 个答案:

答案 0 :(得分:2)

您的代码没有意义。你已经读过钥匙了。 instanceof测试证明了这一点。你不应该读另一个对象:你应该投射你已经读过的对象。