1.今天我有个朋友说他们公司用上面这个加密跟编码的,但是他解析出来老是乱码,然后我就看了看帮他改了改,记录一下,顺便有朋友也遇到这样问题的时候可以看看,代码如下:
赞
**
* 项目名称 FileOutputStreamClass
* 包名 otouzi.com.fileoutputstreamclass
* 类名 AESBase
* 时间 2018/8/17
*/
public class AESBase {
private static final String IV_STRING = "shoushoutao*.+Ap";
private static final String KEY = "shoushoutao*.+Ap";
public static String encryptAES(String content) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] byteContent = content.getBytes("UTF-8");
// 注意,为了能与 iOS 统一
// 这里的 key 不可以使用 KeyGenerator、SecureRandom、SecretKey 生成
byte[] enCodeFormat = KEY.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
// 指定加密的算法、工作模式和填充方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encryptedBytes = cipher.doFinal(byteContent);
// 同样对加密后数据进行 base64 编码
return Base64.encodeToString(encryptedBytes, Base64.NO_WRAP);//Base64.NO_WRAP
}
public static String decrypt(byte[] content) throws Exception {
try {
byte[] encrypted1 = Base64.decode(content, Base64.NO_WRAP);
// 创建AES秘钥
SecretKeySpec key = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
// 初始化解密器
byte[] initParam = IV_STRING.getBytes("UTF-8");
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
// 解密
byte[] original = cipher.doFinal(encrypted1);
return new String(original, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
}
就是这么简单然后就处理了,在android中测试运力不能调用base64的库,这个需要注意一下,剩下的
也就没有啥大问题了。有问题留言
举报