2017-09-23 52 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