2

我正在用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);



}

请帮帮我谢谢

4

2 回答 2

0

您可以使用此类从字符串中获取字节数组:

http://www.docjar.com/docs/api/sun/misc/BASE64Decoder.html

import sun.misc.BASE64Decoder;

从字节数组中,获取一个 PublicKey 对象...顺便说一句。标准 sdk 不支持此代码,它只是 sun,所以要小心。

于 2012-06-05T09:16:43.183 回答
0

您可以使用它在 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));
}
于 2012-06-05T09:20:02.657 回答