![0968e9f04ef682275f933a340f9be494.png](https://i-blog.csdnimg.cn/blog_migrate/f962f4dc18096743b5b91f58b4397950.jpeg)
专注于Android开发,分享经验总结,欢迎加入
![86e8b3a5c556019be6ffba26b4eba947.png](https://i-blog.csdnimg.cn/blog_migrate/b55715778e6ea796da6b5a34ee0c42be.png)
github
接口数据加密
方案:客户端请求时数据加密,服务端解密;服务端返回数据时加密,客户端再去解密;需要两对公钥和私钥
RSA非对称加密,公钥加密,私钥去解密,AES是对称加密,由于RSA加密数据有上限,需要做分段加解密处理,在解密时很容易报错,所以用RSA公钥去加密AES,AES去加解密内容
在做的过程中遇到一些问题,特此记录
Android端加解密都正常,Java端加解密也正常,当Android和Java交互时RSA解密报错,出现乱码,原因是RSA加解密的格式不同,转byte时加上编码方式string.getBytes("utf-8")
在Android端获取加解密的Cipher类时要使用Cipher.getInstance("RSA/ECB/PKCS1Padding");
在Java端使用Cipher.getInstance("RSA")来获取
RSA Android端加密解密方式,Java端使用Cipher.getInstance("RSA")
![58f05f9058655395dc5b41d0f4dc526b.png](https://i-blog.csdnimg.cn/blog_migrate/579eb7012c753d73460146e3fa3c4dd0.jpeg)
![b623b635b67f6edda69b64367c22d9e0.png](https://i-blog.csdnimg.cn/blog_migrate/9821c6791068abc529230d9fb39aa631.jpeg)
核心类代码
Base64编码解码工具类
public final class Base64 {
private static final int BASELENGTH = 128;
private static final int LOOKUPLENGTH = 64;
private static final int TWENTYFOURBITGROUP = 24;
private static final int EIGHTBIT = 8;
private static final int SIXTEENBIT = 16;
private static final int FOURBYTE = 4;
private static final int SIGN = -128;
private static char PAD = '=';
private static byte[] base64Alphabet = new byte[BASELENGTH];
private static char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect) {
return (octect == PAD);
}
private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;