views:

31

answers:

1

Here are my constants

//Encryption fields
/** Algorithm=RSA Mode=ECB Padding=PKCS1Padding*/
public static final String ALGORITHM_MODE_PADDING = "RSA/ECB/PKCS1Padding";
/** Algorithm=RSA */
public static final String ALGORITHM = "RSA";
/** Provider=BouncyCastle */
public static final String PROVIDER = "BC";
/** Key size for the public and private keys */
public static final int KEY_SIZE = 1024;

I have made two public/private keys like this:

        //Generate the keys
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM,PROVIDER);
        kpg.initialize(KEY_SIZE);
        KeyPair kp = kpg.generateKeyPair();
        PublicKey pubk = kp.getPublic();
        PrivateKey prvk = kp.getPrivate();

I am decrypting like this:

        byte[] privateKey = Base64.decodeBase64(pKey); //decode
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory factory = KeyFactory.getInstance(ALGORITHM,PROVIDER);
        PrivateKey privKey = factory.generatePrivate(keySpec);
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, privKey);
        return cipher.doFinal(data);

This works with small amounts of data, when when the data becomes larger such as 263 bytes if fails with an IllegalBlockSizeException. I thinks this is because the data is greater than 256 bytes but that is just an guess and I have no idea of how to fix it.

What am I doing wrong?

UPDATE

I changed it to use the update method, but still have the same problem

        // encryption pass
    cipher.init(Cipher.ENCRYPT_MODE, privKey);
        byte[] cipherText = new byte[cipher.getOutputSize(data.length)];
        int ctLength = cipher.update(data, 0, data.length, cipherText, 0);
        ctLength += cipher.doFinal(cipherText, ctLength);

I am trying to implement digital signatures by the way. They client has the public key and the server has the private key.

+1  A: 

You cannot use RSA to encrypt more data than the size in bytes of the modulus - 11. This is probably what you are looking for.

GregS
Just curious: if you didn't want to bother with the hybrid method, would you just break your data down into sections of a small block size and encrypt sequentially? If that makes sense, how do you determine the block size?
Justin K
That would of course get rid of the errors. block size = modulus_size - 11, where modulus size = (modulus.bitLength() + 7) / 8.
GregS
+1 Hybrid encryption is the correct solution because symmetric ciphers are much faster, you wouldn't want to encrypt large chunks of data using only RSA - that would slow down the system a lot.
Krystian
I missed that you are trying to implement digital signatures. To do so, just use the Signature class.
GregS