Open xiangnanscu opened 1 year ago
sample code implementation in java
` import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Base64;
public class TimeBasedEncryption {
private static final String ENCRYPTION_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String SECRET_KEY = "your_key_16bytes";
private static final String INIT_VECTOR = "your_iv_16bytes";
public static void main(String[] args) {
String ip = "192.168.0.1";
String encryptedIP = encryptIP(ip);
System.out.println("Encrypted IP: " + encryptedIP);
String decryptedIP = decryptIP(encryptedIP);
System.out.println("Decrypted IP: " + decryptedIP);
}
public static String encryptIP(String ip) {
LocalDateTime expirationTime = LocalDateTime.now().plusHours(1);
String timestamp = expirationTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
String message = timestamp + ip;
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(INIT_VECTOR.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encryptedBytes = cipher.doFinal(message.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decryptIP(String encryptedIP) {
try {
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedIP);
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(INIT_VECTOR.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedMessage = new String(decryptedBytes, StandardCharsets.UTF_8);
// Extract timestamp and IP address
LocalDateTime expirationTime = LocalDateTime.parse(decryptedMessage.substring(0, 14),
DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
LocalDateTime currentTime = LocalDateTime.now();
if (currentTime.isAfter(expirationTime)) {
throw new RuntimeException("Expired encrypted IP");
}
return decryptedMessage.substring(14);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}`
ngx_encrypted_session will plant an expiration time
this part is hard. I don't know how to implement it in nodejs. I try to use this snippet to decrypt the string encrypted byencrypted-session-nginx-module
, the output is a partial success:the nodejs decrypt snippet