java写一个对long型的id进行复杂的加密获得字符串再写一个方法通过这个字符串解密获取id
下面是一个示例的Java代码,使用AES算法对long类型的id进行加密和解密:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class IdEncryptor {
private static final String SECRET_KEY = "mySecretKey12345"; // 密钥
public static String encrypt(long id) {
try {
// 将long类型的id转换为字节数组
byte[] idBytes = longToBytes(id);
// 创建AES算法的密钥
SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
// 创建AES加密算法实例
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// 加密id字节数组
byte[] encryptedBytes = cipher.doFinal(idBytes);
// 使用Base64编码将加密后的字节数组转换为字符串
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static long decrypt(String encryptedId) {
try {
// 使用Base64解码字符串
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedId);
// 创建AES算法的密钥
SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
// 创建AES解密算法实例
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
// 解密id字节数组
byte[] idBytes = cipher.doFinal(encryptedBytes);
// 将字节数组转换为long类型的id
return bytesToLong(idBytes);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
private static byte[] longToBytes(long value) {
byte[] bytes = new byte[8];
for (int i = 7; i >= 0; i--) {
bytes[i] = (byte) (value & 0xFF);
value >>= 8;
}
return bytes;
}
private static long bytesToLong(byte[] bytes) {
long value = 0;
for (int i = 0; i < 8; i++) {
value <<= 8;
value |= (bytes[i] & 0xFF);
}
return value;
}
public static void main(String[] args) {
long id = 123456789L;
String encryptedId = encrypt(id);
System.out.println("Encrypted Id: " + encryptedId);
long decryptedId = decrypt(encryptedId);
System.out.println("Decrypted Id: " + decryptedId);
}
}
上述代码使用AES算法对long类型的id进行加密和解密。首先,将long类型的id转换为字节数组,然后使用密钥对字节数组进行加密或解密操作。加密后的字节数组使用Base64编码后转换为字符串,解密时先使用Base64解码字符串,然后进行解密操作,最后将解密后的字节数组转换回long类型的id。在示例的main方法中,先加密id,再解密得到原始的id。
原文地址: https://www.cveoy.top/t/topic/jbRv 著作权归作者所有。请勿转载和采集!