I am writing an application targeting Android 25 and I am trying to sign my HTTP query parameter String
by using my public key. However, I am getting the following exception java.security.SignatureException: object not initialized for signing
when this method is invoked.
What do you think I am missing here? The related line in my code where exception is thrown is marked with the comment //EXCEPTION IS THROWN HERE IN THE FOLLOWING LINE
.
private static String signSHA256RSA(String httpQueryParameterString, String strPublicKey) throws Exception {
String input = httpQueryParameterString;
if(input == null || input.isEmpty() || strPublicKey == null || strPublicKey.isEmpty()){
return "";
}
String realPublicKey = strPublicKey.
replaceAll("-----END PUBLIC KEY-----", "").
replaceAll("-----BEGIN PUBLIC KEY-----", "").
replaceAll("\n", "");
byte[] b1 = Base64.decode(realPublicKey, Base64.DEFAULT);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(b1);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKey rsaPubKey = (RSAPublicKey) kf.generatePublic(keySpec);
Signature publicSignature = Signature.getInstance("SHA256withRSA");
publicSignature.initVerify(rsaPubKey);
//EXCEPTION IS THROWN HERE IN THE FOLLOWING LINE
byte[] s = publicSignature.sign();
return Base64.encodeToString(s, Base64.DEFAULT);
}