package org.expeditee.encryption.core; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.expeditee.core.Image; import org.expeditee.encryption.CryptographyConstants; import org.expeditee.items.Picture; @SuppressWarnings("serial") public class EncryptedImage extends Image implements CryptographyConstants { /** String specifying the extension for encrypted images. */ public static String EXPEDITEE_ENCRYPTED_IMAGE_EXTENSION = ".eei"; private EncryptedImage(boolean fromDisk) { super(fromDisk); } public static Image getNoise() { return _manager.getNoise(); } public static Image getImage(String filename, byte[] keyBytes) { if (filename.endsWith(EXPEDITEE_ENCRYPTED_IMAGE_EXTENSION)) { File file = new File(filename); if (!file.exists() || file.isDirectory()) { return null; } try { SecretKey key = new SecretKeySpec(keyBytes, SymmetricAlgorithm); Cipher cipher = Cipher.getInstance(SymmetricAlgorithm); cipher.init(Cipher.DECRYPT_MODE, key); CipherInputStream fIn = new CipherInputStream(new FileInputStream(file), cipher); List bytesArrayList = new ArrayList(); int i; while((i = fIn.read()) != -1) { bytesArrayList.add((byte) i); } fIn.close(); byte[] bytes = new byte[bytesArrayList.size()]; for (int o = 0; o < bytes.length; o++) { bytes[o] = bytesArrayList.get(o); } return _manager.createImage(bytes); } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { e.printStackTrace(); return null; } } else { return Image.getImage(filename); } } public static boolean encryptImage(Picture picture, byte[] keyBytes) { SecretKey key = new SecretKeySpec(keyBytes, SymmetricAlgorithm); Path imagePath = Paths.get(picture.getPath()); String imageName = picture.getName(); try { Cipher cipher = Cipher.getInstance(SymmetricAlgorithm); cipher.init(Cipher.ENCRYPT_MODE, key); CipherInputStream fIn = new CipherInputStream(new FileInputStream(imagePath.toFile()), cipher); imagePath = imagePath.getParent().resolve(imageName.substring(0, imageName.lastIndexOf('.')) + EXPEDITEE_ENCRYPTED_IMAGE_EXTENSION); FileOutputStream fOut = new FileOutputStream(imagePath.toFile()); int i; while((i = fIn.read()) != -1) { fOut.write(i); } fIn.close(); fOut.flush(); fOut.close(); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException e) { e.printStackTrace(); return false; } return true; } public static void encryptImage(String filename, byte[] keyBytes) { } }