0
votes

I have created following to method

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;
}

for encryption

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);
} 

I have long xml string and using these both method as following

byte[] message = xmlMessage.getBytes();

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

But it is giving me Data must not be longer than 256 bytes when using rsa

Certificate is shard by client it is saying Signature algorithm sha256RS.

1

1 Answers

0
votes

Typically, you would use a symmetric cipher to encrypt the document (with a random secret key) and then just encrypt the key with RSA. This does not only overcome the length problem but is also much faster.