2012-06-05 47 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)); 
}