根据序列号加密生产4*4的密码,如:X9PL-TERY-NOZN-GMF1

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 根据序列号加密生产4*4的密码
 */

public class EncryptionAndDecryption {
    // 私钥
    private static String salt = "1234123412341234";

    /**
     * 加密
     *
     * @param encryptMessage 需要加密的信息
     * @return
     * @throws Exception
     */
    public static String encrypt(String encryptMessage) throws Exception {
        // 两个参数,第一个为私钥字节数组, 第二个为加密方式 AES或者DES
        SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES");
        // 实例化加密类,参数为加密方式,要写全
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 初始化加密
        cipher.init(Cipher.ENCRYPT_MODE, key);
        // 加密操作,返回加密后的字节数组
        byte[] bytes = cipher.doFinal(encryptMessage.getBytes());
        String tempResult = Base64.encodeBase64String(bytes);
        // 正则取出字母数字
        String result = tempResult.replaceAll("[^(a-zA-Z0-9)]", "");
        StringBuilder sql = new StringBuilder("");
        // 每4位拼接一次
        for (int i = 0; i < 16; i = i + 4) {
            sql.append(result.substring(i, i + 4).toUpperCase());
            sql.append("-");
        }
        String substring = sql.substring(0, sql.length() - 1);
        return substring;
    }

    // 测试
    public static void main(String[] args) throws Exception {
        String serialNumber = "123456789";
        String encrypt = encrypt(serialNumber);
        System.out.println("加密后信息encrypt:" + encrypt);
    }
}
原文地址:https://www.cnblogs.com/nginxTest/p/15481055.html