编码算法
首先准备好原文
static String name = "我喜欢你";
URL编码算法
/*
* 编码算法
* */
@Test
public void URLEncodeTest() {
String s = URLEncoder.encode(name, StandardCharsets.UTF_8); // URL编码
System.out.println(s);
String decode = URLDecoder.decode(s, StandardCharsets.UTF_8);//URL解码
System.out.println(decode);
}
Base64编码算法
@Test
public void base64Test() {
byte[] bytes = name.getBytes(StandardCharsets.UTF_8);
String encodeToString = Base64.getEncoder().encodeToString(bytes); //Base64编码
System.out.println(encodeToString);
byte[] decode = Base64.getDecoder().decode(encodeToString); //Base64解码
String s = new String(decode);
System.out.println(s);
}
哈希算法
这里以MD5为例
/*
* 哈希算法
* */
@Test
public void md5Test() {
try {
MessageDigest md = MessageDigest.getInstance("MD5"); //获取MD5实例
md.update(name.getBytes(StandardCharsets.UTF_8)); //输入数据
byte[] bytes = md.digest(); //
System.out.println(new BigInteger(1, bytes).toString(16)); //转换为16进制的字符输出
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
更多哈希算法可见官网算法,只需要更换实例名称即可。
对称加密算法
以AES加密为例,即有一个密匙,可以是128/192/256位的byte数组
public void arsTest() throws Exception {
// 128位密钥 = 16 bytes Key:
byte[] key = "1234567890abcdef".getBytes("UTF-8");
// 开始加密
byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
byte[] encrypt = encrypt(key, nameBytes);
System.out.println("加密:" + new String(encrypt));
// 解密
byte[] decrypt = decrypt(key, encrypt);
System.out.println("解密:" + new String(decrypt));
}
// 加密
public static byte[] encrypt(byte[] key, byte[] nameBytes) throws GeneralSecurityException {
Cipher instance = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKey secretKey = new SecretKeySpec(key, "AES");
instance.init(Cipher.ENCRYPT_MODE, secretKey);
return instance.doFinal(nameBytes);
}
//解密
public static byte[] decrypt(byte[] key, byte[] encrypt) throws GeneralSecurityException {
Cipher instance = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKey secretKey = new SecretKeySpec(key, "AES");
instance.init(Cipher.DECRYPT_MODE, secretKey);
return instance.doFinal(encrypt);
}