Search code examples
javaencryptionaesrsa

Right way to do encryption in java


I'm completely new with encryption stuff and i have some questions about encryption in java I use to do this for RSA encryption in java

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPTION_MODE,publicKey);
byte result = cipher.doFinal(data);

and same way to use AES and I use this code to generate a AES key

SecureRandom random = new SecureRandom();
byte [] key = new byte [16];
random.nextByte(key);
SecretKeySpec secretKey = new SecretKeySpec(key,"AES");

but as i saw in other programs code this is not how they use encryption i always see they use something as IV param in AES and they never use "AES" or "RSA" to get a cipher instance. Is the way i using to encrypt data safe? I'm sure that i missing something

UPDATE:

I also have a question about changing data size in AES encryption in the way that i use to encrypt data with AES it changes the data size from 1024 to 1040

    byte key [] = new byte[16];
    SecureRandom random = new SecureRandom();
    random.nextBytes(key);
    SecretKeySpec keySpec = new SecretKeySpec(key,"AES");
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.ENCRYPT_MODE,keySpec);
    FileInputStream in = new FileInputStream("test.txt");
    byte [] buffer = new byte[1024];
    byte [] encrypted;
    while (in.read()>0){
        encrypted = c.doFinal(buffer);
        System.out.println(encrypted.length);
    }

the out put is: 1040 1040 . . 1040

Simply encrypted data size is always 16 bytes more than original data Do i have to deal with this or it's because i using Cipher.getInstance("AES");


Solution

  • This is not the recommended way and you will need to change it. You may want to have a better look on StackOverflow. Your question is (in)directly answered in this post How to encrypt String in Java.

    Make sure you look further down to all the answers. For example this one will probably help you to understand more.