sign认证(MD5)
想法 同一个方法 A用几个参数 通过MD5生成一个字符串 B也用这个方法 根据A传的参数生成一个字符串 两者一致 sign认证通过 参数可借助数据库生成一次两边一起更改成新的值 提高加密级别
1、生成sign的方法
public static String generateSignature(TreeMap<String, String> params, String secret) {
// Sort the parameters and concatenate them
StringBuilder mixParamBuilder = new StringBuilder();
for (String key : params.keySet()) {
mixParamBuilder.append(key).append(params.get(key));
}
String mixParam = mixParamBuilder.toString();
// Perform MD5 encryption twice and convert to uppercase
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5Bytes = md.digest(mixParam.getBytes());
String md5Hex = bytesToHex(md5Bytes);
String upperMd5 = md5Hex.toUpperCase();
// Add the secret and perform MD5 again
String combined = upperMd5 + secret;
byte[] secondMd5Bytes = md.digest(combined.getBytes());
String secondMd5Hex = bytesToHex(secondMd5Bytes);
return secondMd5Hex.toUpperCase();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
public static void main(String[] args) {
TreeMap<String, String> params = new TreeMap<>();
params.put("param1", "value1"); //第一个加密参数 key和value 随意取值
// params.put("param2", "value2"); //第二个加密参数 key(param2)和value(value2)随意取值 (根据加密级别需要随意传多个参数)
String secret = "JiaMiKey"; //加密key 随意取 (一般存于库中)
/*上述map的key值 value值 secret 要与下部分代码快保持一致*/
String signature = generateSignature(params, secret);
System.out.println("Generated Signature: " + signature); //生成一个唯一sign签名
}
2、sign认证
public static boolean isSignatureValid(TreeMap<String, String> params, String secret, String receivedSignature) {
// Remove the 'sign' parameter if present
String actualSignature = params.remove("sign");
// If the received signature is null or empty, return false
if (receivedSignature == null || receivedSignature.isEmpty()) {
return false;
}
// Generate the expected signature
String expectedSignature = generateSignature(params, secret);
System.out.println("expectedSignature===>"+expectedSignature);
System.out.println("receivedSignature===>"+receivedSignature);
// Compare the received and expected signatures
return receivedSignature.equals(expectedSignature);
}
private static String generateSignature(TreeMap<String, String> params, String secret) {
// Sort the parameters and concatenate them
StringBuilder mixParamBuilder = new StringBuilder();
for (String key : params.keySet()) {
mixParamBuilder.append(key).append(params.get(key));
}
String mixParam = mixParamBuilder.toString();
// Perform MD5 encryption twice and convert to uppercase
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5Bytes = md.digest(mixParam.getBytes());
String md5Hex = bytesToHex(md5Bytes);
String upperMd5 = md5Hex.toUpperCase();
// Add the secret and perform MD5 again
String combined = upperMd5 + secret;
byte[] secondMd5Bytes = md.digest(combined.getBytes());
String secondMd5Hex = bytesToHex(secondMd5Bytes);
return secondMd5Hex.toUpperCase();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
//模拟controller 接收前端传过来的数据
public static void main(String[] args) {
TreeMap<String, String> params = new TreeMap<>();
params.put("param1", "value1"); //第一个加密参数 与上方代码块保持一致
// params.put("param2", "value2"); //第二个加密参数 与上方代码块保持一致
params.put("sign", "7139B95E3106C6CB39C33DFBF23094FC"); //前端接收的sign签证
String secret = "JiaMiKey"; //自己从数据库查
//这个sign(7139B95E3106C6CB39C33DFBF23094FC) 是后台通过上边参数执行生成的 看和传过来的sign是否一致 一致的话sign认证通过
boolean isValid = isSignatureValid(params, secret, "7139B95E3106C6CB39C33DFBF23094FC");
System.out.println("Is Signature Valid: " + isValid);
}
数据加解密 (AES)
1、生成secretkey
//生成secretkey
public static byte[] generateAESKey(int keySize) throws NoSuchAlgorithmException, InvalidKeySpecException {
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
PBEKeySpec spec = new PBEKeySpec(
"password".toCharArray(), // password 这个字符串可以随意替换
salt, // Salt
1000, // Iteration count
keySize // Key length
);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
return factory.generateSecret(spec).getEncoded();
}
public static void main(String[] args) {
try {
byte[] aesKey = generateAESKey(128);
System.out.println("生成的secretKey: " + Base64.getEncoder().encodeToString(aesKey));
} catch (Exception e) {
e.printStackTrace();
}
}
2、将生成的secregtKey 代入
public static byte[] encrypt(byte[] key, byte[] data) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] key, byte[] encrypted) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return cipher.doFinal(encrypted);
}
public static void main(String[] args) throws Exception {
// Example usage
String secretKey = "S0PiNVWeRilAPtPhQDqbew=="; //上一步代码生成的secretKey
String plainText = "[{\"value1\":\"1\", \"value2\":\"abcd\",\"value3\":\"\"}]"; //需要加密的数据(只要是字符串就可以 可通过JSONArray进行解析数据)
byte[] plainTextBytes = plainText.getBytes();
byte[] key = secretKey.getBytes("UTF-8");
// 将数据加密 --- 传到前端
byte[] encrypted = encrypt(key, plainTextBytes);
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
System.out.println("加密: " + encryptedString);
// 前端接收过来的加密数据进行解密 --- 进行处理
byte[] decryptedBytes = decrypt(key, Base64.getDecoder().decode(encryptedString));
String decryptedText = new String(decryptedBytes);
System.out.println("解密: " + decryptedText);
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
/*--------------------- 引用com.alibaba.json依赖(自己找)---------------------------*/
String str = new String(decryptedBytes);
JSONArray jsonArray = JSON.parseArray(decryptedText);
System.out.println(jsonArray);
/*-------------------- 然后将解析好的数据转换成数组对象进行逻辑处理 ----------------------*/
}
2万+

被折叠的 条评论
为什么被折叠?



