根據序列號加密生產4*4的密碼,如:X9PL-TERY-NOZN-GMF1
阿新 • • 發佈:2021-10-29
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); } }