how to encrypt an image using java

how to encrypt an image using java

To encrypt an image using Java, you can use a symmetric encryption algorithm such as AES (Advanced Encryption Standard) to encrypt the image file.

Here's an example of how to encrypt an image using Java and the AES algorithm:

refer to‮iruttual:‬.com
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class ImageEncryption {

  public static void main(String[] args) throws Exception {
    // Read the image file into a byte array
    FileInputStream in = new FileInputStream("image.jpg");
    byte[] image = new byte[in.available()];
    in.read(image);
    in.close();

    // Generate a secret key
    Key key = new SecretKeySpec("mysecretkey".getBytes(), "AES");

    // Create a cipher and initialize it for encryption
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, key);

    // Encrypt the image
    byte[] encryptedImage = cipher.doFinal(image);

    // Write the encrypted image to a file
    FileOutputStream out = new FileOutputStream("encrypted.jpg");
    out.write(encryptedImage);
    out.close();
  }
}

In the above example, the main() method reads the image file into a byte array, generates a secret key using the AES algorithm, and creates a cipher for encryption. The init() method initializes the cipher for encryption

Created Time:2017-11-01 20:42:50  Author:lautturi