在开发中,我们经常和服务器打交道:最终目的是要和数据打交道,但往往会出现数据安全的问题。比如我们向服务器发送数据,服务器返回数据给我们,这就涉及到很重要的安全问题:分3步解决这个问题。1:首先我们新建一个加解密类如下:**Createdbyacer-pcon2018/6/22.*/publicclassEncryptUtil{privatestaticfinalStringALGORITHM="AES/ECB/PKCS5Padding";//加密密钥privatestaticfinalStringAES_KEY="XXX(我们自己设置)";privatestaticSecretKeySpecsecretKeySpec;/***前台传输数据解密**@paramrawJson原始JSON*@return解密后的Map*/publicstaticTdecrypt(StringrawJson,ClasstClass){Tresult=null;try{Ciphercipher=Cipher.getInstance(ALGORITHM);cipher.init(Cipher.DECRYPT_MODE,getAesKey());byte[]paramBytes=cipher.doFinal(Base64.decode(rawJson.getBytes("UTF-8"),Base64.NO_WRAP));StringparamJson=newString(paramBytes);result=GsonUtil.fromJson(paramJson,tClass);}catch(NoSuchPaddingExceptione){e.printStackTrace();}catch(NoSuchAlgorithmExceptione){e.printStackTrace();}catch(InvalidKeyExceptione)){e.printStackTrace();}catch(BadPaddingExceptione){e.printStackTrace();}catch(IllegalBlockSizeExceptione){e.printStackTrace();}catch(UnsupportedEncodingExceptione){e.printStackTrace();}returnresult;}/***数据传输过程中需要加密设置*@paramrawMap*@return*/publicstaticStringencrypt(MaprawMap){Stringresult="";try{Ciphercipher=Cipher.getInstance(算法);cipher.init(Cipher.ENCRYPT_MODE,getAesKey());StringrawJson=Gs??onUtil.toJson(rawMap);byte[]paramBytes=cipher.doFinal(rawJson.getBytes("UTF-8"));result=Base64.encodeToString(paramBytes,Base64.NO_WRAP);}catch(NoSuchPaddingExceptione){e.printStackTrace();}catch(NoSuchAlgorithmExceptione){e.printStackTrace();}catch(InvalidKeyExceptione){e.printStackTrace();}catch(BadPaddingExceptione){e.printStackTrace();}catch(IllegalBlockSizeExceptione){e.printStackTrace();}catch(UnsupportedEncodingExceptione){e.printStackTrace();}returnresult;}privatestaticSecretKeySpecgetAesKey(){if(secretKeySpec!=null)){returnsecretKeySpec;}try{secretKeySpec=newSecretKeySpec(AES_KEY.getBytes("UTF-8"),"AES");}catch(UnsupportedEncodingExceptione){e.printStackTrace();}returnsecretKeySpec;}}2:BaseResult如下(待解析数据的根类,放数据的类要继承该类):publicclassBaseResult{privateintresult;privateStringmessage;publicintgetResult(){returnresult;}publicvoidsetResult(intresult){this.result=result;}publicStringgetMessage(){returnmessage;}publicvoidsetMessage(Stringmessage){this.message=message;}}3:当我们在主类(或Fragment)中使用它时,它如下://loadDatapublicvoidinitData(){//这里使用线程池,让线程在线程池中运行,防止程序卡死APIConfig.getDataIntoView(newRunnable(){@Overridepublicvoidrun(){Mapma??p=newHashMap<>();map.put("token",RuntimeConfig.user.getToken());StringparamJson=EncryptUtil.encrypt(map);Stringurl="http://这里是我们的targetURL";Stringrs=HttpUtil.GetDataFromNetByPost(url,newParamsBuilder().addParam("paramJson",paramJson.getParams());//rs判断为空finalDiaryDetailResultresult=EncryptUtil.decrypt(rs,DiaryDetailResult.class);UIUtils.runOnUIThread(newRunnable(){@Overridepublicvoidrun(){//这里禁用if(result!=null&&result.getResult()==APIConfig.CODE_SUCCESS){DiarydiaryData=result.getData().getContent();//接下来对解析出来的数据进行自己的操作。..........}else{//Toast弹窗加载失败;}}});}});}3:大功告成!