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

package qr;


/*
 * Created by JFormDesigner on Wed Aug 26 13:36:16 CST 2020
 */



import com.formdev.flatlaf.FlatDarculaLaf;
import qr.GoogleBarCodeUtils;
import qr.QRCode;
import qr.QrCodeShow;
import sdk.CheckActiveCode;
import util.ExcelUtil;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

/**
 * @author 1
 */
public class CodeTest extends JFrame {
    private static final  String codePath = System.getProperty("user.home") + "/.activeCode.code";

    public void test1(){

    }
    public static void main(String[] args) {
        //System.out.println(System.getProperty("user.home"));
        //FlatLightLaf.install();
        //FlatDarkLaf.install();
        //FlatIntelliJLaf.install();
        FlatDarculaLaf.install();
        System.out.println(codePath);
        File f = new File(codePath);
        if(!f.exists()){
            String value = JOptionPane.showInputDialog("请输入激活码~");
            value(value);
            try {
                writeFile(value);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                String value = readerFile();
                value(value);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        new CodeTest().setVisible(true);;
    }
    public CodeTest() {
        initComponents();


        setTitle("二维码批量生成器");  // 标题
        //setTitle("二维码批量生成器!   ----- 作者:超级大蚂蚁         联系QQ:894411856");  // 标题
        setResizable(false); // 固定窗体
        //setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); //退出窗口不适用
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口 ,退出进程

        //显示屏幕中央
        int width = 720;  //宽度
        int height =  535;  // 高度
        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));  //窗体大小



        radioButton1.setSelected(true);
        textField1.setText("1");
        textField2.setEditable(false);
        textField3.setEditable(false);
        label6.setEnabled(false);
        label7.setEnabled(false);
        textField4.setText("300");
        textField5.setText("300");



        //二维码
        radioButton1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                radioButton1.setSelected(true);
                radioButton2.setSelected(false);
                button3.setEnabled(true);
                label6.setText("");
                //二维码尺寸
                label9.setEnabled(true);
                label10.setEnabled(true);
                label11.setEnabled(true);
                textField4.setEnabled(true);
                textField5.setEnabled(true);
                textArea1.addFocusListener(new FocusListener() {
                    @Override
                    public void focusGained(FocusEvent e) {
                        textArea1.setText("");
                    }
                    @Override
                    public void focusLost(FocusEvent e) {
                        textArea1.setText("内容");
                        textArea1.setForeground(new Color(128, 128, 128));
                    }
                });

            }
        });

        //条形码
        radioButton2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                radioButton1.setSelected(false);
                radioButton2.setSelected(true);
                button3.setEnabled(false);
                textArea1.setText("");
                textField2.setText("");
                textField3.setText("");
                label5.setIcon(new ImageIcon());
                label6.setText("");
                //二维码尺寸
                label9.setEnabled(false);
                label10.setEnabled(false);
                label11.setEnabled(false);
                textField4.setEnabled(false);
                textField5.setEnabled(false);
                textArea1.addFocusListener(new FocusListener() {
                    @Override
                    public void focusGained(FocusEvent e) {
                        textArea1.setText("");
                    }
                    @Override
                    public void focusLost(FocusEvent e) {
                        //textArea1.setText("内容");
                        textArea1.setForeground(new Color(128, 128, 128));
                    }
                });

            }
        });


        //生成二维码按钮
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                String context = textArea1.getText();
                String execlPth = label7.getText();


                if((context == null || "".equals(context)) &&
                        (execlPth == null || "".equals(execlPth))){
                    JOptionPane.showMessageDialog(null,"内容不能为空!");
                    return;
                }


                //二维码
                if(radioButton1.isSelected()){

                    //数量
                    String countNum = textField1.getText();
                    if(countNum == null || "".equals(countNum)){
                        JOptionPane.showMessageDialog(null,"数量不能为空!");
                        return;
                    }
                    int w = Integer.valueOf(textField4.getText());
                    int h = Integer.valueOf(textField5.getText());
                    if(w ==0 || h ==0){
                        JOptionPane.showMessageDialog(null,"二维码尺寸不正常!");
                        return;
                    }
                    int len = context.length();
                    if(len > 3000 ){
                        JOptionPane.showMessageDialog(null,"内容不能超过3000个长度!");
                        return;
                    }
                    if(len >1000 && (w <=300 || h <=300)){
                        JOptionPane.showMessageDialog(null,"内容长度大于1000,二维码尺寸设置大一点!");
                        return;
                    }

                    //保存路径
                    String path = textField2.getText();
                    if(path == null || "".equals(path)){
                        JOptionPane.showMessageDialog(null,"保存路径不能为空!");
                        return;
                    }
                    //图片路径
                    String imgPath  = textField3.getText();
                    int count = Integer.valueOf(countNum);
                    if(execlPth != null && !"".equals(execlPth)){
                        String fileName = execlQrcode(w,h,execlPth,path,imgPath);
                        String showPath = "file:///"+ path+"/"+fileName;
                        label6.setText(showPath);
                        System.out.println(showPath);
                    }else{
                        for(int i=0; i<count ; i++){
                            try {
                                String fileName = QRCode.encode(context,w,h, imgPath, path, true,false);
                                String showPath = "file:///"+ path+"/"+fileName;
                                label6.setText(showPath);
                                System.out.println(showPath);

                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }

                }


                //条形码
                if(radioButton2.isSelected()){

                    String pattern = "[\u4e00-\u9fa5]+";


                    // 内容
                    if (context.length() > 100){
                        JOptionPane.showMessageDialog(null,"内容长度超过100个字符!");
                        return ;
                    }
                    for(int i=0; i<context.length() ; i++){
                        String str = context.charAt(i)+"";
                        boolean isMatch =  Pattern.matches(pattern,str);
                        if(isMatch){
                            JOptionPane.showMessageDialog(null,"内容不能存在中文!");
                            return ;
                        }
                    }

                    //数量
                    String countNum = textField1.getText();
                    if(countNum == null || "".equals(countNum)){
                        JOptionPane.showMessageDialog(null,"数量不能为空!");
                        return;
                    }
                    //保存路径
                    String path = textField2.getText();
                    if(path == null || "".equals(path)){
                        JOptionPane.showMessageDialog(null,"保存路径不能为空!");
                        return;
                    }

                    int count = Integer.valueOf(countNum);
                    for(int i=0; i<count ; i++){
                        try {
                            BufferedImage image = GoogleBarCodeUtils.insertWords(
                                    GoogleBarCodeUtils.getBarCode(context), context);
                            String file = new Random().nextInt(99999999)+".jpg";
                            ImageIO.write(image, "jpg", new File(path +"/"+file));
                            String showPath = "file:///"+ path+"/"+file;
                            label6.setText(showPath);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }


                }


                JOptionPane.showMessageDialog(null,"生成完成!");
            }
        });

        //预览
        button4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(label6.getText() == null || "".equals(label6.getText())){
                    JOptionPane.showMessageDialog(null,"二维码、条形码未生成!");
                    return;
                }
                String title = "";
                if(radioButton1.isSelected()){
                    title = "二维码";
                }
                if(radioButton2.isSelected()){
                    title = "条形码";
                }
                int w = Integer.valueOf(textField4.getText());
                int h = Integer.valueOf(textField5.getText());
                System.out.println("预览:"+label6.getText());
                new QrCodeShow(label6.getText(),title,w+30 ,h+30).setVisible(true);
            }
        });




        //保存路径
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        JFileChooser fileChooser = new JFileChooser();
                        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                        int option = fileChooser.showOpenDialog(getContentPane());
                        if (option == JFileChooser.APPROVE_OPTION) {
                            File file = fileChooser.getSelectedFile();
                            textField2.setText(file.getPath());
                            //System.out.println("选择文件或目录: " + file.getPath());
                        }
                    }
                };
                SwingUtilities.invokeLater(runnable);
            }
        });

        //选择文件路径
        button3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        JFileChooser fileChooser = new JFileChooser();
                        FileNameExtensionFilter filter = new FileNameExtensionFilter ("*.jpg,*.gif,*.png,*.jpeg", "jpg", "gif", "png", "jpeg");
                        fileChooser.setFileFilter(filter);
                        int option = fileChooser.showOpenDialog(getContentPane());
                        if (option == JFileChooser.APPROVE_OPTION) {
                            File file = fileChooser.getSelectedFile();
                            String path = file.getPath();
                            textField3.setText(path);

                            Icon icon = null;
                            try {
                                icon = new ImageIcon(new URL("file:///"+ path));
                                //icon = new ImageIcon(new URL("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg"));
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            }
                            label5.setIcon(icon);
                        }
                    }
                };
                SwingUtilities.invokeLater(runnable);
            }
        });


        //选择excel文件路径
        button5.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        JFileChooser fileChooser = new JFileChooser();
                        FileNameExtensionFilter filter = new FileNameExtensionFilter ("*.xls,*.xlsx", "xls", "xlsx");
                        fileChooser.setFileFilter(filter);
                        int option = fileChooser.showOpenDialog(getContentPane());
                        if (option == JFileChooser.APPROVE_OPTION) {
                            File file = fileChooser.getSelectedFile();
                            String path = file.getPath();
                            label7.setText(path);
                        }
                    }
                };
                SwingUtilities.invokeLater(runnable);
            }
        });

        //选择excel文件路径
        button6.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textArea1.setText("");
                radioButton1.setSelected(true);
                textField1.setText("1");
                textField2.setText("");
                textField3.setText("");
                label5.setIcon(null);
                label6.setText("");
                label7.setText("");
            }
        });

    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        panel1 = new JPanel();
        radioButton1 = new JRadioButton();
        radioButton2 = new JRadioButton();
        label1 = new JLabel();
        label2 = new JLabel();
        textField1 = new JTextField();
        label3 = new JLabel();
        textField2 = new JTextField();
        button2 = new JButton();
        label4 = new JLabel();
        textField3 = new JTextField();
        button3 = new JButton();
        panel2 = new JPanel();
        label5 = new JLabel();
        label6 = new JLabel();
        label7 = new JLabel();
        label9 = new JLabel();
        textField4 = new JTextField();
        label10 = new JLabel();
        label11 = new JLabel();
        textField5 = new JTextField();
        button1 = new JButton();
        panel3 = new JPanel();
        scrollPane1 = new JScrollPane();
        textArea1 = new JTextArea();
        label8 = new JLabel();
        button4 = new JButton();
        button5 = new JButton();
        button6 = new JButton();

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

        //======== panel1 ========
        {
            panel1.setBorder(new TitledBorder("\u751f\u6210\u914d\u7f6e"));
            panel1.setLayout(null);

            //---- radioButton1 ----
            radioButton1.setText("\u4e8c\u7ef4\u7801");
            panel1.add(radioButton1);
            radioButton1.setBounds(150, 35, 80, 25);

            //---- radioButton2 ----
            radioButton2.setText("\u6761\u5f62\u7801");
            panel1.add(radioButton2);
            radioButton2.setBounds(235, 35, 100, 25);

            //---- label1 ----
            label1.setText("\u7c7b\u578b\uff1a");
            panel1.add(label1);
            label1.setBounds(new Rectangle(new Point(95, 40), label1.getPreferredSize()));

            //---- label2 ----
            label2.setText("\u6570\u91cf\uff1a");
            panel1.add(label2);
            label2.setBounds(95, 80, 45, 20);
            panel1.add(textField1);
            textField1.setBounds(150, 75, 180, 25);

            //---- label3 ----
            label3.setText("\u4fdd\u5b58\u8def\u5f84\uff1a");
            panel1.add(label3);
            label3.setBounds(70, 120, 85, 20);
            panel1.add(textField2);
            textField2.setBounds(150, 115, 380, 25);

            //---- button2 ----
            button2.setText("\u9009\u62e9");
            panel1.add(button2);
            button2.setBounds(565, 115, 100, button2.getPreferredSize().height);

            //---- label4 ----
            label4.setText("\u4e8c\u7ef4\u7801Logo\uff1a");
            panel1.add(label4);
            label4.setBounds(55, 160, 85, 25);
            panel1.add(textField3);
            textField3.setBounds(150, 160, 380, 25);

            //---- button3 ----
            button3.setText("\u9009\u62e9Logo");
            panel1.add(button3);
            button3.setBounds(565, 160, 100, 24);

            //======== panel2 ========
            {
                panel2.setBorder(new TitledBorder("\u56fe\u7247"));
                panel2.setLayout(null);
                panel2.add(label5);
                label5.setBounds(30, 25, 140, 100);

                {
                    // 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);
                }
            }
            panel1.add(panel2);
            panel2.setBounds(150, 190, 200, 140);
            panel1.add(label6);
            label6.setBounds(new Rectangle(new Point(370, 35), label6.getPreferredSize()));
            panel1.add(label7);
            label7.setBounds(0, 335, 0, 0);

            //---- label9 ----
            label9.setText("\u4e8c\u7ef4\u7801\u5c3a\u5bf8\uff1a");
            panel1.add(label9);
            label9.setBounds(345, 75, 80, 25);
            panel1.add(textField4);
            textField4.setBounds(435, 75, 45, 25);

            //---- label10 ----
            label10.setText("\u5bbd");
            panel1.add(label10);
            label10.setBounds(420, 75, 25, 25);

            //---- label11 ----
            label11.setText("  X  \u9ad8");
            panel1.add(label11);
            label11.setBounds(480, 75, 40, 25);
            panel1.add(textField5);
            textField5.setBounds(520, 75, 45, 25);

            //---- button1 ----
            button1.setText("\u751f\u6210");
            panel1.add(button1);
            button1.setBounds(565, 30, 100, button1.getPreferredSize().height);

            {
                // 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, 160, 695, 340);

        //======== panel3 ========
        {
            panel3.setBorder(new TitledBorder("\u5185\u5bb9"));
            panel3.setLayout(null);

            //======== scrollPane1 ========
            {
                scrollPane1.setViewportView(textArea1);
            }
            panel3.add(scrollPane1);
            scrollPane1.setBounds(30, 35, 505, 100);

            //---- label8 ----
            label8.setText("* \u5907\u6ce8\uff1a\u5982\u5bfc\u5165Excel\u751f\u6210\u65f6\uff0c\u5185\u5bb9\u6587\u672c\u6846\u91cc\u7684\u503c\u8981\u4e3a\u7a7a\uff0cExcel\u53ea\u53d6\u201cA\u201d\u5217\u7684\u503c");
            label8.setForeground(Color.red);
            panel3.add(label8);
            label8.setBounds(30, 15, 515, label8.getPreferredSize().height);

            {
                // compute preferred size
                Dimension preferredSize = new Dimension();
                for(int i = 0; i < panel3.getComponentCount(); i++) {
                    Rectangle bounds = panel3.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 = panel3.getInsets();
                preferredSize.width += insets.right;
                preferredSize.height += insets.bottom;
                panel3.setMinimumSize(preferredSize);
                panel3.setPreferredSize(preferredSize);
            }
        }
        contentPane.add(panel3);
        panel3.setBounds(10, 10, 565, 150);

        //---- button4 ----
        button4.setText("\u9884\u89c8");
        contentPane.add(button4);
        button4.setBounds(600, 60, 100, button4.getPreferredSize().height);

        //---- button5 ----
        button5.setText("\u5bfcExcel");
        contentPane.add(button5);
        button5.setBounds(600, 20, 100, 24);

        //---- button6 ----
        button6.setText("\u91cd\u7f6e");
        contentPane.add(button6);
        button6.setBounds(600, 105, 100, 24);

        {
            // 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 JRadioButton radioButton1;
    private JRadioButton radioButton2;
    private JLabel label1;
    private JLabel label2;
    private JTextField textField1;
    private JLabel label3;
    private JTextField textField2;
    private JButton button2;
    private JLabel label4;
    private JTextField textField3;
    private JButton button3;
    private JPanel panel2;
    private JLabel label5;
    private JLabel label6;
    private JLabel label7;
    private JLabel label9;
    private JTextField textField4;
    private JLabel label10;
    private JLabel label11;
    private JTextField textField5;
    private JButton button1;
    private JPanel panel3;
    private JScrollPane scrollPane1;
    private JTextArea textArea1;
    private JLabel label8;
    private JButton button4;
    private JButton button5;
    private JButton button6;
    // JFormDesigner - End of variables declaration  //GEN-END:variables


    private static String execlQrcode( int w,int h,String excelPath,String savePath,String imagePath){
        java.util.List<java.util.List<String>> resultList = ExcelUtil.readExcel(excelPath);
        String fileName = "";
        if (resultList != null) {
            for (int i = 0; i < resultList.size(); i++) {
                List<String> cellList = resultList.get(i);
                String context = cellList.get(0);
                try {
                     fileName = QRCode.encode(context,w,h ,imagePath, savePath, true,true);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }

        }
        return fileName;
    }

    private static String readerFile() throws IOException {
        FileReader fileReader = new FileReader(new File(codePath));
        BufferedReader br=new BufferedReader(fileReader);
        String line=br.readLine();
        br.close();
        fileReader.close();
        return line;
    }
    private static void writeFile(String code) throws IOException {
        File file = new File(codePath);
        FileWriter fw=new FileWriter(file);
        BufferedWriter  bw=new BufferedWriter(fw);
        bw.write(code);
        bw.close();
        fw.close();
        String sets = "attrib +H \"" + file.getAbsolutePath() + "\"";
        // 运行命令串
        Runtime.getRuntime().exec(sets);
    }

    private static void value(String value){
        if (value == null || "".equals(value)){
            System.exit(0);
        }else{

            try {
                if(!CheckActiveCode.verifyCode(value)){
                    String code = JOptionPane.showInputDialog("激活码已过期,请输入新的激活码~");
                    value(code);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,"机器码不一致,无法激活");
                System.exit(0);
            }
        }
    }



}
package qr;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: ljt
 * @Version 1.0
 * @Date: 2020/08/26/16:14
 * @Description:
 */
public class GoogleBarCodeUtils {
    /** 条形码宽度 */
    private static final int WIDTH = 300;

    /** 条形码高度 */
    private static final int HEIGHT = 50;

    /** 加文字 条形码 */
    private static final int WORDHEIGHT = 75;
    /**
     * 设置 条形码参数
     */
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;
        {
            // 设置编码方式
            put(EncodeHintType.CHARACTER_SET, "utf-8");
        }
    };
    /**
     * 生成 图片缓冲
     * @author fxbin
     * @param vaNumber  VA 码
     * @return 返回BufferedImage
     */
    public static BufferedImage getBarCode(String vaNumber){
        try {
            Code128Writer writer = new Code128Writer();
            // 编码内容, 编码类型, 宽度, 高度, 设置参数
            BitMatrix bitMatrix = writer.encode(vaNumber, BarcodeFormat.CODE_128, WIDTH, HEIGHT, hints);
            return MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 把带logo的二维码下面加上文字
     * @author fxbin
     * @param image  条形码图片
     * @param words  文字
     * @return 返回BufferedImage
     */
    public static BufferedImage insertWords(BufferedImage image, String words){
        // 新的图片,把带logo的二维码下面加上文字
        if (words != null && !"".equals(words)) {

            BufferedImage outImage = new BufferedImage(WIDTH, WORDHEIGHT, BufferedImage.TYPE_INT_RGB);

            Graphics2D g2d = outImage.createGraphics();

            // 抗锯齿
            setGraphics2D(g2d);
            // 设置白色
            setColorWhite(g2d);

            // 画条形码到新的面板
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            Color color=new Color(0, 0, 0);
            g2d.setColor(color);
            // 字体、字型、字号
            g2d.setFont(new Font("微软雅黑", Font.PLAIN, 18));
            //文字长度
            int strWidth = g2d.getFontMetrics().stringWidth(words);
            //总长度减去文字长度的一半  (居中显示)
            int wordStartX=(WIDTH - strWidth) / 2;
            //height + (outImage.getHeight() - height) / 2 + 12
            int wordStartY=HEIGHT+20;

            // 画文字
            g2d.drawString(words, wordStartX, wordStartY);
            g2d.dispose();
            outImage.flush();
            return outImage;
        }
        return null;
    }

    /**
     * 设置 Graphics2D 属性  (抗锯齿)
     * @param g2d  Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setGraphics2D(Graphics2D g2d){
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(s);
    }

    /**
     * 设置背景为白色
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setColorWhite(Graphics2D g2d){
        g2d.setColor(Color.WHITE);
        //填充整个屏幕
        g2d.fillRect(0,0,600,600);
        //设置笔刷
        g2d.setColor(Color.BLACK);
    }
    public static void main(String[] args) throws IOException {
//        BufferedImage image = insertWords(getBarCode("123456789"), "123456789");
//        A80/90R8A(8A侧通孔)
        BufferedImage image = insertWords(getBarCode("1 23 4567890 12 "), "1 23 4567890 12 ");
        ImageIO.write(image, "jpg", new File("C:\\Users\\pax\\Documents\\aaaaaaaaaaa\\barcode.png"));
    }


}

 

package qr;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;

/**
 *  生成二维码,解析二维码
 */
public class QRCode {
    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二维码尺寸
    //private static final int QRCODE_SIZE = 300;
    // LOGO宽度
    private static final int WIDTH = 60;
    // LOGO高度
    private static final int HEIGHT = 60;

    private static BufferedImage createImage(String content, int w,int h, String imgPath,
                                             boolean needCompress) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, w, h, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
                        : 0xFFFFFFFF);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入图片
        QRCode.insertImage(image,w,h, imgPath, needCompress);
        return image;
    }

    /**
     * 插入LOGO
     *
     * @param source
     *            二维码图片
     * @param imgPath
     *            LOGO图片地址
     * @param needCompress
     *            是否压缩
     * @throws Exception
     */
    private static void insertImage(BufferedImage source,int w,int h, String imgPath,
                                    boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println(""+imgPath+"   该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height,
                    Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (w - width) / 2;
        int y = (h - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content
     *            内容
     * @param imgPath
     *            LOGO地址
     * @param destPath
     *            存放目录
     * @param needCompress
     *            是否压缩LOGO
     * @throws Exception
     */
    public static String encode(String content, int w,int h,String imgPath, String destPath,
                                boolean needCompress,boolean isExecl) throws Exception {
        BufferedImage image = QRCode.createImage(content,  w, h,imgPath,
                needCompress);
        mkdirs(destPath);
        String file = "";
        if(isExecl){
            file = content+".jpg";
        }else{
            file = new Random().nextInt(99999999)+".jpg";
        }
        image.setRGB(w, h,BufferedImage.TYPE_INT_RGB);

        ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
        return file;
    }

    /**
     * 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
     * @date 2013-12-11 上午10:16:36
     * @param destPath 存放目录
     */
    public static void mkdirs(String destPath) {
        File file =new File(destPath);
        //当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content
     *            内容
     * @param imgPath
     *            LOGO地址
     * @param destPath
     *            存储地址
     * @throws Exception
     */
    public static void encode(String content,int w,int h, String imgPath, String destPath,boolean isExecl)
            throws Exception {
        QRCode.encode(content,w,h, imgPath, destPath, false,isExecl);
    }

    /**
     * 生成二维码
     *
     * @param content
     *            内容
     * @param destPath
     *            存储地址
     * @param needCompress
     *            是否压缩LOGO
     * @throws Exception
     */
    public static void encode(String content, int w,int h,String destPath,
                              boolean needCompress) throws Exception {
        QRCode.encode(content, w,h,null, destPath, needCompress);
    }

    /**
     * 生成二维码
     *
     * @param content
     *            内容
     * @param destPath
     *            存储地址
     * @throws Exception
     */
    public static void encode(String content,int w,int h, String destPath) throws Exception {
        QRCode.encode(content, w, h, null, destPath, false);
    }

    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content
     *            内容
     * @param imgPath
     *            LOGO地址
     * @param output
     *            输出流
     * @param needCompress
     *            是否压缩LOGO
     * @throws Exception
     */
    public static void encode(String content,int w,int h, String imgPath,
                              OutputStream output, boolean needCompress) throws Exception {
        BufferedImage image = QRCode.createImage(content, w, h, imgPath,
                needCompress);
        image.setRGB(w, h,BufferedImage.TYPE_INT_RGB);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    /**
     * 生成二维码
     *
     * @param content
     *            内容
     * @param output
     *            输出流
     * @throws Exception
     */
    public static void encode(String content,int w,int h, OutputStream output)
            throws Exception {
        QRCode.encode(content, w,h,null, output, false);
    }

    /**
     * 解析二维码
     *
     * @param file
     *            二维码图片
     * @return
     * @throws Exception
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
                image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 解析二维码
     *
     * @param path
     *            二维码图片地址
     * @return
     * @throws Exception
     */
    public static String decode(String path) throws Exception {
        return QRCode.decode(new File(path));
    }

    public static void main(String[] args) throws Exception {
        String text = "http://www.baidu.com";  //这里设置自定义网站url
        String logoPath = "C:\\15.jpg";
        String destPath = "C:\\";
        int w =300;
        int h=300;
        System.out.println(QRCode.encode(text, w,h, logoPath, destPath, true,false));
    }
}  
/*
 * Created by JFormDesigner on Thu Aug 27 14:33:02 CST 2020
 */

package qr;

import com.formdev.flatlaf.FlatIntelliJLaf;

import javax.swing.*;
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author 1
 */
public class QrCodeShow extends JFrame {
    public QrCodeShow(String url,String title,int w,int h) {
        FlatIntelliJLaf.install();
        initComponents();

        ImageIcon icon = null;
        try {
            icon = new ImageIcon(new URL(url));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        label1.setIcon(icon);

        setTitle(title);  // 标题
        setResizable(false); // 固定窗体
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //关闭窗口 ,退出进程

        //显示屏幕中央
//        int width = 325;  //宽度
//        int height =  340;  // 高度
        int width = w;
        int height = h;
        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));  //窗体大小
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        label1 = new JLabel();

        //======== this ========
        Container contentPane = getContentPane();
        contentPane.setLayout(null);
        contentPane.add(label1,BorderLayout.CENTER);
        label1.setBounds(40, 15, 430, 345);

        {
            // 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 JLabel label1;
    // JFormDesigner - End of variables declaration  //GEN-END:variables
}

在C#中,对软件进行密和防解密通常涉及以下几个步骤: 1. **数据密**: - 使用.NET Framework内置的`System.Security.Cryptography`命名空间提供的密算法,如`Aes`(高级密标准)或`Rijndael`来进行数据密。例如,你可以创建一个SymmetricKey密器(如AesCryptoServiceProvider),然后将明文数据密成密文。 ```csharp using System.IO; using System.Security.Cryptography; // ... byte[] key = ... // 生成或获取密密钥 byte[] iv = ... // 初始化向量,用于流式密 using (Aes aes = Aes.Create()) { aes.Key = key; aes.IV = iv; using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, aes.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] input = Encoding.UTF8.GetBytes("待密的文本"); csEncrypt.Write(input, 0, input.Length); } byte[] encryptedBytes = msEncrypt.ToArray(); } } ``` 2. **使用哈希函数**(如SHA、MD5)保护敏感信息的完整性,防止篡改。 3. **混淆代码**(Obfuscation):通过第三方工具如ILRepack、Dotfuscator等,可以混淆源代码,使得反汇编和逆工程变得困难。 4. **许可管理**(License Management):可以使用专有的密许可证系统,如Strong Name Signing(保证唯一性和代码来源验证)或使用专门的授权服务。 5. **资源文件密**:如果需要保护资源文件(如图片、音频),可以在应用程序发布时将其转换为不可读的形式。 请注意,尽管上述技术可以帮助提高软件的安全性,但完全防止所有形式的解密是不可能的,因为密总是基于数学算法,理论上都可以被破解。因此,一个好的安全策略通常是结合多种防护手段,并定期更新和评估安全性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值