最近公司爲了項目安全 使用了https 所有接口要使用DES 加密 加密 RequestBody 的value值
心想 這不是很簡單嗎 直接在攔截器中獲取到要上傳的數據 然後加密 重新賦值 很簡單嘛 但是實踐起來 我真的氣的想要罵娘 太坑了好嗎。。。。無語直接就打到我的臉上
廢話不多說 讓我重溫一下這些坑
第一步 在網絡請求類裏添加攔截器
在攔截器裏對上傳的數據進行操作
如果是post 請求 取出來request.body(); 循環 取出 encodedValue 加密後 重新再 addEncoded 添加進去 這裏要注意 URLDecoder的解碼
如果是get請求 先拿到 request.url() 然後再看這個url中包含不包含請求參數 url.encodedQuery() 如果這個不爲空的話 就是接下來字符串截取->修改加密->重新拼接
然後進行網絡請求
然後解密 ---->
和後臺商量後 後臺返回的數據只對 “data” 字段的value進行了加密 好 那我只對“data” 進行解密就好了
獲取到 response 對返回的json進行解析 因爲後臺對“data”進行加密 無疑 data是String類型的 解析解密後 怎麼將解密後的data重新安裝到json中呢 ?
解密後的data是String類型的 但是原本想要表達的 “data” 該是什麼類型呢 不知道什麼類型 又該怎麼準確的安到實體類裏呢
我被這個“data”困阻了 一直在想 怎麼直接去操作json串 我知道這也不是一個絕美精妙的辦法 但是我腦容量畢竟不大 我覺得我能想到解決的辦法已經很棒了 substring(0,1);畢竟 返回的json也就那麼幾種 { 、[ 、還有什麼都沒有的
那不就好辦了嗎 直接統稱兩類 jsonArray 和jsonObject 至此 我才終於有了完整的思路
我猜看到這裏大家也到了耐心的極限了 但是整體的思路 使用的方法 上面已經基本都講的差不多了 合格的程序員 應該腦海裏也知道該怎麼做了 有點凡爾賽那味了
上代碼!!!!
public class OkhttpInstance {
private static OkHttpClient okHttpClient;
private static Response response;
public static synchronized OkHttpClient createInstance() {
if (okHttpClient == null) {
synchronized (OkhttpInstance.class) {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS) //設置連接超時
.readTimeout(60, TimeUnit.SECONDS) //設置讀超時
.writeTimeout(60, TimeUnit.SECONDS) //設置寫超時
.retryOnConnectionFailure(true) //是否自動重連
.addInterceptor(interceptor) //添加攔截器
.build();
}
}
}
return okHttpClient;
}
private static Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder requestBuilder = request.newBuilder();
//post請求加密
if (request.body() instanceof FormBody) {
FormBody.Builder newFormBody = new FormBody.Builder();//創建新表單
FormBody oidFormBody = (FormBody) request.body();//請求表單
//循環取出 request Body 注意FormBody 纔會有size屬性 FormBody可以滿足大部分的請求
for (int i = 0; i < oidFormBody.size(); i++) {
String str = oidFormBody.encodedValue(i);//value
String decode = URLDecoder.decode(str);//對value進行URLDecoder解碼
String s = oidFormBody.encodedName(i);//name
String name = URLDecoder.decode(s);//對name進行URLDecoder解碼 很重要 這兩個都加上 不然取出請求體的時候有的請求體被URLDecoder編碼 後臺不知道你傳過去的是什麼
String encrypt = DesCipherUtil.encrypt(decode, HDUrl.PAS);//des加密 HDUrl.PAS 是我的密碼 你跟後臺商量定什麼爲密碼
newFormBody.addEncoded(name.trim(), encrypt.trim());//去空格 相當重要!!都是我踩過的坑
}
requestBuilder.method(request.method(), newFormBody.build());
}
request = requestBuilder.build();
// get請求加密
//還回加密的請求頭
HttpUrl url = request.url();
String path = url.encodedPath();//
String query = url.encodedQuery();//請求參數
if (!TextUtils.isEmpty(query)) {
StringBuffer sb = new StringBuffer();
sb.append(HDUrl.DEFAULT).append(path).append("?");//HDUrl.DEFAULT是我的請求地址:https://192.16.2.88 我猜你知道我說的是什麼
Set<String> queryList = url.queryParameterNames();
Iterator<String> iterator = queryList.iterator();
for (int i = 0; i < queryList.size(); i++) {
String queryName = iterator.next();
sb.append(queryName).append("=");
String queryKey = url.queryParameter(queryName);
//對query的key進行加密
if (TextUtils.isEmpty(queryKey) || null == queryKey || "null".equals(queryKey) || queryKey.length() == 0 || "".equals(queryKey)) {
} else {
Log.e("tag", "queryKey-----------" + queryKey);
sb.append(DesCipherUtil.encrypt(queryKey, HDUrl.PAS));
}
if (iterator.hasNext()) {
sb.append("&");
}
}
String newUrl = sb.toString();
// 進行加密後的get請求鏈接
Request.Builder url1 = request.newBuilder()
.url(newUrl);
request = url1.build();
}
response = chain.proceed(request);
byte[] data = response.body().bytes();
String s = new String(data);
MediaType mediaType = response.body().contentType();
try {
Log.e("tag", "s-----------------------" + s);
JSONObject jsonObject = new JSONObject(s);
int code = 0;
if (jsonObject.has("code")) {
code = jsonObject.getInt("code");
} else {
code = jsonObject.getInt("errCode");
}
if (code == 200 || code == 0) {
// 當code=200/0時解密
if (jsonObject.has("data")) {
String code1 = jsonObject.getString("data");
String decrypt = DesCipherUtil.decrypt(code1, HDUrl.PAS);
jsonObject.remove("data");
jsonObject.put("data", decrypt);
Gson gson = new Gson();
//
DefaultBean defaultBean = gson.fromJson(s, DefaultBean.class);
if (decrypt.substring(0, 1).equals("[")) {
List<Object> arrData = gson.fromJson(decrypt, new TypeToken<List<Object>>() {
}.getType());
defaultBean.setData(arrData);
} else if (decrypt.substring(0, 1).equals("{")) {
Object objectData = gson.fromJson(decrypt, Object.class);
defaultBean.setData(objectData);
} else {
defaultBean.setData(decrypt);
}
s = new Gson().toJson(defaultBean);
}
} else if (code == 10100) {
//就代表token過期了
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
UserInfo userInfo = (UserInfo) ShareprefencesUtils.getBean(App.getApplicationContent(), ShareprefencesUtils.USER_INFO);
userInfo.setAccess_token("");
ShareprefencesUtils.putBean(App.getApplicationContent(), ShareprefencesUtils.USER_INFO, userInfo);
Intent intent = new Intent(App.getApplicationContent(), SelectJoinActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
App.getApplicationContent().startActivity(intent);
Toast.makeText(App.getApplicationContent(), "登錄超時請重新登錄", Toast.LENGTH_SHORT).show();
Looper.loop();
}
});
thread.start();
}
} catch (JSONException e) {
e.printStackTrace();
}
return response.newBuilder()
.body(ResponseBody.create(mediaType, s))
.build();
}
};
public static synchronized OkHttpClient getInstance() {
return okHttpClient;
}
其實已經很容易看懂了 一些東西我就不做解釋了 自己悟去吧 下面貼一下DES加密解密類
private DesCipherUtil() {
throw new AssertionError("No DesCipherUtil instances for you!");
}
static {
// add BC provider
// Security.addProvider(new BouncyCastleProvider());
}
/**
* 加密
*
* @param encryptText 需要加密的信息
* @param key 加密密鑰
* @return 加密後Base64編碼的字符串
*/
@SuppressLint("NewApi")
public static String encrypt(String encryptText, String key) {
if (encryptText == null || key == null) {
throw new IllegalArgumentException("encryptText or key must not be null");
}
try {
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(encryptText.getBytes(Charset.forName("UTF-8")));
return Base64.getEncoder().encodeToString(bytes);
} catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException | NoSuchPaddingException
| BadPaddingException | NoSuchProviderException | IllegalBlockSizeException e) {
throw new RuntimeException("encrypt failed", e);
}
}
/**
* 解密
*
* @param decryptText 需要解密的信息
* @param key 解密密鑰,經過Base64編碼
* @return 解密後的字符串
*/
public static String decrypt(String decryptText, String key) {
if (decryptText == null || key == null) {
throw new IllegalArgumentException("decryptText or key must not be null");
}
try {
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] bytes = new byte[0];
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
bytes = cipher.doFinal(Base64.getDecoder().decode(decryptText));
}
return new String(bytes, Charset.forName("UTF-8"));
} catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException | NoSuchPaddingException
| BadPaddingException | NoSuchProviderException | IllegalBlockSizeException e) {
throw new RuntimeException("decrypt failed", e);
}
}
public static void main(String[] args) {
}
這些都是我實實在在用到項目中的 有問題別質疑 我的代碼沒有問題 傲嬌臉