2017-09-23 51 views
0

我創建了以下的方法XML字符串加密給我當使用RSA

public static PublicKey readPublicKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { 

    PublicKey key = null; 
    CertificateFactory fact; 

    try { 

     // MBFS certificate to be used 
     FileInputStream is = new FileInputStream(filename); 
     fact = CertificateFactory.getInstance("X.509"); 
     System.out.println(is.toString()); 
     X509Certificate cer = (X509Certificate) fact.generateCertificate(is); 
     key = cer.getPublicKey(); 
     System.out.println(key.getAlgorithm()); 

    } catch (CertificateException e) { 

     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return key; 
} 

加密

public static byte[] encrypt(PublicKey key, byte[] plaintext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { 

    Cipher cipher = Cipher.getInstance("RSA"); 
    cipher.init(Cipher.ENCRYPT_MODE, key); 
    return cipher.doFinal(plaintext); 
} 

我早就XML字符串和使用這些兩個數據不得超過245個字節方法如下

byte[] message = xmlMessage.getBytes(); 

byte[] secret = encrypt(publicKey, message); 

但它給我使用rsa時數據不能超過256字節

證書是由客戶端碎片,它是說簽名算法sha256RS。

回答

0

通常情況下,您將使用對稱密碼來加密文檔(使用隨機密鑰),然後使用RSA加密密鑰。這不僅克服長度問題,而且快得多。

+0

感謝任何鏈接或mvn依賴關係 –

+0

我已經完成了這與隨機密鑰,但我怎樣才能使用我的公鑰爲相同的密鑰 –

+0

您已經擁有此零件:'encrypt(pubKey,randomKey)'' – Henry