将加密的图像字节保存到文件,并在java中恢复为原始图像 [英] Save encrypted image bytes to file and recover to original image in java

查看:200
本文介绍了将加密的图像字节保存到文件,并在java中恢复为原始图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图像的加密和解密问题,现在确定了原因,但我无法理解解决方案。



我正在尝试实现这个项目



但是问题是加密的图像字节在使用rasterclass和ImageIO类写入图像文件后不会恢复

我的问题,尝试的代码和解释是


我必须在加密图像中嵌入文本(Stegnography)。我googled并发现在图像中嵌入文本的代码。但是我必须首先加密图像,并在这个加密的图像中嵌入文本。我的尝试如下。

  / * 
*要更改此模板,请选择工具模板
*并在编辑器中打开模板。
* /
package tbn;

import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.imageio.ImageIO;

/ **
*
* @author用户
* /
public class DbtClass {

public static void main (String [] args){
try {
BufferedImage orgnlimage = ImageIO.read(new File(parrruuuuuu.png));
orgnlimage = user_space(orgnlimage);
byte [] orgnlimagebytes = get_byte_data(orgnlimage);
byte [] encryptedbytes = encrypt(orgnlimagebytes,abc);
BufferedImage encryptedimage = toImage(encryptedbytes,orgnlimage.getWidth(),orgnlimage.getHeight());
ImageIO.write(encryptedimage,png,new File(encrypted.png));

//////////////////////////////////////// /////////////////////////
///////////////// //////////////////////////////////////////////////

byte [] encryptedbytes2 = get_byte_data(encryptedimage);
System.out.println(encryptedbytes before writing:+ encryptedbytes2.length);

BufferedImage encryptedimage3 = ImageIO.read(new File(encrypted.png));
byte [] encryptedbyte3 = get_byte_data(encryptedimage3);
System.out.println(encryptedbytes after writing:+ encryptedbyte3.length);


} catch(IOException ex){
Logger.getLogger(DbtClass.class.getName())。log(Level.SEVERE,null,ex);
}


public static BufferedImage user_space(BufferedImage image){
//创建具有图像属性的new_img
BufferedImage new_img = new BufferedImage image.getWidth(),image.getHeight(),BufferedImage.TYPE_3BYTE_BGR);
Graphics2D graphics = new_img.createGraphics();
graphics.drawRenderedImage(image,null);
graphics.dispose(); //释放此图像的所有分配内存
return new_img;
}

public static byte [] get_byte_data(BufferedImage image){
WritableRaster raster = image.getRaster();
DataBufferByte buffer =(DataBufferByte)raster.getDataBuffer();
return buffer.getData();
}

public static byte [] encrypt(byte [] orgnlbytes,String key){
byte [] encbytes = null;
尝试{
密码密码= Cipher.getInstance(AES);
KeyGenerator keyGen = KeyGenerator.getInstance(AES);
SecureRandom random = SecureRandom.getInstance(SHA1PRNG);
//加密。安全随机
random.setSeed(key.getBytes());

keyGen.init(128,random);
//例如
SecretKey secretKey = keyGen.generateKey();
cipher.init(Cipher.ENCRYPT_MODE,secretKey);
encbytes = cipher.doFinal(orgnlbytes);
} catch(NoSuchAlgorithmException ex){
Logger.getLogger(DbtClass.class.getName())。log(Level.SEVERE,null,ex);
} catch(NoSuchPaddingException ex){
Logger.getLogger(DbtClass.class.getName())。log(Level.SEVERE,null,ex);
} catch(InvalidKeyException ex){
Logger.getLogger(DbtClass.class.getName())。log(Level.SEVERE,null,ex);
} catch(IllegalBlockSizeException ex){
Logger.getLogger(DbtClass.class.getName())。log(Level.SEVERE,null,ex);
} catch(BadPaddingException ex){
Logger.getLogger(DbtClass.class.getName())。log(Level.SEVERE,null,ex);
}
返回encbytes;
}

public static BufferedImage toImage(byte [] imagebytes,int width,int height){
DataBuffer buffer = new DataBufferByte(imagebytes,imagebytes.length);
WritableRaster raster = Raster.createInterleavedRaster(buffer,width,height,3 * width,3,new int [] {2,1,0},(Point)null);
ColorModel cm = new ComponentColorModel(ColorModel.getRGBdefault()。getColorSpace(),false,true,Transparency.OPAQUE,DataBuffer.TYPE_BYTE);
返回新的BufferedImage(cm,raster,true,null);
}
}

这里我使用栅格类写了加密图像, ImageIO.write()然后从文件中读取加密的字节使用ImageIO.read()。读取图像之前加密的字节[]和读取图像之间的字节[]是完全不同的



我有理由为此此处但是我不知道在这里做什么来克服

解决方案

我得到了一个解决方案, XOR加密
这将永远不会通过将加密的图像字节写入图像文件来导致数据丢失



所以感谢您在每一次在thids和previuos问题中的回复


i have a problem with encryption and decryption of an image the reason is identified now but I couldn't figureout the solution.

and I am trying to implement this project

but the problem is encrypted image bytes are not recovered after written to an image file using rasterclass and ImageIO class

my problem,tried code and explanations are submitted here

I have to embed text in an encrypted image(Stegnography). I googled and found codes for embedding text in an image. But I have to encrypt image at first and embed text in this encrypted image. My tries are as follows.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tbn;

import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.imageio.ImageIO;

/**
 *
 * @author user
 */
public class DbtClass {

    public static void main(String[] args) {
        try {
            BufferedImage orgnlimage = ImageIO.read(new File("parrruuuuu.png"));
            orgnlimage = user_space(orgnlimage);
            byte[] orgnlimagebytes = get_byte_data(orgnlimage);
            byte[] encryptedbytes = encrypt(orgnlimagebytes, "abc");
            BufferedImage encryptedimage = toImage(encryptedbytes, orgnlimage.getWidth(), orgnlimage.getHeight());
            ImageIO.write(encryptedimage, "png", new File("encrypted.png"));

            /////////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////////

            byte[] encryptedbytes2 = get_byte_data(encryptedimage);
            System.out.println("encryptedbytes before writing: "+encryptedbytes2.length);

            BufferedImage encryptedimage3 = ImageIO.read(new File("encrypted.png"));
            byte[] encryptedbyte3 = get_byte_data(encryptedimage3);
            System.out.println("encryptedbytes after writing: "+encryptedbyte3.length);


        } catch (IOException ex) {
            Logger.getLogger(DbtClass.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static BufferedImage user_space(BufferedImage image) {
        //create new_img with the attributes of image
        BufferedImage new_img = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D graphics = new_img.createGraphics();
        graphics.drawRenderedImage(image, null);
        graphics.dispose(); //release all allocated memory for this image
        return new_img;
    }

    public static byte[] get_byte_data(BufferedImage image) {
        WritableRaster raster = image.getRaster();
        DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
        return buffer.getData();
    }

    public static byte[] encrypt(byte[] orgnlbytes, String key) {
        byte[] encbytes = null;
        try {
            Cipher cipher = Cipher.getInstance("AES");
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            // cryptograph. secure random 
            random.setSeed(key.getBytes());

            keyGen.init(128, random);
            // for example
            SecretKey secretKey = keyGen.generateKey();
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            encbytes = cipher.doFinal(orgnlbytes);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(DbtClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(DbtClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(DbtClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalBlockSizeException ex) {
            Logger.getLogger(DbtClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadPaddingException ex) {
            Logger.getLogger(DbtClass.class.getName()).log(Level.SEVERE, null, ex);
        }
        return encbytes;
    }

    public static BufferedImage toImage(byte[] imagebytes, int width, int height) {
        DataBuffer buffer = new DataBufferByte(imagebytes, imagebytes.length);
        WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, 3 * width, 3, new int[]{2, 1, 0}, (Point) null);
        ColorModel cm = new ComponentColorModel(ColorModel.getRGBdefault().getColorSpace(), false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
        return new BufferedImage(cm, raster, true, null);
    }
}

Here I was written the encrypted image using raster class and ImageIO.write().Then read this encrypted bytes from file Using ImageIO.read().The encrypted byte[] before writing the image and the byte[] after reading the image are totaly different

I got reason for this here but I don't know what to do here to overcome

解决方案

I got a solution by replacing AES encryption by XOR encryption this will never cause the data loss by writing encrypted image bytes to image file

so thank you for your responses in every time in thids and previuos question

这篇关于将加密的图像字节保存到文件,并在java中恢复为原始图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆