Question

This is the code I'm currently using. It uses the BouncyCastle Provider.

static
{
   Security.addProvider(new BouncyCastleProvider());
}

protected String encrypt(byte[] keyData, byte[] data) throws Exception {
   X509EncodedKeySpec keyspec = new X509EncodedKeySpec(keyData);
   KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
   PublicKey pk = kf.generatePublic(keyspec);
   Cipher rsa =  Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
   rsa.init(Cipher.ENCRYPT_MODE, pk);
   byte[] output = rsa.doFinal(data);
   String result = base64EncodeBytes(output);
   return result;
}

I'm currently getting a

 java.lang.ArrayIndexOutOfBoundsException: too much data for RSA block
    at org.bouncycastle.jce.provider.JCERSACipher.engineDoFinal(Unknown Source)
    at javax.crypto.Cipher.doFinal(DashoA13*..)
    at Encryption.encrypt(RSAToken.java:60)
Was it helpful?

Solution

Using RSA to encrypt a lot of data is not a good practice.

The approach taken by cryptographic protocols is to generate a symmetric key, use it to encrypt the data, then encrypt that symmetric key with RSA.

This is how PGP and S/MIME work. It also makes it easy to allow multiple readers to decrypt the data—by encrypting the symmetric key for each intended recipient, rather than encrypting the entire data for each.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top