簡體   English   中英

在JAVA中將字符串轉換為PublicKey

[英]String to PublicKey in JAVA

我現在用Java寫程序DigitalSignature,我可以將公鑰和簽名發送給接收者,但是當接收者收到我的公鑰和簽名時,

它是String(Base64)的類型(我需要發送String數據)

如何再次將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);



}

請幫我謝謝

您可以使用此類從字符串獲取字節數組:

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

import sun.misc.BASE64Decoder;

從字節數組中,獲取PublicKey Object ... Btw。 標准sdk不支持此代碼,它僅是sun,因此請小心。

您可以使用它來轉換PublicKey實例中的String(在Base64中編碼):

注意:我不知道如何在Base64中對String進行編碼,例如,如果您使用的是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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM