您可以使用它在 PublicKey 实例中转换您的字符串(以 Base64 编码):
注意:我不知道您如何在 Base64 中编码您的字符串,例如,如果您使用 apache commons,请使用同一 API 中的“revert”方法。对于这个示例,我使用了 sun.misc.BASE64Decoder,因为字符串 publicKey 是使用 sun.misc.BASE64Encoder 编码的。
/**
* Verify the origin of the message using signature and encoded message.
* @param publicKey String - a public key, created with RSA and encoded with sun.misc.BASE64Encoder.
* @param sign String - a signature encoded with sun.misc.BASE64Encoder.
* @param message String - an encoded message.
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeySpecException
* @throws InvalidKeyException
* @throws InvalidAlgorithmParameterException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws NoSuchProviderException
* @throws IOException
* @throws SignatureException
* @see sun.misc.BASE64Encoder
*/
public boolean verifyMessageSign(String publicKey, String sign, String message) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException, IOException, SignatureException{
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//Create the PublicKey object from the String encoded in Base64.
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(publicKey));
PublicKey pub = keyFactory.generatePublic(publicKeySpec);
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(pub);
sig.update(message.getBytes());
return sig.verify(new BASE64Decoder().decodeBuffer(sign));
}