小程序模板網(wǎng)

Java實(shí)現(xiàn)小程序用戶信息解密

發(fā)布時(shí)間:2018-02-10 12:05 所屬欄目:小程序開(kāi)發(fā)教程

Node,php,Phthon,C++地址:http://www.wxapp-union.com/forum.php?mod=viewthread&tid=1415
以及C#的代碼:http://www.wxapp-union.com/forum.php?mod=viewthread&tid=1398
ruby:http://www.wxapp-union.com/forum.php?mod=viewthread&tid=1541
go:http://www.wxapp-union.com/forum.php?mod=viewthread&tid=539
 
加上這個(gè),已經(jīng)比較齊全了,值得參考,另外大家可以搜索一下“登錄”這個(gè)關(guān)鍵詞,查看一些文章關(guān)于登錄的,用于輔助;
關(guān)鍵代碼:

public String decrypt(String encryptedData, String sessionKey, String iv, String encodingFormat) throws Exception {

   try {

      Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

      BASE64Decoder base64Decoder = new BASE64Decoder();

      byte[] _encryptedData = base64Decoder.decodeBuffer(encryptedData);

      byte[] _sessionKey = base64Decoder.decodeBuffer(sessionKey);

      byte[] _iv = base64Decoder.decodeBuffer(iv);

      SecretKeySpec secretKeySpec = new SecretKeySpec(_sessionKey, "AES");

      IvParameterSpec ivParameterSpec = new IvParameterSpec(_iv);

      cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

      byte[] original = cipher.doFinal(_encryptedData);

      byte[] bytes = WxPKCS7Encoder.decode(original);

      String originalString = new String(bytes, encodingFormat);      return originalString;

   } catch (Exception ex) {

      return null;

   }

}

依賴類 WxPKCS7Encoder.javaclass WxPKCS7Encoder {

   static Charset CHARSET = Charset.forName("utf-8");

   static int BLOCK_SIZE = 32;



   /**

    * 獲得對(duì)明文進(jìn)行補(bǔ)位填充的字節(jié).

    * 

    * @param count 需要進(jìn)行填充補(bǔ)位操作的明文字節(jié)個(gè)數(shù)

    * @return 補(bǔ)齊用的字節(jié)數(shù)組

    */

   static byte[] encode(int count) {

      // 計(jì)算需要填充的位數(shù)

      int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);

      if (amountToPad == 0) {

         amountToPad = BLOCK_SIZE;

      }

      // 獲得補(bǔ)位所用的字符

      char padChr = chr(amountToPad);

      String tmp = new String();

      for (int index = 0; index < amountToPad; index++) {

         tmp += padChr;

      }

      return tmp.getBytes(CHARSET);

   }



   /**

    * 刪除解密后明文的補(bǔ)位字符

    * 

    * @param decrypted 解密后的明文

    * @return 刪除補(bǔ)位字符后的明文

    */

   static byte[] decode(byte[] decrypted) {

      int pad = (int) decrypted[decrypted.length - 1];

      if (pad < 1 || pad > 32) {

         pad = 0;

      }

      return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);

   }



   /**

    * 將數(shù)字轉(zhuǎn)化成ASCII碼對(duì)應(yīng)的字符,用于對(duì)明文進(jìn)行補(bǔ)碼

    * 

    * @param a 需要轉(zhuǎn)化的數(shù)字

    * @return 轉(zhuǎn)化得到的字符

    */

   static char chr(int a) {

      byte target = (byte) (a & 0xFF);

      return (char) target;

   }



}


jdk版本1.8


易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開(kāi)源 碼云倉(cāng)庫(kù):starfork
本文地址:http://22321a.com/wxmini/doc/course/21977.html 復(fù)制鏈接 如需定制請(qǐng)聯(lián)系易優(yōu)客服咨詢:800182392 點(diǎn)擊咨詢
QQ在線咨詢