Question

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?

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. The client has the public key and the server has the private key.

Was it helpful?

Solution

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.

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