加密规则
# 附录:加密规则
加密方式:AES
密钥:Z0mA12Fw2DnY8qtMCgwFGb0Zq41ck5qN
加密模式:CBC
填充:PKCS5Padding
数据块:256位
输出:Base64
字符集:utf8
**Java Code Demo**:
加密前字符串:20640,0200636,75.00,20191227235959
加密后字符串:bQpEjehTNVY%2Bkrni82ef6l8BTE1eiWVnEGmi7hSH3pxh1evVZdarQtiFtvYJeV9m
```java
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* AESCoder 256bits密钥 加解密
*/
public class Demo {
/* 秘钥长度,256bits */
private static final int KEY_BITS = 256;
/* 256 BITS的秘钥, 对应的Byte长度. */
private static final int KEY_256_BITS = KEY_BITS / 8;
private static final String CIPHER_AES = "AES";
private static final String CIPHER_TYPE = "AES/CBC/PKCS5Padding";
/* 根据传入的256bits的秘钥进行加密. */
public static byte[] encrypt(@NotNull byte[] rawKey, @NotNull byte[] origin) throws Exception {
if(rawKey.length != KEY_256_BITS) {
throw new RuntimeException("密钥长度不合法");
}
return encrypt0(rawKey, origin);
}
/**
* 根据传入的256bits的秘钥,解密.
*/
public static byte[] decrypt(@NotNull byte[] rawKey, @NotNull byte[] decoded) throws Exception {
if(rawKey.length != KEY_256_BITS) {
throw new RuntimeException("密钥长度不合法");
}
return decrypt0(rawKey, decoded);
}
/**
* AESCoder 加密
* @return 返回 256位的密文
*/
private static byte[] encrypt0(byte[] rawKey, byte[] origin) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, CIPHER_AES);
Cipher cipher = Cipher.getInstance(skeySpec.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
return cipher.doFinal(origin);
}
/**
* AESCoder 解密
*/
private static byte[] decrypt0(byte[] rawKey, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, CIPHER_AES);
Cipher cipher = Cipher.getInstance(skeySpec.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
return cipher.doFinal(encrypted);
}
public static void main(String[] args) {
try{
String secretKey = "Z0mA12Fw2DnY8qtMCgwFGb0Zq41ck5qN";
String toEncryStr = "20640,0200636,75.00,20191227235959";
byte[] encryResultByte = Demo.encrypt(secretKey.getBytes(),toEncryStr.getBytes());
String encryResult = Base64.encodeBase64String(encryResultByte);
String encodeResult = URLEncoder.encode(encryResult, StandardCharsets.UTF_8.name());
System.out.println("加密字符串====" + encodeResult);
// bQpEjehTNVY%2Bkrni82ef6l8BTE1eiWVnEGmi7hSH3pxh1evVZdarQtiFtvYJeV9m
String secretCode = URLDecoder.decode(encodeResult, StandardCharsets.UTF_8.name());
byte[] decryResultByte = Demo.decrypt(secretKey.getBytes(),Base64.decodeBase64(encryResult));
String decryResult = new String(decryResultByte);
System.out.println("解密字符串====" + decryResult);
// 20640,0200636,75.00,20191227235959
} catch (Exception e) {
e.printStackTrace();
}
}
}
```