我用java编写程序Digitalsignature 现在我可以向接收者发送公钥和签名 但是当接收者收到我的公钥和签名时
它的字符串类型(Base64)(我需要发送字符串数据)
如何将String(Base64)再次恢复为PublicKey(Type)
public verifiSign(String signature,String data) {
String publickey="MIG...."
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(publickey); //<-- Cannot use String
sig.update(data.getBytes());
boolean verified = sig.verify(asBytes(signature));
System.out.println("Verify = " + verified);
}
请帮帮我 谢谢
答案 0 :(得分:0)
您可以使用此类从String中获取字节数组:
http://www.docjar.com/docs/api/sun/misc/BASE64Decoder.html
import sun.misc.BASE64Decoder;
从字节数组中获取PublicKey对象... 顺便说一句。
表示,标准sdk不支持此代码,仅限日照。答案 1 :(得分:0)
您可以使用它来转换PublicKey实例中的String(在Base64中编码):
注意:我不知道你如何在Base64中编码你的String,如果你使用apache commons,例如,使用同一API中的“revert”方法。在这个例子中,我使用了sun.misc.BASE64Decoder,因为String 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));
}