在Android开发或者其他需要通讯的过程中我们都喜欢把参数进行加密来保证数据在传输过程中的安全。
这里我们用java写个简单的对称加密解密算法。
package xxx.xxx
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidParameterException;
import java.security.SecureRandom;
import java.util.Base64;
public class CryptionUtil {
/**
* 内容加密
* @param content 需要加密的内容
* @param secretKey 密钥
* @return
* @throws Exception
*/
public static String encrypt(String content, String secretKey) throws Exception {
byte[] key = Base64.getDecoder().decode(secretKey);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] cipherText = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
String res = Base64.getEncoder().encodeToString(cipherText);
return String.join("~split~", Base64.getEncoder().encodeToString(iv), res);
}
/**
* 内容解密
* @param cipherText 需要解密的内容
* @param secretKey 解密密钥
* @return
* @throws Exception
*/
public static String decrypt(String cipherText, String secretKey) throws Exception {
byte[] key = Base64.getDecoder().decode(secretKey);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
String[] arr = cipherText.split("~split~");
if (arr == null || arr.length != 2) {
throw new InvalidParameterException();
}
byte[] iv = Base64.getDecoder().decode(arr[0]);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedText = cipher.doFinal(Base64.getDecoder().decode(arr[1]));
return new String(decryptedText, StandardCharsets.UTF_8);
}
}
现在我们简单的测试下:
加密
HashMap<String,Object> params = new HashMap<>();
params.put("id","66937s9nnah2779293223hhad");
params.put("content_type","userinfo");
params.put("title","这是标题");
params.put("name","这是姓名");
params.put("image","https://blog.jishuge.cn/avtar.jpg");
try {
String key = "ABCDT5F8Dgn12345"; //这里是密钥,加密和解密都用到它,不传输
String seceretKey = Base64.getEncoder().encodeToString(key.getBytes());
String encrypt = CryptionUtil.encrypt(JSONObject.toJSONString(params),seceretKey);
System.out.println(encrypt);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
解密
//被加密之后的密文
String message = "sGSCA05A9aBY0rIKwgWkEQ==~split~cRFS++NpEZGHZXW06k0p/0l3o4Et2+PrZpr1GYx3TkO8Zj9T725bhB5OzEubwhfxEMOf67qG4U/xXGLgXBdMGhupVpOFaLCOzHJUCuoYWbo=";
String key = "ABCDT5F8Dgn12345";
String seceretKey = Base64.getEncoder().encodeToString(key.getBytes());
try {
String decrypt = CryptionUtil.decrypt(message,seceretKey);
System.out.println(decrypt);
} catch (Exception e) {
throw new RuntimeException(e);
}
我们这个算法设置的密钥必须是16位,自己可以根据自己的需求来修改密钥长度。