2012-06-05 57 views
2

我写程序的DigitalSignature用java 现在我可以给公钥和签名接收器 但是,当接收器接收到我的公钥和签名字符串公钥在JAVA

这类型的字符串(Base64编码)(我需要发送字符串数据)

如何回复字符串(Base64编码),以公钥(类型)再次

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

您是如何将公钥转换为Base64字符串的?相同的操作应该颠倒过来。应该使用相同的类。 –

回答

0

你可以使用这个类从字符串获取字节数组:

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

import sun.misc.BASE64Decoder; 

从字节数组,得到一个公钥对象... 顺便说一句。此代码不支持标准sdk,它只是太阳,所以要小心。

+1

[使用Sun专有的Java类是不好的做法?](http://stackoverflow.com/questions/1834826/it-is-a-bad-practice-to-use-suns-proprietary-java-classes) – Jesper

+0

你可以得到像这样的警告: http://stackoverflow.com/questions/1136659/how-can-i-suppress-java-compiler-warnings-about-sun-proprietary-api – user1434045

+0

...另一个好链接http ://stackoverflow.com/questions/469695/decode-base64-data-in-java – user1434045

0

你可以使用这个在公钥实例来改变你的字符串(以Base64编码):

注:我不知道你是如何编码您的字符串为Base64,如果您使用Apache的百科全书,例如,使用来自同一API的“恢复”方法。在这个例子中我使用了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)); 
}