Hi friends,
I need to encrypt an image of size 151*15 with RSA.
This is the java code to encrypt the image file
import javax.crypto.Cipher;
plaintext = time;
cipher = Cipher.getInstance('RSA');
keygen = java.security.KeyPairGenerator.getInstance('RSA');
keyPair = keygen.genKeyPair();
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate())
plaintextUnicodeVals = uint16(plaintext)
plaintextBytes = typecast(plaintextUnicodeVals, 'int8')
ciphertext = cipher.doFinal(plaintextBytes);
This is the image file to be encrypted
I got the following error
Java exception occurred: javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes
At com.sun.crypto.provider.RSACipher.a(DashoA13*..)
at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
Please give me the hint or procedure so that I can approach in the right direction.
Thanks.
Error while trying to encrypt an image of size 151*15 with RSA
Hello Jillian,
You have to make sure that you are using AES for encrypting large data. Note that RSA cannot be able to encrypt data larger than key's size. But you can be able to encrypt an AES key using RSA, and the whole image with AES.
When you use RSA you will notice that it is very slow, and for that matter it will not be good for when it comes to encryption of large data, in the event that you wish to split up an image to a large number of blocks of for instance size 117 bytes and thereafter encrypt them one after the other
For instance:
  public static byte[] encrypt(byte[] data) {    try {      KeyPair keyPair = initalizeKeyPair();      final javax.crypto.Cipher rsa = javax.crypto.Cipher.getInstance("RSA");     rsa.init(javax.crypto.Cipher.ENCRYPT_MODE, keyPair.getPublic());      SecureRandom random = newSecureRandom();      final byte[] secretKey = new byte[16];     random.nextBytes(secretKey);      final javax.crypto.Cipher aes = javax.crypto.Cipher.getInstance("AES");      SecretKeySpec k =new SecretKeySpec(secretKey, "AES");     aes.init(javax.crypto.Cipher.ENCRYPT_MODE, k);     final byte[] ciphedKey = rsa.doFinal(secretKey);      final byte[] ciphedData = aes.doFinal(data);      byte[] result = new byte[256 + ciphedData.length];      System.arraycopy(ciphedKey, 0, result,0, 256);      System.arraycopy(ciphedData, 0, result, 256, ciphedData.length);      returnresult;    } catch (... e) {      throw new SomeException(e);    } }
Regards,
Carl