使用Andorid中的公钥进行Java SHA256签名(25)

时间:2018-04-08 15:55:15

标签: java android encryption public-key-encryption rsa-sha256

我正在编写一个针对Android 25的应用程序,我正在尝试使用我的公钥来签署我的HTTP查询参数String。但是,在调用此方法时,我收到以下异常java.security.SignatureException: object not initialized for signing

您认为我在这里失踪了什么?我的代码中抛出异常的相关行标有注释//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);
}

0 个答案:

没有答案