欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

利用Preferences对软件进行加密

程序员文章站 2022-07-13 13:36:07
...

利用Preferences对软件进行加密

1.思路流程图
利用Preferences对软件进行加密
2.加密工具类DesUtil

package bing;

import java.io.IOException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * DES加密 解密算法
 * 
 * 
 */
public class DesUtil {

	private final static String DES = "DES";
	private final static String ENCODE = "GBK";
	public static String defaultKey = "eqweqwe-dtd*asd+gjljaslk";//自定义的秘钥

	/**
	 * 使用 默认key 加密
	 * 
	 * @param data
	 *            待加密数据
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String data) throws Exception {
		byte[] bt = encrypt(data.getBytes(ENCODE), defaultKey.getBytes(ENCODE));
		String strs = new BASE64Encoder().encode(bt);
		return strs;
	}

	/**
	 * 使用 默认key 解密
	 * 
	 * @param data
	 *            待解密数据
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static String decrypt(String data) throws IOException, Exception {
		if (data == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] buf = decoder.decodeBuffer(data);
		byte[] bt = decrypt(buf, defaultKey.getBytes(ENCODE));
		return new String(bt, ENCODE);
	}

	/**
	 * Description 根据键值进行加密
	 * 
	 * @param data
	 *            待加密数据
	 * @param key
	 *            **
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String data, String key) throws Exception {
		byte[] bt = encrypt(data.getBytes(ENCODE), key.getBytes(ENCODE));
		String strs = new BASE64Encoder().encode(bt);
		return strs;
	}

	/**
	 * 根据键值进行解密
	 * 
	 * @param data
	 *            待解密数据
	 * @param key
	 *            **
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static String decrypt(String data, String key) throws IOException,
			Exception {
		if (data == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] buf = decoder.decodeBuffer(data);
		byte[] bt = decrypt(buf, key.getBytes(ENCODE));
		return new String(bt, ENCODE);
	}

	/**
	 * Description 根据键值进行加密
	 * 
	 * @param data
	 * @param key
	 *            加密键byte数组
	 * @return
	 * @throws Exception
	 */
	private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
		// 生成一个可信任的随机数源
		SecureRandom sr = new SecureRandom();

		// 从原始**数据创建DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key);

		// 创建一个**工厂,然后用它把DESKeySpec转换成SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);

		// Cipher对象实际完成加密操作
		Cipher cipher = Cipher.getInstance(DES);

		// 用**初始化Cipher对象
		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

		return cipher.doFinal(data);
	}

	/**
	 * Description 根据键值进行解密
	 * 
	 * @param data
	 * @param key
	 *            加密键byte数组
	 * @return
	 * @throws Exception
	 */
	private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
		// 生成一个可信任的随机数源
		SecureRandom sr = new SecureRandom();

		// 从原始**数据创建DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key);

		// 创建一个**工厂,然后用它把DESKeySpec转换成SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);

		// Cipher对象实际完成解密操作
		Cipher cipher = Cipher.getInstance(DES);

		// 用**初始化Cipher对象
		cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

		return cipher.doFinal(data);
	}
}

3.程序启动Main方法

package bing;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.prefs.Preferences;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Main {
	
	 Preferences pref = Preferences.userRoot().node(this.getClass().getName());//获取一个Preference对象
	 String benjizhucema = pref.get("serialnumber", "");//获取本机的***
	 int count = pref.getInt("count", 1);//计数,用来更新序列码
	 String zhuceDate= pref.get("datea", "1970-12-10 09:53:56");//初始化注册时间
	 Date date=new Date();
	 	
	public void zhucePanel(String serialnumber ){//注册面板
		
		final String s=serialnumber;//本机的注册***
		final JFrame jf=new JFrame();
		JButton sure=new JButton("注册");
		JTextField xuliema=new JTextField(s);
		xuliema.setEditable(false);
		JLabel shuoming =new JLabel("请输入***:");
		final JTextField zhucema=new JTextField(30);
		FlowLayout left=new FlowLayout(FlowLayout.LEFT);
		FlowLayout center=new FlowLayout(FlowLayout.CENTER);
		JPanel northp=new JPanel(center);
		JPanel centerp=new JPanel();
		JPanel leftp=new JPanel();
		JPanel rightp=new JPanel();
		JPanel south=new JPanel(center);
		JPanel center1=new JPanel(left);
		JPanel center2=new JPanel(center);
		northp.add(xuliema);
		centerp.setLayout(new GridLayout(2, 1));
		center1.add(shuoming);
		center2.add(zhucema);
		centerp.add(center1);
		centerp.add(center2);
		south.add(sure);
		jf.add(northp,BorderLayout.NORTH);
		jf.add(leftp,BorderLayout.WEST);
		jf.add(rightp,BorderLayout.EAST);
		jf.add(centerp,BorderLayout.CENTER);
		jf.add(south,BorderLayout.SOUTH);
	
		jf.setSize(400, 180);
		Dimension displaySize = Toolkit.getDefaultToolkit().getScreenSize(); // 获得显示器大小对象  
		Dimension frameSize = jf.getSize();             // 获得窗口大小对象  
		jf.setLocation((displaySize.width - frameSize.width) / 2,  (displaySize.height - frameSize.height) / 2); 
		jf.setResizable(false);
		jf.setVisible(true);
		jf.setTitle("用户注册");
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		sure.addActionListener(new ActionListener() {//注册按钮的单击事件
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				String benjizhucema=zhucema.getText();//输入框填写的***
				System.out.println(benjizhucema);
				String rightzhucema=null;
				try {
					rightzhucema=DesUtil.encrypt(s, DesUtil.defaultKey);//通过传入的本机***和自定义的秘钥,生成正确的***
					System.out.println(rightzhucema);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				if(benjizhucema.equals(rightzhucema)){//判断填写的***是否和正确的***一致,如果一致把本机的***更改为正确的***,如果不一致弹出注册失败
					JOptionPane.showMessageDialog(null, "恭喜你注册成功!","提示",1);
					pref.put("serialnumber", rightzhucema);					
					Date date4=new Date();
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
					pref.put("datea", df.format(date4));	//添加注册日期				
					new Form();//跳转到程序界面
					jf.setVisible(false);//注册框消失
					
				}else{
					JOptionPane.showMessageDialog(null, "***有误!请重新输入!","提示",1);
					
				}
				
			}
		});
		
	}

	public  boolean zhuce(String serialnumber){
		//pref.put("serialnumber", "");

		String rigthzhucema = null;
		try {
			rigthzhucema=DesUtil.encrypt(serialnumber, DesUtil.defaultKey);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		if (benjizhucema.equals(rigthzhucema)) {
			return true;
		} 	
		
		return false;
	}
	
	
	
	
	//获取本机序列码
	public String getSerialNumber(){
		Process process = null;
		try {
			process = Runtime.getRuntime()
					.exec(new String[] { "wmic", "diskdrive", "get",
							"serialnumber" });
			process.getOutputStream().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Scanner sc = new Scanner(process.getInputStream());
		String property = sc.next();
		String serial = sc.next();
		
		return ""+pref.getInt("count", 1)+serial;
	}
	
	//日期比较方法
	public void compareTime(Date now){
		long time =15552000000l;
		int tian=(int) (time/1000/60/60/24);
		//System.out.println("--注册天数--"+tian);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date zhuce=null;       
        try {
			zhuce = sdf.parse(zhuceDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       //System.out.println("--当前时间--"+sdf.format(now));
       //System.out.println("--注册时间--"+sdf.format(zhuce));
        
        long time1 = now.getTime();
        long time2 = zhuce.getTime();
        long time3 = time1-time2;
        
        if(time3>=time){
        	//System.out.println(time3);
        	pref.putInt("count", count+1);
        }
	}
	//主函数
	public static void main(String[] args) {	
		Main m=new Main();
		Date now=new Date();//当前日期
		m.compareTime(now);//对比当前时间	减去注册时间是否大于预设的可用日期,如果大于,计数的count+1,不大于则不变
		String s=m.getSerialNumber();//获取***(注:序列码由“count”和硬盘***组成)
		//System.out.println("--序列码--"+s);	
		boolean b=m.zhuce(s);//传入***,判断本机Preference写入的***是否为正确的***,如果正确,跳转软件界面,否则打开注册面板
		if(b){
			new Form();
		}else{
			m.zhucePanel(s);
		}	
	}
}



相关标签: java 加密解密