Android支付接入(一):支付宝

来源:互联网 发布:网络作家船长写的小说 编辑:程序博客网 时间:2024/05/22 10:29


android支付支付宝sdksdk接入
    相信相同过App获取利润的都会需要接入计费SDK,下边就跟大家走一遍完整的支付宝SDK接入,支付系列均通过计费Button触发,计费所有代码均放到一个java文件实现,这样虽然会有点违背java面向对象及封装性,但这样做的一个好处是可以快速集成到不同的游戏中,将改动的文件降到最低,各有利弊吧,如果大家有什么更好的方法,望一起交流,好了,废话不多说了,开始干活。
PS:初次写博文,各方面还不够完善,看到此博文的朋友有什么意见或者建议请回复或者留言,你们的支持是我最大的动力。

注意事项:
1.添加android.permission.INTERNET权限和android.permission.ACCESS_NETWORK_STATE权限
2.代码中出现注释的地方重点看,没注释的地方可以不看
3.参考下边代码及附带demo足以让你完成支付宝支付,若想了解支付宝更多相关问题请参考附带文档,demo及文档下载地址:http://pan.baidu.com/share/link?shareid=421254&uk=473193131
4.想获取支付宝合作商户ID,及支付宝公钥请点击支付宝链接,生成密钥及PKCS8转码工具在文档中

好了,开始贴代码
MainActivity(程序入口文件)
[java] view plaincopy
  1. package com.example.blogforzfb;  
  2. import android.os.Bundle;  
  3. import android.view.View;  
  4. import android.app.Activity;  
  5.   
  6. public class MainActivity extends Activity {  
  7.   
  8. @Override  
  9. protected void onCreate(Bundle savedInstanceState) {  
  10. super.onCreate(savedInstanceState);  
  11. setContentView(R.layout.activity_main);  
  12. findViewById(R.id.button1).setOnClickListener(newView.OnClickListener() {  
  13. @Override  
  14. public void onClick(View v) {  
  15. // TODO Auto-generated method stub  
  16. //拿到Fiap对象并传入容器  
  17. Fiap fiap = new Fiap(MainActivity.this);  
  18. //调用支付方法,并传入支付金额  
  19. fiap.android_pay(0.01);  
  20. }  
  21. });  
  22. }  
  23.   
  24. }  

Fiap.java(支付逻辑所在文件)
[java] view plaincopy
  1. package com.example.blogforzfb;  
  2.   
  3. // 支付宝应用支付  
  4. // 2012-09-20 14:41:47  
  5. // (c) 2012 Catcap  
  6.   
  7. import java.io.BufferedReader;  
  8. import java.io.File;  
  9. import java.io.FileOutputStream;  
  10. import java.io.IOException;  
  11. import java.io.InputStream;  
  12. import java.io.InputStreamReader;  
  13. import java.io.OutputStream;  
  14. import java.net.HttpURLConnection;  
  15. import java.net.InetSocketAddress;  
  16. import java.net.Proxy;  
  17. import java.net.URL;  
  18. import java.net.URLEncoder;  
  19. import java.security.KeyFactory;  
  20. import java.security.PrivateKey;  
  21. import java.security.PublicKey;  
  22. import java.security.spec.PKCS8EncodedKeySpec;  
  23. import java.security.spec.X509EncodedKeySpec;  
  24. import java.util.ArrayList;  
  25. import java.util.List;  
  26. import javax.net.ssl.HostnameVerifier;  
  27. import javax.net.ssl.HttpsURLConnection;  
  28. import javax.net.ssl.SSLSession;  
  29. importorg.apache.http.client.entity.UrlEncodedFormEntity;  
  30. import org.apache.http.message.BasicNameValuePair;  
  31. import org.json.JSONException;  
  32. import org.json.JSONObject;  
  33. import com.alipay.android.app.IAlixPay;  
  34. import com.alipay.android.app.IRemoteServiceCallback;  
  35. import android.annotation.SuppressLint;  
  36. import android.app.Activity;  
  37. import android.app.AlertDialog;  
  38. import android.app.ProgressDialog;  
  39. import android.content.ComponentName;  
  40. import android.content.Context;  
  41. import android.content.DialogInterface;  
  42. import android.content.Intent;  
  43. import android.content.ServiceConnection;  
  44. import android.content.pm.PackageInfo;  
  45. import android.content.pm.PackageManager;  
  46. import android.net.ConnectivityManager;  
  47. import android.net.NetworkInfo;  
  48. import android.net.Uri;  
  49. import android.os.Bundle;  
  50. import android.os.Handler;  
  51. import android.os.IBinder;  
  52. import android.os.Looper;  
  53. import android.os.Message;  
  54. import android.os.RemoteException;  
  55. import android.util.Log;  
  56. import android.view.KeyEvent;  
  57. import android.widget.Toast;  
  58.   
  59.   
  60. @SuppressLint ("HandlerLeak")  
  61. public class Fiap{  
  62.     Activity mActivity =null;  
  63.       
  64.     //===================================  
  65.     // JAVA 的接口  
  66.     //===================================  
  67.      
  68.       
  69.     public Fiap(Activityactivity){  
  70.      
  71.     mActivity =activity;  
  72.      
  73.     }  
  74.       
  75.     //这里传过来的是想支付多少钱(最好定义成double的,方便调试,毕竟每次测试都支付几元大洋不是每个人都负担的起的)  
  76.     public void android_pay(double coin){  
  77.      
  78.     //支付宝支付必须依赖网络,所以在这里必须加网络判定  
  79.        if (!is_can_internet (mActivity)){  
  80.         
  81.           fiapHandler.sendEmptyMessage(1);  
  82.           return;  
  83.        }  
  84.          
  85.        Message msg = new Message ();  
  86.        Bundle bundle = new Bundle();  
  87.        bundle.putDouble("coin", coin);  
  88.        msg.setData(bundle);  
  89.        msg.what = 1;  
  90.        fss.sendMessage (msg);  
  91.     }  
  92.       
  93.     private HandlerfiapHandler = new Handler(){  
  94.      
  95.     public voidhandleMessage(Message msg) {  
  96.     if (msg.what == 1){  
  97.     new AlertDialog.Builder(mActivity).setTitle ("提示").setMessage("连接不到网络。").setPositiveButton ("确定", newDialogInterface.OnClickListener() {  
  98. @Override  
  99. public void onClick(DialogInterface dialog, int which) {  
  100. // TODO Auto-generated method stub  
  101. Intent intent = new Intent(  
  102. "android.settings.WIFI_SETTINGS");  
  103. mActivity.startActivity(intent);  
  104. }  
  105. }).create ().show ();  
  106. }  
  107.     };  
  108.     };  
  109.       
  110.     //===================================  
  111.     // 支付宝  
  112.     //===================================  
  113.     public classPartnerConfig {  
  114.   
  115. //以下配置涉及到公司内容,所以略去,需自己配置  
  116.        //合作商户ID。用签约支付宝账号登录ms.alipay.com后,在账户信息页面获取。  
  117.        public static final String PARTNER ="";   
  118.        // 商户收款的支付宝账号  
  119.        public static final String SELLER = "";  
  120.        //商户(RSA)私钥(注意一定要转PKCS8格式,否则在Android4.0及以上系统会支付失败)  
  121.        public static final String RSA_PRIVATE ="";  
  122.        // 支付宝(RSA)公钥用签约支付宝账号登录ms.alipay.com后,在密钥管理页面获取。  
  123.        public static final String RSA_ALIPAY_PUBLIC ="";  
  124.     }  
  125.       
  126.       
  127.     private ProgressDialogmProgress = null;  
  128.       
  129.       
  130.     public static classAlixOnCancelListener implements DialogInterface.OnCancelListener{  
  131.        Activity mcontext;  
  132.          
  133.          
  134.        AlixOnCancelListener (Activity context){  
  135.            mcontext =context;  
  136.        }  
  137.          
  138.          
  139.        public void onCancel (DialogInterfacedialog){  
  140.           mcontext.onKeyDown (KeyEvent.KEYCODE_BACK, null);  
  141.        }  
  142.     }  
  143.       
  144.       
  145.     private Handler fss =new Handler (){  
  146.        @SuppressWarnings ("deprecation")  
  147.        public void handleMessage (Message msg){  
  148.           MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(mActivity);  
  149.            booleanisMobile_spExist = mspHelper.detectMobile_sp ();  
  150.            if(!isMobile_spExist)  
  151.               return;  
  152.            //根据订单信息开始进行支付  
  153.            try{  
  154.               //准备订单信息  
  155.               Bundle bundle =msg.getData();  
  156.               double _coin =bundle.getDouble("coin");  
  157.               String orderInfo =getOrderInfo(_coin);  
  158.               // 这里根据签名方式对订单信息进行签名  
  159.               String signType = getSignType();  
  160.               String strsign = sign(signType, orderInfo);  
  161.               // 对签名进行编码  
  162.               strsign = URLEncoder.encode(strsign);  
  163.               // 组装好参数  
  164.               String info = orderInfo +"&sign=" + """ + strsign + """ +"&" + getSignType ();  
  165.               //调用pay方法进行支付  
  166.               MobileSecurePayer msp = newMobileSecurePayer ();  
  167.               boolean bRet = msp.pay (info,mHandler, AlixId.RQF_PAY, mActivity);  
  168.               if (bRet){  
  169.                  // 显示“正在支付”进度条  
  170.                  closeProgress ();  
  171.                  mProgress = BaseHelper.showProgress (mActivity,null"正在支付"falsetrue);  
  172.               }  
  173.            } catch(Exception ex){  
  174.               ex.printStackTrace ();  
  175.            }  
  176.        }  
  177.     };  
  178.       
  179.     private Handler mHandler= new Handler (){  
  180.        public void handleMessage (Message msg){  
  181.            try{  
  182.               String strRet = (String)msg.obj;  
  183.               switch (msg.what){  
  184.                  case AlixId.RQF_PAY:{  
  185.                      //  
  186.                     closeProgress ();  
  187.                      //处理交易结果  
  188.                      try{  
  189.                         // 获取交易状态码,具体状态代码请参看文档  
  190.                         String tradeStatus ="resultStatus={";  
  191.                         int imemoStart =strRet.indexOf ("resultStatus=");  
  192.                         imemoStart +=tradeStatus.length ();  
  193.                         int imemoEnd = strRet.indexOf("};memo=");  
  194.                         tradeStatus =strRet.substring (imemoStart, imemoEnd);  
  195.                         //先验签通知  
  196.                         ResultChecker resultChecker =new ResultChecker (strRet);  
  197.                         int retVal =resultChecker.checkSign ();  
  198.                         if (retVal ==ResultChecker.RESULT_CHECK_SIGN_FAILED){  
  199.                            BaseHelper.showDialog (mActivity, "提示","您的订单信息已被非法篡改。", android.R.drawable.ic_dialog_alert);  
  200.                         } else{  
  201.                            if (tradeStatus.equals ("9000")){  
  202.                             
  203.                               //程序到这里表示支付已经成功了,想干什么就在这里干吧 -v-  
  204.                            Toast.makeText(mActivity,"支付成功",Toast.LENGTH_LONG).show();  
  205.                            Log.i("result of this pay:","successful");  
  206.                              
  207.                            } else if (!tradeStatus.equals ("4000")){  
  208.                             
  209.                            //程序到这里表示此次支付失败,查看具体原因可以从这里打印个log  
  210.                            Toast.makeText(mActivity, "支付失败,交易状态码为:" +tradeStatus, Toast.LENGTH_LONG).show();  
  211.                            Log.e("result of this pay""falied");  
  212.                            }  
  213.                         }  
  214.                      } catch(Exception e){  
  215.                         e.printStackTrace ();  
  216.                      }  
  217.                  }  
  218.                     break;  
  219.               }  
  220.               super.handleMessage(msg);  
  221.            } catch(Exception e){  
  222.               e.printStackTrace ();  
  223.            }  
  224.        }  
  225.     };  
  226.       
  227.       
  228.     String getSignType(){  
  229.        String getSignType = "sign_type=" + """ + "RSA"+ """;  
  230.        return getSignType;  
  231.     }  
  232.       
  233.       
  234.     void closeProgress(){  
  235.        try{  
  236.            if(mProgress != null){  
  237.               mProgress.dismiss ();  
  238.               mProgress = null;  
  239.            }  
  240.        } catch (Exception e){  
  241.           e.printStackTrace ();  
  242.        }  
  243.     }  
  244.       
  245.       
  246.     String getOrderInfo(double position){  
  247.      
  248.        String strOrderInfo = "partner=" + """ +PartnerConfig.PARTNER + """;  
  249.        strOrderInfo += "&";  
  250.        strOrderInfo += "seller=" + """ +PartnerConfig.SELLER + """;  
  251.        strOrderInfo += "&";  
  252.        strOrderInfo += "out_trade_no=" + """ +get_order_id () + """;  
  253.        strOrderInfo += "&";  
  254.          
  255.        //这里是显示到支付宝支付界面上的付费信息提示(这里一定要严格按照此格式填写)  
  256.        strOrderInfo += "subject=" + ""猫币"";  
  257.        strOrderInfo += "&";  
  258.        strOrderInfo += "body=" + ""购买猫币"";  
  259.        strOrderInfo += "&";  
  260.        strOrderInfo += "total_fee=" + """ + position +""";  
  261.        strOrderInfo += "&";  
  262.        strOrderInfo += "notify_url=" + """ +"http://notify.java.jpxx.org/index.jsp" + """;  
  263.        return strOrderInfo;  
  264.     }  
  265.       
  266.       
  267.     String sign (StringsignType, String content){  
  268.        return Rsa.sign (content,PartnerConfig.RSA_PRIVATE);  
  269.     }  
  270.       
  271.      
  272.     public booleanis_can_internet (final Context context){  
  273.        try{  
  274.           ConnectivityManager manger = (ConnectivityManager)context.getSystemService (Context.CONNECTIVITY_SERVICE);  
  275.           NetworkInfo info = manger.getActiveNetworkInfo ();  
  276.             
  277.            return(info != null && info.isConnected());  
  278.        } catch (Exception e){  
  279.         
  280.            returnfalse;  
  281.        }  
  282.     }  
  283.       
  284.      
  285.     public Stringget_order_id (){  
  286.        long ran1 = get_round (11119999);  
  287.        long ran2 = get_round (11119999);  
  288.          
  289.        //注掉的这里是返回的渠道号(我们用的友盟)+随机数和当前系统时间组合  
  290.        //return android_get_umeng_channel () + "_" +ran1 + System.currentTimeMillis () + ran2;  
  291.        return "_"+ran1 + System.currentTimeMillis () +ran2;  
  292.     }  
  293.       
  294.      
  295.     public long get_round(int min, int max){  
  296.        return Math.round (Math.random () * (max - min)+ min);  
  297.     }  
  298.       
  299.       
  300.     =================================================================================================  
  301.    //   
  302.     // 支付宝不用动的  
  303.     //==================================================================================================  
  304.     public final classAlixId {  
  305.        public static final int BASE_ID = 0;  
  306.        public static final int RQF_PAY = BASE_ID +1;  
  307.        public static final int RQF_INSTALL_CHECK =RQF_PAY + 1;  
  308.     }  
  309.       
  310.     final class AlixDefine{  
  311.        public static final String IMEI = "imei";  
  312.        public static final String IMSI = "imsi";  
  313.        public static final String KEY = "key";  
  314.        public static final String USER_AGENT ="user_agent";  
  315.        public static final String VERSION ="version";  
  316.        public static final String DEVICE ="device";  
  317.        public static final String SID = "sid";  
  318.        public static final String partner ="partner";  
  319.        public static final String charset ="charset";  
  320.        public static final String sign_type ="sign_type";  
  321.        public static final String sign = "sign";  
  322.        public static final String URL = "URL";  
  323.        public static final String split ="&";  
  324.        public static final String AlixPay ="AlixPay";  
  325.        public static final String action ="action";  
  326.        public static final String actionUpdate ="update";  
  327.        public static final String data = "data";  
  328.        public static final String platform ="platform";  
  329.     }  
  330.       
  331.     public static finalclass Base64 {  
  332.        static private final int BASELENGTH = 128;  
  333.        static private final int LOOKUPLENGTH =64;  
  334.        static private final int TWENTYFOURBITGROUP =24;  
  335.        static private final int EIGHTBIT = 8;  
  336.        static private final int SIXTEENBIT = 16;  
  337.        static private final int FOURBYTE = 4;  
  338.        static private final int SIGN = -128;  
  339.        static private final char PAD = '=';  
  340.        static private final boolean fDebug =false;  
  341.        static final private byte[] base64Alphabet = newbyte[BASELENGTH];  
  342.        static final private char[] lookUpBase64Alphabet= new char[LOOKUPLENGTH];  
  343.        static{  
  344.            for (int i= 0; i < BASELENGTH; ++i){  
  345.               base64Alphabet[i] = -1;  
  346.            }  
  347.            for (int i= 'Z'; i >= 'A'; i--){  
  348.               base64Alphabet[i] = (byte) (i- 'A');  
  349.            }  
  350.            for (int i= 'z'; i >= 'a'; i--){  
  351.               base64Alphabet[i] = (byte) (i- 'a' + 26);  
  352.            }  
  353.            for (int i= '9'; i >= '0'; i--){  
  354.               base64Alphabet[i] = (byte) (i- '0' + 52);  
  355.            }  
  356.           base64Alphabet['+'] = 62;  
  357.           base64Alphabet['/'] = 63;  
  358.            for (int i= 0; i <= 25; i++){  
  359.               lookUpBase64Alphabet[i] =(char) ('A' + i);  
  360.            }  
  361.            for (int i= 26, j = 0; i <= 51; i++, j++){  
  362.               lookUpBase64Alphabet[i] =(char) ('a' + j);  
  363.            }  
  364.            for (int i= 52, j = 0; i <= 61; i++, j++){  
  365.               lookUpBase64Alphabet[i] =(char) ('0' + j);  
  366.            }  
  367.           lookUpBase64Alphabet[62] = (char'+';  
  368.           lookUpBase64Alphabet[63] = (char'/';  
  369.        }  
  370.          
  371.          
  372.        private static boolean isWhiteSpace (charoctect){  
  373.            return(octect == 0x20 || octect == 0xd || octect == 0xa || octect ==0x9);  
  374.        }  
  375.          
  376.          
  377.        private static boolean isPad (charoctect){  
  378.            return(octect == PAD);  
  379.        }  
  380.          
  381.          
  382.        private static boolean isData (charoctect){  
  383.            return(octect < BASELENGTH&& base64Alphabet[octect] !=-1);  
  384.        }  
  385.          
  386.          
  387.         
  388.        public static String encode (byte[]binaryData){  
  389.            if(binaryData == null){  
  390.               return null;  
  391.            }  
  392.            intlengthDataBits = binaryData.length * EIGHTBIT;  
  393.            if(lengthDataBits == 0){  
  394.               return "";  
  395.            }  
  396.            intfewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;  
  397.            intnumberTriplets = lengthDataBits / TWENTYFOURBITGROUP;  
  398.            intnumberQuartet = fewerThan24bits != 0? numberTriplets + 1 :numberTriplets;  
  399.            charencodedData[] = null;  
  400.           encodedData = new char[numberQuartet * 4];  
  401.            byte k =0, l = 0, b1 = 0, b2 = 0, b3 = 0;  
  402.            intencodedIndex = 0;  
  403.            intdataIndex = 0;  
  404.            if(fDebug){  
  405.               System.out.println ("numberof triplets = " + numberTriplets);  
  406.            }  
  407.            for (int i= 0; i < numberTriplets; i++){  
  408.               b1 =binaryData[dataIndex++];  
  409.               b2 =binaryData[dataIndex++];  
  410.               b3 =binaryData[dataIndex++];  
  411.               if (fDebug){  
  412.                  System.out.println ("b1= " + b1 + ", b2= " + b2+ ", b3= " + b3);  
  413.               }  
  414.               l = (byte) (b2& 0x0f);  
  415.               k = (byte) (b1& 0x03);  
  416.               byte val1 = ((b1& SIGN) == 0)? (byte) (b1>> 2) : (byte) ((b1)>> 2 ^ 0xc0);  
  417.               byte val2 = ((b2& SIGN) == 0)? (byte) (b2>> 4) : (byte) ((b2)>> 4 ^ 0xf0);  
  418.               byte val3 = ((b3& SIGN) == 0)? (byte) (b3>> 6) : (byte) ((b3)>> 6 ^ 0xfc);  
  419.               if (fDebug){  
  420.                  System.out.println ("val2 = " + val2);  
  421.                  System.out.println ("k4   = " +(k << 4));  
  422.                  System.out.println ("vak  = " +(val2 | (k << 4)));  
  423.               }  
  424.               encodedData[encodedIndex++] =lookUpBase64Alphabet[val1];  
  425.               encodedData[encodedIndex++] =lookUpBase64Alphabet[val2 | (k <<4)];  
  426.               encodedData[encodedIndex++] =lookUpBase64Alphabet[(l << 2) |val3];  
  427.               encodedData[encodedIndex++] =lookUpBase64Alphabet[b3 & 0x3f];  
  428.            }  
  429.            // formintegral number of 6-bit groups  
  430.            if(fewerThan24bits == EIGHTBIT){  
  431.               b1 =binaryData[dataIndex];  
  432.               k = (byte) (b1& 0x03);  
  433.               if (fDebug){  
  434.                  System.out.println ("b1=" + b1);  
  435.                  System.out.println("b1<<2 = " + (b1>> 2));  
  436.               }  
  437.               byte val1 = ((b1& SIGN) == 0)? (byte) (b1>> 2) : (byte) ((b1)>> 2 ^ 0xc0);  
  438.               encodedData[encodedIndex++] =lookUpBase64Alphabet[val1];  
  439.               encodedData[encodedIndex++] =lookUpBase64Alphabet[k << 4];  
  440.               encodedData[encodedIndex++] =PAD;  
  441.               encodedData[encodedIndex++] =PAD;  
  442.            } else if(fewerThan24bits == SIXTEENBIT){  
  443.               b1 =binaryData[dataIndex];  
  444.               b2 = binaryData[dataIndex +1];  
  445.               l = (byte) (b2& 0x0f);  
  446.               k = (byte) (b1& 0x03);  
  447.               byte val1 = ((b1& SIGN) == 0)? (byte) (b1>> 2) : (byte) ((b1)>> 2 ^ 0xc0);  
  448.               byte val2 = ((b2& SIGN) == 0)? (byte) (b2>> 4) : (byte) ((b2)>> 4 ^ 0xf0);  
  449.               encodedData[encodedIndex++] =lookUpBase64Alphabet[val1];  
  450.               encodedData[encodedIndex++] =lookUpBase64Alphabet[val2 | (k <<4)];  
  451.               encodedData[encodedIndex++] =lookUpBase64Alphabet[l << 2];  
  452.               encodedData[encodedIndex++] =PAD;  
  453.            }  
  454.            return newString (encodedData);  
  455.        }  
  456.          
  457.          
  458.         
  459.        public static byte[] decode (Stringencoded){  
  460.            if(encoded == null){  
  461.               return null;  
  462.            }  
  463.            char[]base64Data = encoded.toCharArray ();  
  464.            // removewhite spaces  
  465.            int len =removeWhiteSpace (base64Data);  
  466.            if (len %FOURBYTE != 0){  
  467.               return null;// should bedivisible by four  
  468.            }  
  469.            intnumberQuadruple = (len / FOURBYTE);  
  470.            if(numberQuadruple == 0){  
  471.               return new byte[0];  
  472.            }  
  473.            bytedecodedData[] = null;  
  474.            byte b1 =0, b2 = 0, b3 = 0, b4 = 0;  
  475.            char d1 =0, d2 = 0, d3 = 0, d4 = 0;  
  476.            int i =0;  
  477.            intencodedIndex = 0;  
  478.            intdataIndex = 0;  
  479.           decodedData = new byte[(numberQuadruple) * 3];  
  480.            for (; i< numberQuadruple - 1; i++){  
  481.               if (!isData ((d1 =base64Data[dataIndex++])) || !isData ((d2 =base64Data[dataIndex++])) || !isData ((d3 =base64Data[dataIndex++])) || !isData ((d4 =base64Data[dataIndex++]))){  
  482.                  return null;  
  483.               }// if found "no data" justreturn null  
  484.               b1 =base64Alphabet[d1];  
  485.               b2 =base64Alphabet[d2];  
  486.               b3 =base64Alphabet[d3];  
  487.               b4 =base64Alphabet[d4];  
  488.               decodedData[encodedIndex++] =(byte) (b1 << 2 | b2>> 4);  
  489.               decodedData[encodedIndex++] =(byte) (((b2 & 0xf)<< 4) | ((b3>> 2) & 0xf));  
  490.               decodedData[encodedIndex++] =(byte) (b3 << 6 | b4);  
  491.            }  
  492.            if(!isData ((d1 = base64Data[dataIndex++])) || !isData ((d2 =base64Data[dataIndex++]))){  
  493.               return null;// if found "nodata" just return null  
  494.            }  
  495.            b1 =base64Alphabet[d1];  
  496.            b2 =base64Alphabet[d2];  
  497.            d3 =base64Data[dataIndex++];  
  498.            d4 =base64Data[dataIndex++];  
  499.            if(!isData ((d3)) || !isData ((d4))){// Check if they are PADcharacters  
  500.               if (isPad (d3)&& isPad (d4)){  
  501.                  if ((b2 & 0xf) != 0)// last 4bits should be zero  
  502.                  {  
  503.                      returnnull;  
  504.                  }  
  505.                  byte[] tmp = new byte[i * 3 + 1];  
  506.                  System.arraycopy (decodedData, 0, tmp, 0, i *3);  
  507.                  tmp[encodedIndex] = (byte) (b1<< 2 | b2>> 4);  
  508.                  return tmp;  
  509.               } else if (!isPad (d3)&& isPad (d4)){  
  510.                  b3 = base64Alphabet[d3];  
  511.                  if ((b3 & 0x3) != 0)// last 2bits should be zero  
  512.                  {  
  513.                      returnnull;  
  514.                  }  
  515.                  byte[] tmp = new byte[i * 3 + 2];  
  516.                  System.arraycopy (decodedData, 0, tmp, 0, i *3);  
  517.                  tmp[encodedIndex++] = (byte) (b1<< 2 | b2>> 4);  
  518.                  tmp[encodedIndex] = (byte) (((b2& 0xf) << 4) | ((b3>> 2) & 0xf));  
  519.                  return tmp;  
  520.               } else{  
  521.                  return null;  
  522.               }  
  523.            } else//No PAD e.g 3cQl  
  524.               b3 =base64Alphabet[d3];  
  525.               b4 =base64Alphabet[d4];  
  526.               decodedData[encodedIndex++] =(byte) (b1 << 2 | b2>> 4);  
  527.               decodedData[encodedIndex++] =(byte) (((b2 & 0xf)<< 4) | ((b3>> 2) & 0xf));  
  528.               decodedData[encodedIndex++] =(byte) (b3 << 6 | b4);  
  529.            }  
  530.            returndecodedData;  
  531.        }  
  532.          
  533.          
  534.         
  535.        private static int removeWhiteSpace (char[]data){  
  536.            if (data== null){  
  537.               return 0;  
  538.            }  
  539.            // countcharacters that's not whitespace  
  540.            intnewSize = 0;  
  541.            int len =data.length;  
  542.            for (int i= 0; i < len; i++){  
  543.               if (!isWhiteSpace(data[i])){  
  544.                  data[newSize++] = data[i];  
  545.               }  
  546.            }  
  547.            returnnewSize;  
  548.        }  
  549.     }  
  550.       
  551.     public static classBaseHelper {  
  552.         
  553.        public static String convertStreamToString(InputStream is){  
  554.           BufferedReader reader = new BufferedReader (new InputStreamReader(is));  
  555.           StringBuilder sb = new StringBuilder ();  
  556.            Stringline = null;  
  557.            try{  
  558.               while ((line =reader.readLine ()) != null){  
  559.                  sb.append (line);  
  560.               }  
  561.            } catch(IOException e){  
  562.               e.printStackTrace ();  
  563.            }finally{  
  564.               try{  
  565.                  is.close ();  
  566.               } catch (IOExceptione){  
  567.                  e.printStackTrace ();  
  568.               }  
  569.            }  
  570.            returnsb.toString ();  
  571.        }  
  572.          
  573.          
  574.         
  575.        public static void showDialog (Activity context,String strTitle, String strText, int icon){  
  576.           AlertDialog.Builder tDialog = new AlertDialog.Builder(context);  
  577.           tDialog.setIcon (icon);  
  578.           tDialog.setTitle (strTitle);  
  579.           tDialog.setMessage (strText);  
  580.           tDialog.setPositiveButton ("确定"null);  
  581.           tDialog.show ();  
  582.        }  
  583.          
  584.          
  585.         
  586.        public static void log (String tag, Stringinfo){  
  587.            //Log.d(tag, info);  
  588.        }  
  589.          
  590.          
  591.         
  592.        public static void chmod (String permission,String path){  
  593.            try{  
  594.               String command = "chmod " +permission + " " + path;  
  595.               Runtime runtime =Runtime.getRuntime ();  
  596.               runtime.exec (command);  
  597.            } catch(IOException e){  
  598.               e.printStackTrace ();  
  599.            }  
  600.        }  
  601.          
  602.          
  603.        //  
  604.        // show the progress bar.  
  605.         
  606.        public static ProgressDialog showProgress(Context context, CharSequence title, CharSequence message, booleanindeterminate, boolean cancelable){  
  607.           ProgressDialog dialog = new ProgressDialog (context);  
  608.           dialog.setTitle (title);  
  609.           dialog.setMessage (message);  
  610.           dialog.setIndeterminate (indeterminate);  
  611.           dialog.setCancelable (false);  
  612.            //dialog.setDefaultButton(false);  
  613.           dialog.setOnCancelListener (new Fiap.AlixOnCancelListener((Activity) context));  
  614.           dialog.show ();  
  615.            returndialog;  
  616.        }  
  617.          
  618.          
  619.         
  620.        public static JSONObject string2JSON (Stringstr, String split){  
  621.            JSONObjectjson = new JSONObject ();  
  622.            try{  
  623.               String[] arrStr = str.split(split);  
  624.               for (int i = 0; i< arrStr.length; i++){  
  625.                  String[] arrKeyValue = arrStr[i].split("=");  
  626.                  json.put (arrKeyValue[0], arrStr[i].substring(arrKeyValue[0].length () + 1));  
  627.               }  
  628.            } catch(Exception e){  
  629.               e.printStackTrace ();  
  630.            }  
  631.            returnjson;  
  632.        }  
  633.     }  
  634.       
  635.     public class Constant{  
  636.        public final static String server_url ="https://msp.alipay.com/x.htm";  
  637.     }  
  638.       
  639.     public classMobileSecurePayer {  
  640.        Integer lock = 0;  
  641.        IAlixPay mAlixPay = null;  
  642.        boolean mbPaying = false;  
  643.        Activity mActivity = null;  
  644.        // 和安全支付服务建立连接  
  645.        private ServiceConnection mAlixPayConnection =new ServiceConnection (){  
  646.            publicvoid onServiceConnected (ComponentName className, IBinderservice){  
  647.               //  
  648.               // wake up the binder tocontinue.  
  649.               // 获得通信通道  
  650.               synchronized (lock){  
  651.                  mAlixPay = IAlixPay.Stub.asInterface(service);  
  652.                  lock.notify ();  
  653.               }  
  654.            }  
  655.             
  656.             
  657.            publicvoid onServiceDisconnected (ComponentName className){  
  658.               mAlixPay = null;  
  659.            }  
  660.        };  
  661.          
  662.          
  663.         
  664.        public boolean pay (final String strOrderInfo,final Handler callback, final int myWhat, final Activityactivity){  
  665.            if(mbPaying)  
  666.               return false;  
  667.            mbPaying =true;  
  668.            //  
  669.            mActivity= activity;  
  670.            // bindthe service.  
  671.            //绑定服务  
  672.            if(mAlixPay == null){  
  673.               // 绑定安全支付服务需要获取上下文环境,  
  674.               //如果绑定不成功使用mActivity.getApplicationContext().bindService  
  675.               // 解绑时同理  
  676.              mActivity.getApplicationContext ().bindService (new Intent(IAlixPay.class.getName ()), mAlixPayConnection,Context.BIND_AUTO_CREATE);  
  677.            }  
  678.            // elseok.  
  679.            //实例一个线程来进行支付  
  680.            new Thread(new Runnable (){  
  681.               public void run (){  
  682.                  try{  
  683.                      // waitfor the service bind operation to completely  
  684.                      //finished.  
  685.                      // Note:this is important,otherwise the next mAlixPay.Pay()  
  686.                      // willfail.  
  687.                      //等待安全支付服务绑定操作结束  
  688.                      //注意:这里很重要,否则mAlixPay.Pay()方法会失败  
  689.                     synchronized (lock){  
  690.                         if (mAlixPay == null)  
  691.                            lock.wait ();  
  692.                      }  
  693.                      //register a Callback for the service.  
  694.                      //为安全支付服务注册一个回调  
  695.                     mAlixPay.registerCallback (mCallback);  
  696.                      // callthe MobileSecurePay service.  
  697.                      //调用安全支付服务的pay方法  
  698.                      StringstrRet = mAlixPay.Pay (strOrderInfo);  
  699.                      // set theflag to indicate that we have finished.  
  700.                      //unregister the Callback, and unbind the service.  
  701.                      //将mbPaying置为false,表示支付结束  
  702.                      //移除回调的注册,解绑安全支付服务  
  703.                      mbPaying =false;  
  704.                     mAlixPay.unregisterCallback (mCallback);  
  705.                     mActivity.getApplicationContext ().unbindService(mAlixPayConnection);  
  706.                      // sendthe result back to caller.  
  707.                      //发送交易结果  
  708.                      Messagemsg = new Message ();  
  709.                      msg.what =myWhat;  
  710.                      msg.obj =strRet;  
  711.                     callback.sendMessage (msg);  
  712.                  } catch (Exception e){  
  713.                     e.printStackTrace ();  
  714.                      // sendthe result back to caller.  
  715.                      //发送交易结果  
  716.                      Messagemsg = new Message ();  
  717.                      msg.what =myWhat;  
  718.                      msg.obj =e.toString ();  
  719.                     callback.sendMessage (msg);  
  720.                  }  
  721.               }  
  722.            }).start();  
  723.            returntrue;  
  724.        }  
  725.          
  726.          
  727.         
  728.        private IRemoteServiceCallback mCallback = newIRemoteServiceCallback.Stub (){  
  729.             
  730.            publicvoid startActivity (String packageName, String className, intiCallingPid, Bundle bundle) throws RemoteException{  
  731.               Intent intent = new Intent(Intent.ACTION_MAIN, null);  
  732.               if (bundle == null)  
  733.                  bundle = new Bundle ();  
  734.               // else ok.  
  735.               try{  
  736.                  bundle.putInt ("CallingPid", iCallingPid);  
  737.                  intent.putExtras (bundle);  
  738.               } catch (Exception e){  
  739.                  e.printStackTrace ();  
  740.               }  
  741.               intent.setClassName(packageName, className);  
  742.               mActivity.startActivity(intent);  
  743.            }  
  744.   
  745.           @Override  
  746.            publicboolean isHideLoadingScreen () throws RemoteException{  
  747.               return false;  
  748.            }  
  749.   
  750.           @Override  
  751.            publicvoid payEnd (boolean arg0, String arg1) throwsRemoteException{  
  752.                 
  753.            }  
  754.        };  
  755.     }  
  756.       
  757.     public classMobileSecurePayHelper {  
  758.        static final String TAG ="MobileSecurePayHelper";  
  759.        private ProgressDialog mProgress = null;  
  760.        Context mContext = null;  
  761.          
  762.          
  763.        public MobileSecurePayHelper (Contextcontext){  
  764.           this.mContext = context;  
  765.        }  
  766.          
  767.          
  768.         
  769.        public boolean detectMobile_sp (){  
  770.            booleanisMobile_spExist = isMobile_spExist ();  
  771.            if(!isMobile_spExist){  
  772.               // 获取系统缓冲绝对路径获取/data/data//cache目录  
  773.               File cacheDir =mContext.getCacheDir ();  
  774.               final String cachePath =cacheDir.getAbsolutePath () + "/temp.apk";  
  775.               mProgress =BaseHelper.showProgress (mContext, null"正在检测安全支付服务版本"false,true);  
  776.               // 实例新线程检测是否有新版本进行下载  
  777.               new Thread (new Runnable(){  
  778.                  public void run (){  
  779.                      //检测是否有新的版本。  
  780.                      StringnewApkdlUrl = checkNewUpdate ();  
  781.                     closeProgress ();  
  782.                      //动态下载  
  783.                      if(newApkdlUrl != null)  
  784.                         retrieveApkFromNet (mContext,newApkdlUrl, cachePath);  
  785.                     showInstallConfirmDialog (mContext, cachePath);  
  786.                  }  
  787.               }).start ();  
  788.            }  
  789.            returnisMobile_spExist;  
  790.        }  
  791.          
  792.          
  793.         
  794.        public void showInstallConfirmDialog (finalContext context, final String cachePath){  
  795.           Looper.prepare ();  
  796.           AlertDialog.Builder tDialog = new AlertDialog.Builder(context);  
  797.           tDialog.setTitle ("安装提示");  
  798.           tDialog.setMessage("为保证您的交易安全,需要您安装支付宝安全支付服务,才能进行付款。\n\n点击确定,立即安装。");  
  799.           tDialog.setPositiveButton ("确定", newDialogInterface.OnClickListener (){  
  800.               public void onClick(DialogInterface dialog, int which){  
  801.                  //  
  802.                  // 修改apk权限  
  803.                  BaseHelper.chmod ("777", cachePath);  
  804.                  //  
  805.                  // install the apk.  
  806.                  // 安装安全支付服务APK  
  807.                  Intent intent = new Intent(Intent.ACTION_VIEW);  
  808.                  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  809.                  intent.setDataAndType (Uri.parse ("file://" +cachePath), "application/vnd.android.package-archive");  
  810.                  context.startActivity (intent);  
  811.               }  
  812.            });  
  813.           tDialog.setNegativeButton ("取消", newDialogInterface.OnClickListener (){  
  814.               public void onClick(DialogInterface dialog, int which){}  
  815.            });  
  816.           tDialog.show ();  
  817.           Looper.loop ();  
  818.        }  
  819.          
  820.          
  821.         
  822.        public boolean isMobile_spExist (){  
  823.           PackageManager manager = mContext.getPackageManager ();  
  824.           List<PackageInfo> pkgList =manager.getInstalledPackages (0);  
  825.            for (int i= 0; i < pkgList.size (); i++){  
  826.               PackageInfo pI = pkgList.get(i);  
  827.               if(pI.packageName.equalsIgnoreCase ("com.alipay.android.app"))  
  828.                  return true;  
  829.            }  
  830.            returnfalse;  
  831.        }  
  832.          
  833.          
  834.         
  835.        public boolean retrieveApkFromAssets (Contextcontext, String fileName, String path){  
  836.            booleanbRet = false;  
  837.            try{  
  838.               InputStream is =context.getAssets ().open (fileName);  
  839.               File file = new File(path);  
  840.               file.createNewFile ();  
  841.               FileOutputStream fos = newFileOutputStream (file);  
  842.               byte[] temp = newbyte[1024];  
  843.               int i = 0;  
  844.               while ((i = is.read (temp))> 0){  
  845.                  fos.write (temp, 0, i);  
  846.               }  
  847.               fos.close ();  
  848.               is.close ();  
  849.               bRet = true;  
  850.            } catch(IOException e){  
  851.               e.printStackTrace ();  
  852.            }  
  853.            returnbRet;  
  854.        }  
  855.          
  856.          
  857.         
  858.        public PackageInfo getApkInfo (Context context,String archiveFilePath){  
  859.           PackageManager pm = context.getPackageManager ();  
  860.           PackageInfo apkInfo = pm.getPackageArchiveInfo (archiveFilePath,PackageManager.GET_META_DATA);  
  861.            returnapkInfo;  
  862.        }  
  863.          
  864.          
  865.         
  866.        public String checkNewUpdate (){  
  867.            String url= null;  
  868.            try{  
  869. //              JSONObject resp =sendCheckNewUpdate (packageInfo.versionName);  
  870.                JSONObjectresp = sendCheckNewUpdate("1.0.0");  
  871.               if (resp.getString("needUpdate").equalsIgnoreCase ("true")){  
  872.                  url = resp.getString ("updateUrl");  
  873.               }  
  874.               // else ok.  
  875.            } catch(Exception e){  
  876.               e.printStackTrace ();  
  877.            }  
  878.            returnurl;  
  879.        }  
  880.          
  881.          
  882.         
  883.        public JSONObject sendCheckNewUpdate (StringversionName){  
  884.            JSONObjectobjResp = null;  
  885.            try{  
  886.               JSONObject req = newJSONObject ();  
  887.               req.put (AlixDefine.action,AlixDefine.actionUpdate);  
  888.               JSONObject data = newJSONObject ();  
  889.               data.put(AlixDefine.platform, "android");  
  890.               data.put (AlixDefine.VERSION,versionName);  
  891.               data.put (AlixDefine.partner,"");  
  892.               req.put (AlixDefine.data,data);  
  893.               objResp = sendRequest(req.toString ());  
  894.            } catch(JSONException e){  
  895.               e.printStackTrace ();  
  896.            }  
  897.            returnobjResp;  
  898.        }  
  899.          
  900.          
  901.         
  902.        public JSONObject sendRequest (final Stringcontent){  
  903.           NetworkManager nM = new NetworkManager (this.mContext);  
  904.            //  
  905.            JSONObjectjsonResponse = null;  
  906.            try{  
  907.               String response = null;  
  908.               synchronized (nM){  
  909.                  //  
  910.                  response = nM.SendAndWaitResponse (content,Constant.server_url);  
  911.               }  
  912.               jsonResponse = new JSONObject(response);  
  913.            } catch(Exception e){  
  914.               e.printStackTrace ();  
  915.            }  
  916.            //  
  917.            if(jsonResponse != null)  
  918.               BaseHelper.log (TAG,jsonResponse.toString ());  
  919.            returnjsonResponse;  
  920.        }  
  921.          
  922.          
  923.         
  924.        public boolean retrieveApkFromNet (Contextcontext, String strurl, String filename){  
  925.            booleanbRet = false;  
  926.            try{  
  927.               NetworkManager nM = newNetworkManager (this.mContext);  
  928.               bRet = nM.urlDownloadToFile(context, strurl, filename);  
  929.            } catch(Exception e){  
  930.               e.printStackTrace ();  
  931.            }  
  932.            returnbRet;  
  933.        }  
  934.          
  935.          
  936.        //  
  937.        // close the progress bar  
  938.        void closeProgress (){  
  939.            try{  
  940.               if (mProgress != null){  
  941.                  mProgress.dismiss ();  
  942.                  mProgress = null;  
  943.               }  
  944.            } catch(Exception e){  
  945.               e.printStackTrace ();  
  946.            }  
  947.        }  
  948.     }  
  949.       
  950.     public classNetworkManager {  
  951.        static final String TAG ="NetworkManager";  
  952.        private int connectTimeout = 30 * 1000;  
  953.        private int readTimeout = 30 * 1000;  
  954.        Proxy mProxy = null;  
  955.        Context mContext;  
  956.          
  957.          
  958.        public NetworkManager (Context context){  
  959.           this.mContext = context;  
  960.           setDefaultHostnameVerifier ();  
  961.        }  
  962.          
  963.          
  964.         
  965.        @SuppressWarnings ("deprecation")  
  966.        private void detectProxy (){  
  967.           ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService (Context.CONNECTIVITY_SERVICE);  
  968.           NetworkInfo ni = cm.getActiveNetworkInfo ();  
  969.            if (ni !=null && ni.isAvailable ()&& ni.getType () ==ConnectivityManager.TYPE_MOBILE){  
  970.               String proxyHost =android.net.Proxy.getDefaultHost ();  
  971.               int port =android.net.Proxy.getDefaultPort ();  
  972.               if (proxyHost != null){  
  973.                  final InetSocketAddress sa = newInetSocketAddress (proxyHost, port);  
  974.                  mProxy = new Proxy (Proxy.Type.HTTP, sa);  
  975.               }  
  976.            }  
  977.        }  
  978.          
  979.          
  980.        private void setDefaultHostnameVerifier(){  
  981.            //  
  982.           HostnameVerifier hv = new HostnameVerifier (){  
  983.               public boolean verify (Stringhostname, SSLSession session){  
  984.                  return true;  
  985.               }  
  986.            };  
  987.           HttpsURLConnection.setDefaultHostnameVerifier (hv);  
  988.        }  
  989.          
  990.          
  991.         
  992.        public String SendAndWaitResponse (StringstrReqData, String strUrl){  
  993.            //  
  994.           detectProxy ();  
  995.            StringstrResponse = null;  
  996.           ArrayList<BasicNameValuePair> pairs =new ArrayList<BasicNameValuePair>();  
  997.            pairs.add(new BasicNameValuePair ("requestData", strReqData));  
  998.           HttpURLConnection httpConnect = null;  
  999.           UrlEncodedFormEntity p_entity;  
  1000.            try{  
  1001.               p_entity = newUrlEncodedFormEntity (pairs, "utf-8");  
  1002.               URL url = new URL(strUrl);  
  1003.               if (mProxy != null){  
  1004.                  httpConnect = (HttpURLConnection)url.openConnection (mProxy);  
  1005.               } else{  
  1006.                  httpConnect = (HttpURLConnection)url.openConnection ();  
  1007.               }  
  1008.               httpConnect.setConnectTimeout(connectTimeout);  
  1009.               httpConnect.setReadTimeout(readTimeout);  
  1010.               httpConnect.setDoOutput(true);  
  1011.              httpConnect.addRequestProperty ("Content-type","application/x-www-form-urlencoded;charset=utf-8");  
  1012.               httpConnect.connect ();  
  1013.               OutputStream os =httpConnect.getOutputStream ();  
  1014.               p_entity.writeTo (os);  
  1015.               os.flush ();  
  1016.               InputStream content =httpConnect.getInputStream ();  
  1017.               strResponse =BaseHelper.convertStreamToString (content);  
  1018.               BaseHelper.log (TAG,"response " + strResponse);  
  1019.            } catch(IOException e){  
  1020.               e.printStackTrace ();  
  1021.            }finally{  
  1022.               httpConnect.disconnect();  
  1023.            }  
  1024.            returnstrResponse;  
  1025.        }  
  1026.          
  1027.          
  1028.         
  1029.        public boolean urlDownloadToFile (Contextcontext, String strurl, String path){  
  1030.            booleanbRet = false;  
  1031.            //  
  1032.           detectProxy ();  
  1033.            try{  
  1034.               URL url = new URL(strurl);  
  1035.               HttpURLConnection conn =null;  
  1036.               if (mProxy != null){  
  1037.                  conn = (HttpURLConnection) url.openConnection(mProxy);  
  1038.               } else{  
  1039.                  conn = (HttpURLConnection) url.openConnection();  
  1040.               }  
  1041.               conn.setConnectTimeout(connectTimeout);  
  1042.               conn.setReadTimeout(readTimeout);  
  1043.               conn.setDoInput (true);  
  1044.               conn.connect ();  
  1045.               InputStream is =conn.getInputStream ();  
  1046.               File file = new File(path);  
  1047.               file.createNewFile ();  
  1048.               FileOutputStream fos = newFileOutputStream (file);  
  1049.               byte[] temp = newbyte[1024];  
  1050.               int i = 0;  
  1051.               while ((i = is.read (temp))> 0){  
  1052.                  fos.write (temp, 0, i);  
  1053.               }  
  1054.               fos.close ();  
  1055.               is.close ();  
  1056.               bRet = true;  
  1057.            } catch(IOException e){  
  1058.               e.printStackTrace ();  
  1059.            }  
  1060.            returnbRet;  
  1061.        }  
  1062.     }  
  1063.       
  1064.     public classResultChecker {  
  1065.        public static final int RESULT_INVALID_PARAM =0;  
  1066.        public static final int RESULT_CHECK_SIGN_FAILED= 1;  
  1067.        public static final intRESULT_CHECK_SIGN_SUCCEED = 2;  
  1068.        String mContent;  
  1069.          
  1070.          
  1071.        public ResultChecker (String content){  
  1072.           this.mContent = content;  
  1073.        }  
  1074.          
  1075.          
  1076.         
  1077.        int checkSign (){  
  1078.            int retVal= RESULT_CHECK_SIGN_SUCCEED;  
  1079.            try{  
  1080.               JSONObject objContent =BaseHelper.string2JSON (this.mContent, ";");  
  1081.               String result =objContent.getString ("result");  
  1082.               result = result.substring (1,result.length () - 1);  
  1083.               // 获取待签名数据  
  1084.               int iSignContentEnd =result.indexOf ("&sign_type=");  
  1085.               String signContent =result.substring (0, iSignContentEnd);  
  1086.               // 获取签名  
  1087.               JSONObject objResult =BaseHelper.string2JSON (result, "&");  
  1088.               String signType =objResult.getString ("sign_type");  
  1089.               signType = signType.replace(""", "");  
  1090.               String sign =objResult.getString ("sign");  
  1091.               sign = sign.replace (""","");  
  1092.               // 进行验签 返回验签结果  
  1093.               if (signType.equalsIgnoreCase("RSA")){  
  1094.                  if (!Rsa.doCheck (signContent, sign,PartnerConfig.RSA_ALIPAY_PUBLIC))  
  1095.                      retVal =RESULT_CHECK_SIGN_FAILED;  
  1096.               }  
  1097.            } catch(Exception e){  
  1098.               retVal =RESULT_INVALID_PARAM;  
  1099.               e.printStackTrace ();  
  1100.            }  
  1101.            returnretVal;  
  1102.        }  
  1103.     }  
  1104.       
  1105.     public static class Rsa{  
  1106.        public static final String SIGN_ALGORITHMS ="SHA1WithRSA";  
  1107.          
  1108.          
  1109.        public static String sign (String content,String privateKey){  
  1110.            Stringcharset = "utf-8";  
  1111.            try{  
  1112.               PKCS8EncodedKeySpec priPKCS8= new PKCS8EncodedKeySpec (Base64.decode (privateKey));  
  1113.               KeyFactory keyf =KeyFactory.getInstance ("RSA");  
  1114.               PrivateKey priKey =keyf.generatePrivate (priPKCS8);  
  1115.               java.security.Signaturesignature = java.security.Signature.getInstance(SIGN_ALGORITHMS);  
  1116.               signature.initSign(priKey);  
  1117.               signature.update(content.getBytes (charset));  
  1118.               byte[] signed =signature.sign ();  
  1119.               return Base64.encode(signed);  
  1120.            } catch(Exception e){  
  1121.               e.printStackTrace ();  
  1122.            }  
  1123.            returnnull;  
  1124.        }  
  1125.          
  1126.          
  1127.        public static boolean doCheck (String content,String sign, String publicKey){  
  1128.            try{  
  1129.               KeyFactory keyFactory =KeyFactory.getInstance ("RSA");  
  1130.               byte[] encodedKey =Base64.decode (publicKey);  
  1131.               PublicKey pubKey =keyFactory.generatePublic (new X509EncodedKeySpec(encodedKey));  
  1132.               java.security.Signaturesignature = java.security.Signature.getInstance(SIGN_ALGORITHMS);  
  1133.               signature.initVerify(pubKey);  
  1134.               signature.update(content.getBytes ("utf-8"));  
  1135.               boolean bverify =signature.verify (Base64.decode (sign));  
  1136.               return bverify;  
  1137.            } catch(Exception e){  
  1138.               e.printStackTrace ();  
  1139.            }  
  1140.            returnfalse;  
  1141.        }  
  1142.     }  
  1143. }  
0 0