密码学课程设计——多人加密聊天系统

  • 实验设计要求:

模块:

  1. 用户认证:数字签名方案
  2. 信息加密:公钥加密方案
  3. 信息隐藏:LSB方案

要求:

实现登陆验证,信息发送和接收(文本和图片),信息加密解密,信息签名和签名验证

 

  • 关键代码解释说明:

1.数字签名:使用java security包中的keypairgenerator 生成rsa秘钥对,长度为512:

2.获取秘钥对中的publicexponent,modulus,privateexponent:

3.加密代码:

其中,输入要加密的信息后,转成byte[],通过取模运算,产生加密信息,转成字节。

4.解密代码:

同解密过程一样。

5.数字签名验证:

通过登录用户输入的姓名,在数据库中查找到对应的e和n(即公钥),通过用户输入的私钥d,对“yaxin”用私钥加密后,服务端用公钥进行解密,内容为yaxin即为验证成功。

6.数据库查找代码:

Resultset集存储客户的e,n,d 返回arraylist可供查找。

8.客户注册代码:

若客户为新注册用户,选择注册按钮,生成新的秘钥对,用户自行保留私钥d,新生成的用户信息将被存储在数据库chatroom1中:

7.客户登陆代码:

客户需要输入昵称和私钥d进行数字签名登陆验证。

8.客户私聊消息加密:通过被传输消息的客户在数据库系统中存储的公钥,传输消息方将数据进行加密,被传输消息方先将数据解密,在显示出来,客户端只会看到解密的消息,非被传输方会看到加密后的信息,但是无法解出。

三、代码展示:

Server类:
package MyChatRoom;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.ihep.Mysqllink;
import com.ihep.RSADemo;


public class Server {
	
	private ServerSocket sc;
	private ExecutorService threadpool;
	private List<PrintWriter> pws;
	private Map<String,PrintWriter> maps;
	
	
	public Server() {
		try {
			sc= new ServerSocket(8088);
		} catch (IOException e) {
			e.printStackTrace();
		}
		threadpool 
		   = Executors.newFixedThreadPool(100);
		pws = new ArrayList<PrintWriter>();
		maps = new HashMap<String,PrintWriter>();
		RSADemo rsa=new RSADemo();	
			Mysqllink msq=new Mysqllink();
			//msq.Mysqllinkstart();
	}
	
	public void start() {
		int count = 0;
		while(true) {
			
			System.out.println("wait..");
			try {
				Socket s= sc.accept();
				ClientHandle hc 
				  = new ClientHandle(s);
				threadpool.execute(hc);
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			count++;
			System.out.println
			   ("第"+count+"个客户连接成功!");
		}
	}
	//自定义方法
	//遍历map集合,将所有在线的好友name拼接成字符串,
	//并返回
	public String findAll(){
		synchronized (maps) {
		//1.遍历map集合,拿到所有在线人的name
			Set<String> names = maps.keySet();
		//2. 遍历set集合,拿到所有人的name
			String nms="";
			Iterator<String> it =  names.iterator();
			while(it.hasNext()){
				String nm = it.next();
				nms +=nm;//重新赋值 拼接每一个在线好友的name
				nms +=",";
			}
		
			return nms;
		}
	}

	//创建ClientHandle类(助教模板类)
	class  ClientHandle implements Runnable{
		Socket s;
		PrintWriter pw;
		String name;
		public ClientHandle(Socket s) {
			this.s=s;
		
			
		}
		public void run() {
			//获取该客户端的输入流,读取该客户端的消息
			try {
				InputStream is 
				  = s.getInputStream();
				InputStreamReader isr 
				 = new InputStreamReader(is);
				BufferedReader br 
				  = new BufferedReader(isr);
				//从socket中获取该客户端的输出流
				OutputStream os = s.getOutputStream();
				OutputStreamWriter osw
					= new OutputStreamWriter(os);
				pw
				  = new PrintWriter(osw,true);
								//在读消息之前,先读客户端发来的 昵称
				name = br.readLine();
				
				//将name和name对应的pw存入map集合中
				synchronized (maps) {
					maps.put(name,pw);
				}		
				pw.println("欢迎你,"
				    +name+",当前在线人数【"+(pws.size()+1)+"】人!");
				//服务器告诉刚上线的客户端都有哪些人在线
				String nms = findAll();
				//至此,所有在线的name都在nms字符串中
				pw.println("当前在线好友:"+nms);
				sendToAll(name+
						"上线了!当前在线人数【"
						+(pws.size()+1)+"】人!");
				
				sendToAll("当前在线好友:"+nms);
				
				//将该客户端的输出流加入到集合中存储起来
				synchronized (pws) {
					pws.add(pw);
				}
				
		SimpleDateFormat sdf 
			 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			Date d = null;
			while(true) {
					String str = br.readLine();//阻塞
					d = new Date(); //当前时间
					String time = sdf.format(d);
					
					System.out.println(name+":"+str);//输出在控制台
					if(str.startsWith("@")){
						//单聊
						//1. 解析出要单聊的name,也就是截取@和:之间的name
						String to_name = str.substring(1, str.indexOf(":"));
						//2. 根据第一步解析出的人名从map中获取到
						//   该人名所对应的pw
						
						PrintWriter to_pw = maps.get(to_name);
						//3. 解析出单聊的消息,也就是截取:之后的内容
						
						String msg = str.substring(str.indexOf(":")+1);
						
					    Mysqllink msq=new Mysqllink();
						ArrayList<String> list=msq.selectsj(to_name);
						//System.out.println(list.get(0).toString()+'\n'+list.get(1).toString()+'\n'+list.get(2).toString());
					   
						RSADemo rsa=new RSADemo();
						
						byte[] mesag=rsa.encrypt((msg.trim()).getBytes(), list.get(0).toString(), list.get(1).toString());
						
						System.out.println("加密过后的消息:"+mesag);
						
						byte[] msg_afterde=rsa.decrypt(mesag, list.get(2).toString(), list.get(1).toString());
						
						String msg_afterde1=new String(msg_afterde);
						
						System.out.println("解密后的消息"+msg_afterde1);						
						//4. 使用第2步获得的pw将第3步解析出的msg进行发送
						to_pw.println(time+"\n"+name+"悄悄对你说:"+msg_afterde1);
						//5. 消息也要返回给自己,不仅是给要单聊的那个人
						pw.println(time+"\n"+"我对"+to_name+"悄悄说:"+msg_afterde1);
						sendToAll(time+"\n"+name+":"+mesag.toString());
					}else{
						
						
						//群发
						sendToAll(time+"\n"+name+":"+str);
					}
				}
			}catch(Exception e) {
				//追踪一异常信息
				//e.printStackTrace();
			}finally{
				//不管出不出异常,finally都会被执行
				//而且是最后执行
				synchronized (pws) {
					pws.remove(pw);
				}
				
				// 当好友下线,除了从list集合中移除该客户端的pw
				// 也要从maps集合中移除该客户端信息
				synchronized (maps) {
					maps.remove(name);
				}
				//移除该客户端之后,再向所有人广播,**下线了
				sendToAll(name+"下线了!当前人数【"+pws.size()+"】人!");
				//广播 更新好友列表:
				//1.可以调用sendtoall (遍历list中的所有pw)
				//2.也可以遍历map集合中的所有values
				String nms = findAll();
				sendToAll("当前在线好友:"+nms);
				
				if(s!=null){
					try {
						s.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	//把广播功能(群发)for循环抽取出来
	public void sendToAll(String msg){
		
		synchronized (pws) {
			for (int i = 0; i <pws.size(); i++) {
				pws.get(i).println(msg);
			}
		}
	}
	
	public static void main(String[] args) {
		Server s  = new Server();
		s.start();
	}

}

Client类:
package MyChatRoom;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.security.*;
import java.security.interfaces.*;
import java.math.*;

import java.awt.BorderLayout;
import java.sql.ResultSet;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.ihep.Mysqllink;
import com.ihep.RSADemo;

public class Client implements ActionListener{
	private Socket s;
	private JFrame f; //聊天界面窗口
	private JTextArea jta;//显示聊天内容的文本域
	private JLabel lab ;  //显示昵称的标签
	private JTextField jtf;//输入消息的框
	private JButton btn;//发送消息的按钮
	private JButton btn1;
	private JFrame dl1;
	private JButton b1;
	private JButton b2;	
	private java.awt.Graphics g;
	private int rgb;
	private String name; //客户端输入的昵称
	private PrintWriter pw;
	private String siyao;
		public void setname(String n) {
		name=n;
	}
	
	public Client() {
		Mysqllink mysql=new Mysqllink();
		btn1=new JButton("图片");
		dl1=new JFrame("登录/注册界面");
		JPanel jp=new JPanel();
		b1=new JButton("登录");
		b2=new JButton("注册");
		//对界面组件(零部件)进行初始化
		f  = new JFrame();
		jta = new JTextArea(16,16); //行 列
		jta.setEditable(false);//不可编辑
		jta.setFont(
				new Font("微软雅黑",Font.ITALIC,16)
				);
		
		jtf = new JTextField(16); //每行字数
		btn = new JButton("发送");
		
		//让用户在输入框中输入要连接的服务器的ip和port
		
		String ip = 
		    JOptionPane.showInputDialog("请输入服务器IP:");
		
		String p = 
			JOptionPane.showInputDialog("请输入端口:");
		
		name = JOptionPane.showInputDialog("请输入昵称:");
		
		//把字符串端口转换成int数字端口
		
		initdl();
		showdl();
			
		b1.addActionListener(new ActionListener() {
			 
			@Override
			public void actionPerformed(ActionEvent e) {
				
				dl1.dispose();
				//name 
		 // = JOptionPane.showInputDialog("请输入昵称:");
				//setname(name);
		System.out.println(name);
		        siyao 
		  = JOptionPane.showInputDialog("请输入私钥d");
		        System.out.println(name);
		        try {
					ArrayList<String> list1=mysql.selectsj(name);
                    RSADemo rsa=new RSADemo();
                    
                    rsa.yanzheng(siyao,list1.get(1).toString(),list1.get(0).toString());
					
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		        
		        init();
	            show();
	          
			}
			
			});
		
		b2.addActionListener(new ActionListener() {
			 
			@Override
			public void actionPerformed(ActionEvent e) {
				
				dl1.dispose();
				//name = JOptionPane.showInputDialog("请输入昵称:");
				//setname(name);
				System.out.println(name);
				RSADemo rsa=new RSADemo();
		        rsa.generateKey();
		       // System.out.println(rsa.gete());
		        try {
					mysql.addsj(name, rsa.gete(),rsa.getn(),rsa.getd());
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		        System.out.println("你的私钥d"+rsa.getd());
		        System.out.println("你的公钥"+rsa.gete());
		        init();
		        show();
		        //start();
		        
		        //System.out.println(name);
		     
			}
			   
			});
		lab = new JLabel(name); //待改动
		try {   
			int port = Integer.parseInt(p);
			s = new Socket(ip,port);
		
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
			
		btn.addActionListener(this);//点击按钮将消息发出
		jtf.addActionListener(this);//按回车消息就发出
	}
	

	//自定义方法,将各个组件放到窗口的指定位置
	public void init(){
		//将显示聊天内容的文本域添加至可滚动画布上
		JScrollPane jsp  = new JScrollPane(jta);
		//将标签 输入框 发送按钮 添加到一个普通画布上
		JPanel p = new JPanel();  
		p.add(lab);
		p.add(jtf);
		p.add(btn);
		p.add(btn1);
		JPanel jp3=new JPanel();
		p.add(jp3);
		//将上述2个画布添加到窗口frame上
		f.add(jsp,BorderLayout.CENTER);
		f.add(p,BorderLayout.SOUTH);
		this.g=jp3.getGraphics();
	}
	//自定义方法,显示窗口
	public void show(){
		f.pack();// 自适应调整大小
		f.setLocationRelativeTo(null);//居中
		f.setDefaultCloseOperation(3);//真正关闭
		f.setVisible(true); //显示出来
	}
	public void initdl() {
		JPanel jp=new JPanel();		
		jp.add(b2);
		jp.add(b1);
		dl1.add(jp,BorderLayout.CENTER);
		
	}
	public void showdl() {
		dl1.pack();
		dl1.setLocationRelativeTo(null);//居中
		dl1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		dl1.setVisible(true);
		//System.out.println(name);
	}
	
	public  void start() {
		 readMsg();
		try {
			OutputStream os
			 = s.getOutputStream();
			OutputStreamWriter osw 
			 = new OutputStreamWriter(os);
			pw 
			 = new PrintWriter(osw,true);
			pw.println(name);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	 }
	 
	 //自定义方法,创建匿名内部类线程,
	 //一直监听服务器有发来消息
	 
	 public void readMsg() {
		 new Thread() {
			 public void run() {
				 //从socket中获取输入流,不停读取
				 try {
					 InputStream is 
					  = s.getInputStream();
					InputStreamReader isr 
					 = new InputStreamReader(is);
					BufferedReader br 
					  = new BufferedReader(isr);
					String str = null;
					while((str=br.readLine())!=null) {
						//System.out.println(str);
						jta.append(str+"\n");
					}
				 
				 }catch(Exception e) {
					 
				 }
			 }
		 }.start();
	 }
	public static void main(String[] args) {
		Client c = new Client();
		c.start();
	}

	//当按钮等组件被点击,该方法能自动执行
	public void actionPerformed(ActionEvent e) {
		//1. 获取到输入框中的信息
		String msg = jtf.getText();
		//2. 使用客户端的输出流将信息写出
		pw.println(msg);
		//3. 清空输入框
		jtf.setText("");	
	}
}
数据库代码:
package com.ihep;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.math.*;

public class Mysqllink {	
	Connection con = null;
	public Mysqllink() {
	          //驱动程序名
	       String driver = "com.mysql.cj.jdbc.Driver";
	         //URL指向要访问的数据库名mydata
	         String url = "jdbc:mysql://localhost:3306/wyx?serverTimezone=UTC";
	         //"jdbc:mysql://xx.x.xx.xxx:3306/health?useUnicode=true&amp;characterEncoding=UTF8"/>
	      //MySQL配置时的用户名
	         String user = "root";
	         //MySQL配置时的密码
	         String password = "Wyx10230331";
	         //遍历查询结果集
	 
	             //加载驱动程序
	             try {
					Class.forName(driver);
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	             //1.getConnection()方法,连接MySQL数据库!!
	             try {
					con = DriverManager.getConnection(url,user,password);
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
	             try {
	             if(!con.isClosed())
					    System.out.println("Succeeded connecting to the Database!");
			    } catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

}
	public void addsj(String name,String e,String n,String d) throws SQLException {
		  //
		PreparedStatement psql;
		//ResultSet res;
		psql = con.prepareStatement("insert into chatroom1(昵称,e,n,d ) values(?,?,?,?)");
		psql.setString(1, name);              //设置参数1,创建id为3212的数据
		psql.setString(2, e);    
		psql.setString(3, n); 
		psql.setString(4, d);
		psql.executeUpdate();           //执行更新
		con.close();
		psql.close();
	}
	//public static void main(String[] args) {
	//	Mysqllink mysql=new Mysqllink();
	//}
	public ArrayList<String> selectsj(String n) throws SQLException {
		 Statement statement = con.createStatement();
		             //要执行的SQL语句
		              //3.ResultSet类,用来存放获取的结果集!!
		 String id=new String();
		 System.out.println(n);
		 String name=String.valueOf(n);
		 String sql="select *from chatroom1 where 昵称='"+name+"'";
		 ResultSet rs = statement.executeQuery(sql);
		 System.out.println(name); 	
		 ArrayList<String> list=new ArrayList<String>();
		// System.out.println(rs.next());
		             while(rs.next()){
		            //	 System.out.println(rs.getString(1));
		            	// System.out.println(rs.getString(2));
		                 list.add(rs.getString("e"));//0
		                 list.add(rs.getString("n"));//1
		                 list.add(rs.getString("d"));//2
		               //System.out.println("数据库里的e  "+list.get(0)+'\n'+"数据库里的n   "+list.get(1)+'\n'+"数据库里的d   "+rs.getString("d")+'\n'+rs.getString("昵称"));
		               	}  
		             
		             rs.close();  
		             con.close();
		             return list;
}
}
public class CopyDemo {
	public static void main(String[] args) throws Exception {
		//读取原文件
		RandomAccessFile raf1 = new RandomAccessFile("6fc2d95f1837905a0ee88cb5e1da58fa.jpg", "r");
		//将读取到的字节写入目标文件
		RandomAccessFile raf2 = new RandomAccessFile("6fc2d95f1837905a0ee88cb5e1da58fa_copy.jpg", "rw");
		
		//注意:读到文件末尾返回-1
		
		//d 表示读到的字节
		int d = -1;
		System.out.println("开始复制");
		
		//获取自1970年1月1日0时到现在的毫秒数
		long time1=System.currentTimeMillis();
		while((d=raf1.read())!=-1) {	
			raf2.write(d);
		}
		long time2 = System.currentTimeMillis();
		System.out.println("用时: "+(time2-time1)+"ms");
		
		raf1.close();
		raf2.close();
	}

}
信息隐藏:LSB方案实现:
package TEST;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Enumeration;


public class InfoHideToBmpImage extends JFrame {
    private int displayWidth, displayHeight;
    private JTextArea textArea;

    private InfoHideToBmpImage() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        displayWidth = (int) (screenSize.getWidth() * 0.7);
        displayHeight = (int) (screenSize.getHeight() * 0.7);
        initFrame();
    }

    private void initFrame() {
        Util.setUIFont(new FontUIResource("微软雅黑", 0, 20));
        setLayout(new BorderLayout());
        setJMenuBar(initMenuBar());
        add(initTextAreaJScrollPane(), BorderLayout.SOUTH);
        setTitle("LSB隐藏器");
        setSize(displayWidth, displayHeight);
        //设置窗体出现在屏幕中间
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }


    private final String FILE_MENU_NAME = "File";
    private final String OPEN_MENU_ITEM_NAME = "Open";
    private final String SAVE_MENU_ITEM_NAME = "Save";
    private final String LSB_MENU_NAME = "LSB";
    private final String HIDE_MENU_ITEM_NAME = "Hide";
    private final String SHOW_MENU_ITEM_NAME = "Show";
    private final String BMP = "bmp";

    private JMenuBar initMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        MenuItemListener listener = new MenuItemListener();
        JMenu menu = new JMenu(FILE_MENU_NAME);
        JMenuItem openItem = new JMenuItem(OPEN_MENU_ITEM_NAME);
        openItem.addActionListener(listener);
        JMenuItem saveItem = new JMenuItem(SAVE_MENU_ITEM_NAME);
        saveItem.addActionListener(listener);
        menu.add(openItem);
        menu.add(saveItem);
        menuBar.add(menu);
        menu = new JMenu(LSB_MENU_NAME);
        JMenuItem hideItem = new JMenuItem(HIDE_MENU_ITEM_NAME);
        hideItem.addActionListener(listener);
        JMenuItem showItem = new JMenuItem(SHOW_MENU_ITEM_NAME);
        showItem.addActionListener(listener);
        menu.add(hideItem);
        menu.add(showItem);
        menuBar.add(menu);
        return menuBar;
    }

    class MenuItemListener implements ActionListener {
        private final String DEFAULT_CURRENT_DIRECTORY_PATH = "C:/Users/LW/Desktop";
        private JFileChooser fileChooser;
        private BmpImageInfo imageInfo;
        private static final byte OPEN_FILE = 1;
        private static final byte SAVE_FILE = 2;

        MenuItemListener() {
            fileChooser = new JFileChooser(DEFAULT_CURRENT_DIRECTORY_PATH);
            fileChooser.setFileFilter(new FileNameExtensionFilter("24位位图(*.bmp)", BMP));
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            switch (e.getActionCommand()) {
                case OPEN_MENU_ITEM_NAME: {
                    openHandler();
                    break;
                }
                case SAVE_MENU_ITEM_NAME: {
                    saveHandler();
                    break;
                }
                case HIDE_MENU_ITEM_NAME: {
                    hideHandler();
                    break;
                }
                case SHOW_MENU_ITEM_NAME: {
                    showHandler();
                    break;
                }
                default: {
                    break;
                }
            }
        }

        private void showHandler() {
            if (null == imageInfo) {
                textArea.setText("请选择图片后重试");
                return;
            }

            String info = Util.analysisHideInfo(imageInfo);
            if ("".equals(info.trim())) {
                textArea.setText("提示信息: 解析出来的信息为空");
                return;
            }

            textArea.setText(info);
        }

        private void hideHandler() {
            if (imageInfo == null || imageInfo.blue == null) {
                textArea.setText("请打开bmp图片文件后重试!");
                return;
            }

            String text = textArea.getText();
            if (null == text || text.trim().length() <= 0) {
                textArea.setText("请在文本框中输入需要隐藏的文本信息后重试");
                return;
            }

            if (Util.hideInfoToBmp(imageInfo, textArea.getText())) {
                textArea.setText("隐藏文本信息成功");
                return;
            }

            textArea.setText("隐藏文本信息失败");

        }

        private void openHandler() {
            File file = selectFile(OPEN_FILE);
            if (null == file) {
                return;
            }

            imageInfo = Util.analysisBmpImage(file);
            showBmpImage(imageInfo);
            textArea.setText("打开图片文件成功!");
            if (imageInfo.getBfOffBits() > BmpImageInfo.DEFAULT_BF_OFF_BITS) {
                textArea.append("  图片文件有可能存在隐藏信息");
            }
        }


        private void saveHandler() {
            File file = new File(generateSaveFileName());
            fileChooser.setSelectedFile(file);
            file = selectFile(SAVE_FILE);
            Util.saveBmpImage(imageInfo, file);
            textArea.setText("保存图片文件成功");
        }

        private String generateSaveFileName() {
            File selectedFile = fileChooser.getSelectedFile();
            String name = selectedFile.getName();
            name = name.substring(name.lastIndexOf('_') + 1);
            String parent = selectedFile.getParent();
            String now = LocalTime.now().toString().replaceAll(":", "-");
            return String.join("", parent, "/", now, "_", name);
        }

        private File selectFile(byte type) {
            // 不是确认
            if (type == OPEN_FILE && JFileChooser.APPROVE_OPTION != fileChooser.showOpenDialog(null)) {
                return null;
            }

            if (type == SAVE_FILE && JFileChooser.APPROVE_OPTION != fileChooser.showSaveDialog(null)) {
                return null;
            }

            File selectedFile = fileChooser.getSelectedFile();
            String fileName = selectedFile.getName();
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (!BMP.equals(suffixName)) {
                System.out.println("非BMP类型文件");
                return null;
            }

            return selectedFile;
        }
    }

    private JScrollPane initTextAreaJScrollPane() {
        JTextArea textArea = new JTextArea();
        this.textArea = textArea;
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(displayWidth, 200));
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        return scrollPane;
    }

    private void showBmpImage(BmpImageInfo imageInfo) {
        DrawPanel drawPanel = new DrawPanel(imageInfo);
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewportView(drawPanel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        add(scrollPane);
        // 刷新界面
        setVisible(true);
    }


    /**
     * 绘图面板
     */
    class DrawPanel extends JPanel {
        BmpImageInfo bmpImageInfo;

        DrawPanel(BmpImageInfo imageInfo) {
            bmpImageInfo = imageInfo;
            // 将画板撑大,这样当图片长宽过大时 jScrollPane 才会显示滚动条
            setPreferredSize(new Dimension(imageInfo.getImageWidth(), imageInfo.getImageHeight()));
        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            if (null == bmpImageInfo) {
                return;
            }

            int height = bmpImageInfo.getImageHeight();
            int width = bmpImageInfo.getImageWidth();
            // 水平居中x 初始坐标
            int initX = 0;
            if (displayWidth > width) {
                Point location = getLocation();
                initX = (int) location.getX() + ((displayWidth - width) >> 1);
            }

            // 这里只考虑了 height 为正数的情况
            for (int h = 0; h < height; h++) {
                for (int w = 0; w < width; w++) {
                    g.setColor(new Color(bmpImageInfo.red[h][w], bmpImageInfo.green[h][w], bmpImageInfo.blue[h][w]));
                    g.fillRect(w + initX, h, 1, 1);
                }
            }
        }
    }

    public static void main(String[] args) {
        new InfoHideToBmpImage();
    }

}


class BmpImageInfo {
    /**
     * 默认偏移量
     */
    static final int DEFAULT_BF_OFF_BITS = 54;

    private int height = -1;
    private int width = -1;

    byte[] fileHeader = new byte[14];
    byte[] informationHeader = new byte[40];
    /**
     * 位图数据数组,即一个像素的三个分量的数据数组
     */
    int[][] red, green, blue;

    /**
     * 类型是否是位图
     *
     * @return true/false
     */
    boolean isBmpType() {
        return fileHeader[0] == 0X42 && fileHeader[1] == 0X4D;
    }

    /**
     * 是否是24位bmp
     *
     * @return true : 是;false: 否
     */
    boolean is24BitCount() {
        return informationHeader[15] == 0 && informationHeader[14] == 24;
    }

    /**
     * 初始化位图数据矩阵
     *
     * @return true:成功;false:失败
     */
    boolean initBitmapDataArr() {
        int imageWidth = getImageWidth();
        int imageHeight = getImageHeight();
        boolean flag = imageHeight != 0 && imageWidth != 0;
        if (flag) {
            red = new int[imageHeight][imageWidth];
            green = new int[imageHeight][imageWidth];
            blue = new int[imageHeight][imageWidth];
        }

        return flag;
    }

    /**
     * 获取偏移量
     *
     * @return 偏移量
     */
    int getBfOffBits() {
        return bytesToInt(Arrays.copyOfRange(fileHeader, 10, 14));
    }

    /**
     * 设置偏移量
     *
     * @param offset 偏移量
     */
    void setBfOffBits(int offset) {
        if (offset <= DEFAULT_BF_OFF_BITS) {
            return;
        }

        byte[] bs = intToBytes(offset);
        int index = 10, bi = 0;
        while (index < fileHeader.length) {
            fileHeader[index] = bs[bi++];
            index++;
        }
    }

    int getImageWidth() {
        if (width == -1) {
            width = bytesToInt(Arrays.copyOfRange(informationHeader, 4, 8));
        }

        return width;
    }

    int getImageHeight() {
        // 需要注意的是 height 有可能为负数
        if (height == -1) {
            height = bytesToInt(Arrays.copyOfRange(informationHeader, 8, 12));
        }

        return height;
    }

    private int bytesToInt(byte[] bytes) {
        if (null == bytes || bytes.length <= 0) {
            return 0;
        }

        return (bytes[3] & 0xff << 24) | (bytes[2] & 0xff) << 16 | (bytes[1] & 0xff) << 8 | bytes[0] & 0xff;
    }

    private byte[] intToBytes(int integer) {
        byte[] bytes = new byte[4];

        bytes[3] = (byte) (integer >> 24);
        bytes[2] = (byte) (integer >> 16);
        bytes[1] = (byte) (integer >> 8);
        bytes[0] = (byte) (integer);
        return bytes;
    }
}

class Util {
    private Util() {
    }

    /**
     * 设置全局页面字体大小
     *
     * @param f FontUIResource实例
     */
    static void setUIFont(FontUIResource f) {
        Enumeration<Object> keys = UIManager.getDefaults().keys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            if (UIManager.get(key) instanceof FontUIResource) {
                UIManager.put(key, f);
            }
        }
    }

    private static final String END_BINARY_STR = "0101010101010101";
    private static final char VALUE_0 = '0';

    static boolean hideInfoToBmp(BmpImageInfo imageInfo, String text) {
        imageInfo.setBfOffBits(imageInfo.getBfOffBits() + 1);
        String binary = toBinary(text).concat(END_BINARY_STR);
        char[] chars = binary.toCharArray();
        int i = 0, j = 0, cnt = 0, len = chars.length;
        for (; i < imageInfo.getImageHeight(); i++) {
            for (; j < imageInfo.getImageWidth(); j++) {
                imageInfo.blue[i][j] = getModifyBitData(imageInfo.blue[i][j], chars[cnt++]);
                if (cnt >= len) {
                    return true;
                }

                imageInfo.green[i][j] = getModifyBitData(imageInfo.green[i][j], chars[cnt++]);
                if (cnt >= len) {
                    return true;
                }

                imageInfo.red[i][j] = getModifyBitData(imageInfo.red[i][j], chars[cnt++]);
                if (cnt >= len) {
                    return true;
                }
            }
        }

        imageInfo.setBfOffBits(BmpImageInfo.DEFAULT_BF_OFF_BITS);
        return false;
    }

    private static int getModifyBitData(int oldValue, char c) {
        // 0 ASCLL 48
        if (c == VALUE_0) {
            return oldValue & 0XE;
        }

        return oldValue | 0X1;
    }

    static String analysisHideInfo(BmpImageInfo imageInfo) {
        if (imageInfo.getBfOffBits() == BmpImageInfo.DEFAULT_BF_OFF_BITS) {
            return "";
        }

        StringBuilder binStrBuilder = new StringBuilder(imageInfo.blue[0].length << 3);
        StringBuilder wordBin = new StringBuilder(16);
        int cnt = 0;
        flag:
        for (int i = 0; i < imageInfo.getImageHeight(); i++) {
            for (int j = 0; j < imageInfo.getImageWidth(); j++) {
                wordBin.append(imageInfo.blue[i][j] & 0X1);
                if (++cnt >= 16) {
                    if (isEndWithAppend(binStrBuilder, wordBin)) {
                        break flag;
                    }

                    cnt = 0;
                }

                wordBin.append(imageInfo.green[i][j] & 0X1);
                if (++cnt >= 16) {
                    if (isEndWithAppend(binStrBuilder, wordBin)) {
                        break flag;
                    }

                    cnt = 0;
                }

                wordBin.append(imageInfo.red[i][j] & 0X1);
                if (++cnt >= 16) {
                    if (isEndWithAppend(binStrBuilder, wordBin)) {
                        break flag;
                    }

                    cnt = 0;
                }
            }
        }

        return toString(binStrBuilder.toString());
    }

    /**
     * 添加内容,并判断是否结束
     *
     * @param binStrBuilder 二进制串
     * @param wordBin       一个字的二进制串
     * @return true:结束;false:否
     */
    private static boolean isEndWithAppend(StringBuilder binStrBuilder, StringBuilder wordBin) {
        if (END_BINARY_STR.equals(wordBin.toString())) {
            return true;
        }

        binStrBuilder.append(wordBin);
        wordBin.delete(0, 16);
        return false;
    }

    /**
     * 解析bmp图片
     */
    static BmpImageInfo analysisBmpImage(File file) {
        BmpImageInfo imageInfo = new BmpImageInfo();

        if (!isWindowOperatingSystem()) {
            System.out.println("非windows操作系统,终止");
            return imageInfo;
        }

        if (null == file) {
            return imageInfo;
        }

        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            bis.read(imageInfo.fileHeader);

            if (!imageInfo.isBmpType()) {
                System.out.println("非bmp类型文件");
                return imageInfo;
            }

            bis.read(imageInfo.informationHeader);
            if (!imageInfo.is24BitCount()) {
                System.out.println("非24位bmp类型文件");
                return imageInfo;
            }

            if (imageInfo.getBfOffBits() > BmpImageInfo.DEFAULT_BF_OFF_BITS) {
                System.out.println("bmp文件偏移超过默认偏移量,可能存在隐藏信息");
                bis.skip(imageInfo.getBfOffBits() - BmpImageInfo.DEFAULT_BF_OFF_BITS);
            }


            if (!imageInfo.initBitmapDataArr()) {
                System.out.println("初始化位图数据矩阵失败,可能未读取信息头数据");
                return imageInfo;
            }

            int imageWidth = imageInfo.getImageWidth();
            // 通过计算得到每行计算机需要填充的字符数。
            // 为什么要填充?这是因为windows系统在扫描数据的时候,每行都是按照4个字节的倍数来读取的。
            // 因为图片是由每个像素点组成。而每个像素点都是由3个颜色分量来构成的,而每个分量占据1个字节。
            // 因此在内存存储中实际图片数据每行的长度是width*3
            int skipCount = getSkipCount(imageWidth);

            int imageHeight = imageInfo.getImageHeight();
            // 这里需要注意,因为根据bmp的保存格式。
            // 位图数据中height的值如果是正数的话:
            // 那么数据就是按从下到上,从左到右的顺序来保存。这个称之为倒向位图。
            // 反之就是按从上到下,从左到右的顺序来保存。这个则称之为正向位图。
            if (imageHeight < 0) {
                // todo 大多数BMP位图是倒向的位图,imageHeight是正值,所以负值的情况暂未实现
                return null;
            }

            for (int i = imageHeight - 1; i >= 0; i--) {
                for (int j = 0; j < imageWidth; j++) {
                    // 这里遍历的时候,一定要注意本来像素是有RGB来表示,
                    // 但是在存储的时候由于windows是小段存储,所以在内存中是BGR顺序。
                    imageInfo.blue[i][j] = bis.read();
                    imageInfo.green[i][j] = bis.read();
                    imageInfo.red[i][j] = bis.read();
                }

                // 跳过每一行的补0项 ,网上有些是在j==0时进行跳过,表示傻傻不明白
                bis.skip(skipCount);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return imageInfo;
    }

    /**
     * 获取填充的补0数
     *
     * @param width 图像像素宽度
     * @return 跳过数目
     */
    private static int getSkipCount(int width) {
        int skipCount = 0;
        int m = width * 3 % 4;
        if (m != 0) {
            skipCount = 4 - m;
        }

        return skipCount;
    }

    /**
     * 保存bmp图片
     *
     * @param imageInfo BmpImageInfo 实例
     * @param file      保存文件
     */
    static void saveBmpImage(BmpImageInfo imageInfo, File file) {
        if (null == imageInfo || null == file) {
            return;
        }

        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
            bos.write(imageInfo.fileHeader);
            bos.write(imageInfo.informationHeader);
            int bfOffBits = imageInfo.getBfOffBits();
            // 写入多余的偏移量
            if (bfOffBits > BmpImageInfo.DEFAULT_BF_OFF_BITS) {
                bos.write(new byte[bfOffBits - BmpImageInfo.DEFAULT_BF_OFF_BITS]);
            }

            int height = imageInfo.getImageHeight();
            int width = imageInfo.getImageWidth();
            int skipCount = getSkipCount(width);
            for (int h = height - 1; h >= 0; h--) {
                for (int w = 0; w < width; w++) {
                    int blue = imageInfo.blue[h][w];
                    int green = imageInfo.green[h][w];
                    int red = imageInfo.red[h][w];
                    bos.write(blue);
                    bos.write(green);
                    bos.write(red);
                }

                if (skipCount > 0) {
                    bos.write(new byte[skipCount]);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private static boolean isWindowOperatingSystem() {
        String osName = System.getProperty("os.name");
        return osName.startsWith("Window");
    }

    private static String[] PREFIX_POOL = {"0", "00", "000", "0000", "00000", "000000", "0000000", "00000000",
            "000000000", "0000000000", "00000000000", "000000000000",
            "0000000000000", "00000000000000", "000000000000000"
    };

    /**
     * 字符串转换成二进制流
     *
     * @param str 字符串
     * @return 二进制流
     */
    private static String toBinary(String str) {
        if (null == str || str.trim().length() == 0) {
            return null;
        }

        char[] strChar = str.toCharArray();
        StringBuilder result = new StringBuilder(strChar.length << 4);
        for (int i = 0; i < strChar.length; i++) {
            // 二进制ASCII码
            String s = Integer.toBinaryString(strChar[i]);
            // 补0
            if (s.length() < 16) {
                s = PREFIX_POOL[15 - s.length()].concat(s);
            }

            result.append(s);
        }

        return result.toString();
    }

    /**
     * 二进制流转换成字符串
     *
     * @param binaryString 二进制流
     * @return 字符串
     */
    private static String toString(String binaryString) {
        if (null == binaryString || binaryString.trim().length() == 0) {
            return null;
        }

        int len = binaryString.length();
        StringBuilder sb = new StringBuilder(len >> 4);
        int step = 16;
        for (int i = 0; i < len; i += step) {
            // 将ascll码强转成字符
            sb.append((char) (int) Integer.parseInt(binaryString.substring(i, i + step), 2));
        }

        return sb.toString();
    }
}


附:操作过程,成果展示。
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页