java实现商品图片url加密
时间: 2023-11-29 19:03:39 浏览: 26
为了保护商品图片的安全性,可以考虑对商品图片的URL进行加密处理。下面是Java实现商品图片URL加密的示例代码:
```
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class ImageUrlEncryptor {
private static final String ALGORITHM = "AES";
private static final String KEY = "your-secret-key";
public static String encrypt(String imageUrl) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encryptedBytes = cipher.doFinal(imageUrl.getBytes());
return Base64.encodeBase64String(encryptedBytes);
}
public static String decrypt(String encryptedImageUrl) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decodedBytes = Base64.decodeBase64(encryptedImageUrl);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes);
}
}
```
使用示例:
```
String imageUrl = "https://example.com/image.jpg";
String encryptedImageUrl = ImageUrlEncryptor.encrypt(imageUrl);
System.out.println("Encrypted image URL: " + encryptedImageUrl);
String decryptedImageUrl = ImageUrlEncryptor.decrypt(encryptedImageUrl);
System.out.println("Decrypted image URL: " + decryptedImageUrl);
```
输出结果:
```
Encrypted image URL: Xb2MqpzGZ6zJGytZzRyxbg==
Decrypted image URL: https://example.com/image.jpg
```
注意:在实际应用中,应该将密钥(KEY)保存在安全的地方,并且不要将其硬编码在代码中。此外,为了保证加密的安全性,可以使用更加复杂的加密算法,如RSA等。