Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 手机动态口令令牌实现思路与关键代码

編輯:關於 Android 程式設計

折腾了一天一夜,做出了这个小东西——安卓手机令牌。因为这套东西最终要给公司使用,涉及业务的部分不便展开,这里主要分享界面组织、与服务端通信、计时以及口令生成这几块通用思路。

整体功能构成

一个可用的动态令牌大致包含四部分:令牌界面(展示口令与倒计时)、Java 客户端与 C# 服务端的交互、倒计时与正计时逻辑、以及口令生成算法。真正难的其实不是逻辑,而是界面——这部分靠的是经验积累,我大概有一半时间花在了布局调优上。

界面布局

主体是一个 RelativeLayout,从上到下依次为:顶部标题区(图标 + 名称)、口令显示区(大号数字)、服务器时间与序列号信息行、操作按钮行(时间校准、操作说明)、底部公司信息。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/my_bg"
    android:gravity="center_horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <!-- 标题区 -->
    <LinearLayout android:id="@+id/activity_contact_li_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center">
        <ImageView android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
        <TextView android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="***"
            android:textSize="40sp" />
    </LinearLayout>

    <!-- 口令显示区 -->
    <LinearLayout android:id="@+id/activity_contact_li_mobilephone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/activity_contact_li_title"
        android:layout_marginTop="30dp"
        android:background="@drawable/table_mid_bg"
        android:gravity="center_vertical">
        <TextView android:id="@+id/number"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:gravity="center"
            android:text="123456"
            android:textScaleX="1.2"
            android:textSize="40sp" />
    </LinearLayout>

    <!-- 刷新提示 -->
    <LinearLayout android:id="@+id/activity_contact_li_times"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/activity_contact_li_mobilephone"
        android:layout_marginTop="17dp"
        android:gravity="center">
        <TextView android:id="@+id/textView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=">> 口令 "
            android:textColor="@color/listitem_blue" />
        <TextView android:id="@+id/textView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="22"
            android:textColor="@color/red" />
        <TextView android:id="@+id/textView8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" 秒后更新"
            android:textColor="@color/listitem_blue" />
    </LinearLayout>
</RelativeLayout>

与 C# 服务端通信

Android 与 .NET WebService 对接,最省事的办法是引入 ksoap2(ksoap2-android-assembly-2.4-jar-with-dependencies.jar)。调用流程很固定:构造 SoapObject、创建传输对象、准备 Envelope、call 出去、解析返回值。

private String getDateTime() throws Exception {
    SoapObject rpc = new SoapObject(NAMESPACE, GET_TIME_METHOD_NAME);
    AndroidHttpTransport ht = new AndroidHttpTransport(URL);
    ht.debug = true;

    SoapSerializationEnvelope envelope =
            new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.bodyOut = rpc;
    envelope.dotNet = true;
    envelope.setOutputSoapObject(rpc);

    try {
        ht.call(GET_TIME_SOAP_ACTION, envelope);
    } catch (Exception e) {
        UIHelper.ToastMessage(MainActivity.this, "未连接网络或网络异常");
    }

    SoapObject result = (SoapObject) envelope.bodyIn;
    SoapPrimitive detail =
            (SoapPrimitive) result.getProperty("GetDateTimeResult");
    return detail.toString();
}

注意 envelope.dotNet = true 这一行不能漏,否则解析 .NET 服务返回的报文会出问题。

倒计时与正计时

令牌的核心节奏是"倒计时到 0 → 重新取时间 → 刷新口令"。用 Handler 的延时消息实现最直观:

Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                recLen--;
                txtTextTimeBack.setText(recLen < 10 ? "0" + recLen : "" + recLen);
                if (recLen > 0) {
                    handler.sendMessageDelayed(handler.obtainMessage(1), 1000);
                } else {
                    handler.sendMessageDelayed(handler.obtainMessage(1), 1000);
                    // 时间归零:校准服务器时间并刷新口令
                    String dateTime = DateFormate.getDateTime();
                    txtDateTime.setText(dateTime);
                    turnTimeBack();
                    showTheNumber();
                }
                break;
        }
        super.handleMessage(msg);
    }
};

正计时不需要另写一套,只要在同一个倒计时逻辑里用 60 - recLen 换算即可,注意小于 10 时补前导零:

String ss = DateFormate.getStringFromDate(
        DateFormate.getDateFormString(txtDateTime.getText().toString()));
if (recLen > 50) {
    ss += "0" + (60 - recLen);
} else {
    ss += "" + (60 - recLen);
}
txtDateTime.setText(ss);

口令生成

这是整个令牌最关键的一环,具体算法涉及公司业务,这里只说通用做法:把序列号、时间戳和一段预置字符串混合,再做摘要运算。常用的摘要算法如 MD5 就足够了:

String key = String.valueOf((dateTimeLong ^ serialNumberLong));
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] digest = md5.digest(key.getBytes());
String result = /* 按需要的规则截取、格式化 */ null;

需要强调的是,无论用哪种摘要,客户端与服务端必须使用完全一致的时间基准和序列号,否则生成的口令永远校验不过——这也是为什么"时间校准"功能必不可少。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved