Vipin
Vipin

Reputation: 63

getting public key null while converting string to public key

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

this line returns null value

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

when I try to convert server key to rsa public key type it reurns null value at this line

pbKey = (PublicKey) pr.readObject();

Upvotes: 4

Views: 914

Answers (1)

user207421
user207421

Reputation: 311050

Your code doesn't make sense. You've already read the key. The instanceof test proves it. You should not be reading another object: you should be casting the object you already read.

Upvotes: 2

Related Questions