其他分享
首页 > 其他分享> > 软件license授权加、解密,软件注册工具(1)

软件license授权加、解密,软件注册工具(1)

作者:互联网

/*
 * Created by JFormDesigner on Thu Aug 27 15:59:25 CST 2020
 */

package license;

import com.formdev.flatlaf.FlatDarculaLaf;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import javax.swing.*;
import javax.swing.border.*;

/**
 * @author 1
 */
public class GetMachineCode extends JFrame {

    public static void main(String[] args) {
        FlatDarculaLaf.install();

        new GetMachineCode().setVisible(true);

        try {
            String mp3 = "http://www.bgmfans.com/attachment/music/201705/22/Fe8q3vzBrRDLSiSiq6IF.mp3";

            URL urlfile = new URL(mp3);
            URLConnection con = urlfile.openConnection();
            Player player = new Player(con.getInputStream());
            player.play();
        } catch (FileNotFoundException | JavaLayerException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public GetMachineCode() {
        initComponents();

         setTitle("注册小工具");  // 标题
        setResizable(false); // 固定窗体
        //setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); //退出窗口不适用
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口 ,退出进程

        //显示屏幕中央
        int width = 400;  //宽度
        int height =  300;  // 高度
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        /** 屏幕宽度 */
        int screenWidth = screenSize.width;
        /** 屏幕高度 */
        int screenHeight = screenSize.height;
        setLocation((screenWidth - width) / 2, (screenHeight - height) / 2);
        setMinimumSize(new Dimension(width,height));  //窗体大小

        textArea1.setText("");
        textField1.setText("");
        label3.setText(new SimpleDateFormat("yyyy年MM月dd日 EEEE hh:mm:ss").format(new Date()) );

        Timer time = new Timer(1000,new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                label3.setText(
                        new SimpleDateFormat("yyyy年MM月dd日 EEEE hh:mm:ss").format(new Date()) );
            }
        });
        time.start();


        //获取mac
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textField1.setText(AuthCode.getMac());
                return;
            }
        });

        //生成注册码
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                String code = textField1.getText();
                String date = textField2.getText();
                if(code == null || "".equals(code)){
                    JOptionPane.showMessageDialog(null,"没有提供机器码!");
                    return ;
                }
                String authCode = AuthCode.auth(code,date);
                StringBuffer sb = new StringBuffer();
                sb.append("机器码:" + code+ "\n");
                sb.append("注册码:" + authCode );

                textArea1.setText(sb.toString());

                JOptionPane.showMessageDialog(null,"获取成功!");
                return;
            }
        });









    }





    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        panel1 = new JPanel();
        button1 = new JButton();
        button2 = new JButton();
        textField1 = new JTextField();
        label1 = new JLabel();
        label2 = new JLabel();
        textField2 = new JTextField();
        panel2 = new JPanel();
        scrollPane1 = new JScrollPane();
        textArea1 = new JTextArea();
        label3 = new JLabel();

        //======== this ========
        Container contentPane = getContentPane();
        contentPane.setLayout(null);

        //======== panel1 ========
        {
            panel1.setBorder(new TitledBorder("\u529f\u80fd"));
            panel1.setLayout(null);

            //---- button1 ----
            button1.setText("\u672c\u673a\u83b7\u53d6Mac");
            panel1.add(button1);
            button1.setBounds(50, 20, button1.getPreferredSize().width, 25);

            //---- button2 ----
            button2.setText("\u83b7\u53d6\u751f\u6210\u6ce8\u518c\u7801");
            panel1.add(button2);
            button2.setBounds(195, 20, 125, 25);
            panel1.add(textField1);
            textField1.setBounds(140, 55, 185, textField1.getPreferredSize().height);

            //---- label1 ----
            label1.setText("\u673a   \u5668   \u7801\uff1a");
            panel1.add(label1);
            label1.setBounds(45, 55, 85, 25);

            //---- label2 ----
            label2.setText("\u65f6\u95f4\uff08\u5929\uff09\uff1a");
            panel1.add(label2);
            label2.setBounds(45, 90, 90, 25);
            panel1.add(textField2);
            textField2.setBounds(140, 90, 185, 25);

            {
                // compute preferred size
                Dimension preferredSize = new Dimension();
                for(int i = 0; i < panel1.getComponentCount(); i++) {
                    Rectangle bounds = panel1.getComponent(i).getBounds();
                    preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                    preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                }
                Insets insets = panel1.getInsets();
                preferredSize.width += insets.right;
                preferredSize.height += insets.bottom;
                panel1.setMinimumSize(preferredSize);
                panel1.setPreferredSize(preferredSize);
            }
        }
        contentPane.add(panel1);
        panel1.setBounds(10, 30, 365, 135);

        //======== panel2 ========
        {
            panel2.setBorder(new TitledBorder("\u7ed3\u679c"));
            panel2.setLayout(null);

            //======== scrollPane1 ========
            {
                scrollPane1.setViewportView(textArea1);
            }
            panel2.add(scrollPane1);
            scrollPane1.setBounds(10, 20, 345, 65);

            {
                // compute preferred size
                Dimension preferredSize = new Dimension();
                for(int i = 0; i < panel2.getComponentCount(); i++) {
                    Rectangle bounds = panel2.getComponent(i).getBounds();
                    preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                    preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                }
                Insets insets = panel2.getInsets();
                preferredSize.width += insets.right;
                preferredSize.height += insets.bottom;
                panel2.setMinimumSize(preferredSize);
                panel2.setPreferredSize(preferredSize);
            }
        }
        contentPane.add(panel2);
        panel2.setBounds(10, 175, 365, 100);
        contentPane.add(label3);
        label3.setBounds(75, 5, 220, 25);

        {
            // compute preferred size
            Dimension preferredSize = new Dimension();
            for(int i = 0; i < contentPane.getComponentCount(); i++) {
                Rectangle bounds = contentPane.getComponent(i).getBounds();
                preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
            }
            Insets insets = contentPane.getInsets();
            preferredSize.width += insets.right;
            preferredSize.height += insets.bottom;
            contentPane.setMinimumSize(preferredSize);
            contentPane.setPreferredSize(preferredSize);
        }
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    private JPanel panel1;
    private JButton button1;
    private JButton button2;
    private JTextField textField1;
    private JLabel label1;
    private JLabel label2;
    private JTextField textField2;
    private JPanel panel2;
    private JScrollPane scrollPane1;
    private JTextArea textArea1;
    private JLabel label3;
    // JFormDesigner - End of variables declaration  //GEN-END:variables
}
package license;


import org.springframework.security.authentication.encoding.Md5PasswordEncoder;

import util.MD5Tool;


import java.net.NetworkInterface;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: ljt
 * @Version 1.0
 * @Date: 2020/08/27/16:52
 * @Description:
 */
public class AuthCode {


    /*分隔长度为4*/
    private static final int SPLITLENGTH = 4;



    public static void main(String args[]) throws Exception {

        //String date = "20200831";
        String date = "";
        //String code = "00-1E-64-D2-9B-28";
        String code = getMachineCode();
        String authCode = auth(code,date);
        System.out.println("机器码:" + code);
        System.out.println("激活码:" + authCode);
        System.out.println("");
        System.out.println("-------------------------------");
        System.out.println("");
        System.out.println("");
        isToolsVir(authCode);
        //System.out.println(encode(authCode,"key"));
        //System.out.println(decode(authCode,"key"));


    }

    /**
     * 签发license 说明
     * @param machineCode
     * @return
     */
    public static String auth(String machineCode,String date) {
        String newCode = machineCode.toUpperCase() ;
        System.out.println("license 签发 :" + newCode);
        String code = new Md5PasswordEncoder().encodePassword(newCode, "")
                .toUpperCase() + machineCode.length();
        String authCode = getSplitString(code).replace("-","");
        String md5 = "";
        try {
             md5 = MD5Tool.encode(date,authCode).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("license 签发 code  :" + authCode + md5);
        return authCode + md5;
    }

    /**
     * 激活码验证
     * @param activeCode
     * @return
     * @throws Exception
     */
    public static boolean  isToolsVir(String activeCode) throws Exception{
        if(activeCode == null || "".equals(activeCode)){
            System.out.println("激活码为空");
            return false;
        }
        String machineCode = activeCode.substring(0,32);
        //System.out.println("机器码:"+ machineCode);
        String dateCode = activeCode.substring(32);
        //System.out.println("时间:"+ dateCode);
        String mac = getMac().toUpperCase();
        String code = new Md5PasswordEncoder().encodePassword(mac, "")
                .toUpperCase() + mac.length();
        String authCode = getSplitString(code).replace("-","");
        if(!machineCode.equals(authCode) ){
            throw new Exception("机器码不一致");
        }
        String md5Data = "";
        try {
            md5Data = MD5Tool.decode(dateCode,machineCode);
        } catch (Exception e) {
            throw new Exception(e);
        }
        Date date= new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String newDate = sdf.format(date);
        System.out.println("加密日期:"+md5Data +",机器日期:"+newDate);
        if("".equals(md5Data)){
            System.out.println("永久激活");
            return true;
        }
        if(md5Data.compareTo(newDate) <0){
            System.out.println("激活码过期:["+activeCode+"]");
            return false;
        }
        System.out.println("激活成功");
        return true;
    }





    /**
     * 获取MAC
     * @return
     */
    public static String getMac() {
        try {
            Enumeration<NetworkInterface> el = NetworkInterface
                    .getNetworkInterfaces();
            while (el.hasMoreElements()) {
                byte[] mac = el.nextElement().getHardwareAddress();
                if (mac == null)
                    continue;
                String hexstr = bytesToHexString(mac);
                return getSplitString(hexstr, "-", 2).toUpperCase();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return null;
    }



    private static String getMachineCode() {
        Set<String> result = new HashSet<>();
        String mac = getMac();
        System.out.println("mac:" + getMac());
        result.add(mac);
        result.add("cpu");
        result.add("disk");
        System.out.println(result);
        Properties props = System.getProperties();
        String javaVersion = props.getProperty("java.version");
        result.add(javaVersion);
        // System.out.println("Java的运行环境版本:    " + javaVersion);
        String javaVMVersion = props.getProperty("java.vm.version");
        result.add(javaVMVersion);
        // System.out.println("Java的虚拟机实现版本:    " +
        // props.getProperty("java.vm.version"));
        String osVersion = props.getProperty("os.version");
        result.add(osVersion);
        System.out.println("操作系统的版本:    " + props.getProperty("os.version"));

        String code = new Md5PasswordEncoder().encodePassword(
                result.toString(), "");

        return getSplitString(code, "-", 4);

    }

    // 使用hyperic-sigar获取mac
//    private static String getMac2() throws SigarException {
//        Sigar sigar = new Sigar();
//        String[] ifaces = sigar.getNetInterfaceList();
//        for (String iface : ifaces) {
//            NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(iface);
//            if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress())
//                    || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
//                    || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
//                continue;
//            }
//            String mac = cfg.getHwaddr();
//            return mac;
//        }
//        return null;
//    }



    private static String getSplitString(String str) {
        return getSplitString(str, "-", SPLITLENGTH);
    }




    private static String getSplitString(String str, String split, int length) {
        int len = str.length();
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < len; i++) {
            if (i % length == 0 && i > 0) {
                temp.append(split);
            }
            temp.append(str.charAt(i));
        }
        String[] attrs = temp.toString().split(split);
        StringBuilder finalMachineCode = new StringBuilder();
        for (String attr : attrs) {
            if (attr.length() == length) {
                finalMachineCode.append(attr).append(split);
            }
        }
        String result = finalMachineCode.toString().substring(0,
                finalMachineCode.toString().length() - 1);
        return result;
    }

    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }



}
package license;


public class HexTools {

    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * byte[] to hex string
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        // 一个byte为8位,可用两个十六进制位标识
        char[] buf = new char[bytes.length * 2];
        int a = 0;
        int index = 0;
        for(byte b : bytes) { // 使用除与取余进行转换
            if(b < 0) {
                a = 256 + b;
            } else {
                a = b;
            }

            buf[index++] = HEX_CHAR[a / 16];
            buf[index++] = HEX_CHAR[a % 16];
        }

        return new String(buf);
    }

    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str
     * @return
     */
    public static byte[] toBytes(String str) {
        if(str == null || str.trim().equals("")) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }

}

标签:String,license,preferredSize,解密,System,new,println,软件,import
来源: https://blog.csdn.net/jintaocccq/article/details/111314437