I've a Public key converted to byte array. I want to convert it back to Public key. I followed this link but getting an error :
Operation failed: javax.crypto.spec.SecretKeySpec incompatible with java.security.PublicKey
Since I know that it is a public key, is there any to convert it to Publickey
instead of SecretKey
.
EDIT
I have created a public key using RSAPublicKeySPec
. Now there is no error but the signature verification fails because when I see the key material of the newly created public key, it is different from what I passed.
Key Material I passed
3082010a0282010100ab7f161c0042496ccd6c6d4dadb919973435357776003acf54b7af1e440afb80b64a8755f8002cfeba6b184540a2d66086d74648346d75b8d71812b205387c0f6583bc4d7dc7ec114f3b176b7957c422e7d03fc6267fa2a6f89b9bee9e60a1d7c2d833e5a5f4bb0b1434f4e795a41100f8aa214900df8b65089f98135b1c67b701675abdbc7d5721aac9d14a7f081fcec80b64e8a0ecc8295353c795328abf70e1b42e7bb8b7f4e8ac8c810cdb66e3d21126eba8da7d0ca34142cb76f91f013da809e9c1b7ae64c54130fbc21d80e9c2cb06c5c8d7cce8946a9ac99b1c2815c3612a29a82d73a1f99374fe30e54951662a6eda29c6fc411335d5dc7426b0f6050203010001
Key Material I got after converting it to public key using RSAPublicKeySpec
30820122300D06092A864886F70D01010105000382010F003082010A0282010100AB7F161C0042496CCD6C6D4DADB919973435357776003ACF54B7AF1E440AFB80B64A8755F8002CFEBA6B184540A2D66086D74648346D75B8D71812B205387C0F6583BC4D7DC7EC114F3B176B7957C422E7D03FC6267FA2A6F89B9BEE9E60A1D7C2D833E5A5F4BB0B1434F4E795A41100F8AA214900DF8B65089F98135B1C67B701675ABDBC7D5721AAC9D14A7F081FCEC80B64E8A0ECC8295353C795328ABF70E1B42E7BB8B7F4E8AC8C810CDB66E3D21126EBA8DA7D0CA34142CB76F91F013DA809E9C1B7AE64C54130FBC21D80E9C2CB06C5C8D7CCE8946A9AC99B1C2815C3612A29A82D73A1F99374FE30E54951662A6EDA29C6FC411335D5DC7426B0F6050203010001
Clearly, the verification will fail because the key material is wrong! I don't understand why it is getting altered.
But when I directly create a public key using java.security.PublicKey
(anonymous inner class), the key material doesn't get altered. But when I pass it to verify, I get wrong algorithm type error (I passed RSA as the algorithm)
CODE SNIPPET
PublicKey pubKey = new PublicKey() {
private static final long serialVersionUID = 1L;
@Override
public String getFormat() {
return "PKCS1";
}
@Override
public byte[] getEncoded() {
return keyMat;
}
@Override
public String getAlgorithm() {
return "SHA256withRSA"; // tried with "RSA", getting same error
}
};
return pubKey;
}