views:

785

answers:

1

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)
+5  A: 
erickson
Is there a security reason for it not being a good practice? AFAIK the reason it's done this way is speed. BouncyCastle simply doesn't support it, doesn't mean it's not an option...
wds
Speed, compatibility, and complexity are all good reasons not to do it this way. I don't know of any vulnerabilities to cryptanalytic methods in current practice, but this approach requires more code to be written by someone who doesn't have a deep understanding of cryptography, so it is definitely less secure. It would be better to use BouncyCastle's S/MIME or PGP libraries; using widely reviewed protocols and implementations is much safer than inventing your own.
erickson
This made everything clear to me. Thanks!
ScArcher2