package com.runt.open.mvi.retrofit.converter; import android.text.TextUtils; import android.util.Log; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.runt.open.mvi.BuildConfig; import com.runt.open.mvi.retrofit.utils.RSAUtils; import com.runt.open.mvi.utils.GsonUtils; import org.json.JSONException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import okhttp3.ResponseBody; import retrofit2.Converter; /** * @purpose 解密gson转换器 * @author Runt (qingingrunt2010@qq.com) * @date 2021-7-22. */ public class DecryptGsonResponseBodyConverter implements Converter { private final Gson gson; private final TypeAdapter adapter; private final Charset UTF_8 = Charset.forName("UTF-8"); private final boolean transHump;//驼峰转换 private final String ENCRYPT = "body"; public DecryptGsonResponseBodyConverter(Gson gson, TypeAdapter adapter, boolean transHump) { this.gson = gson; this.adapter = adapter; this.transHump = transHump; } @Override public T convert(ResponseBody value) throws IOException { String response = null; try { String val = new String(value.bytes(),UTF_8); response = decryptJsonStr(val);//解密 } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { e.printStackTrace(); response = "{\"code\":412,\"message\":\""+"解密数据出错"+e.getMessage()+"\"}"; } catch (JSONException e) { e.printStackTrace(); response = "{\"code\":414,\"message\":\"非标准json\"}"; }catch (Exception e){ e.printStackTrace(); JsonReader jsonReader = gson.newJsonReader(value.charStream()); return adapter.read(jsonReader); } finally { if(response==null){ return null; } InputStream inputStream = new ByteArrayInputStream(response.getBytes()); JsonReader jsonReader = gson.newJsonReader(new InputStreamReader(inputStream, UTF_8)); T result = adapter.read(jsonReader); if (jsonReader.peek() != JsonToken.END_DOCUMENT) { throw new JsonIOException("JSON document was not fully consumed."); } value.close(); return result; } } /** * 解密json * @param body * @return * @throws Exception */ protected String decryptJsonStr(String body) throws Exception { if(BuildConfig.DEBUG) { Log.e("Converter", "decryptJsonStr body:" + body); } if(TextUtils.isEmpty(body)){ }else if(body.indexOf("{") == 0) { body = RSAUtils.decryptVerify(body,ENCRYPT); } return transHump? GsonUtils.toHumpJson(body):body; } }