从智能手机捕获指纹并保存到文件

时间:2016-03-11 07:40:00

标签: java android xml android-studio

我正在做一个项目,我需要使用NFC连接将指纹扫描捕获的结果传输到本地服务器,然后从服务器接收答案。

到目前为止,我设法了解如何使用谷歌的API进行传输和扫描fringerprint,但问题是我无法获取扫描结果以将其发送给服务器以完成认证

我使用的是来自API23的谷歌指纹库。

MainActivity:

package com.gmtechnology.smartalarm;

import android.Manifest;
import android.app.KeyguardManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;


public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private static final String KEY_NAME = "main_key";
protected FingerprintManager fingerprintManager;
protected KeyguardManager keyguardManager;
private KeyStore keyStore;
protected KeyGenerator keyGenerator;
private Cipher cipher;
protected FingerprintManager.CryptoObject cryptoObject;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView state = (TextView) findViewById(R.id.state);

    FloatingActionButton lock = (FloatingActionButton) findViewById(R.id.lock);
    FloatingActionButton unlock = (FloatingActionButton) findViewById(R.id.unlock);
    FloatingActionButton start = (FloatingActionButton) findViewById(R.id.start);
    FloatingActionButton stop = (FloatingActionButton) findViewById(R.id.stop);

    PackageManager pm = this.getPackageManager();
    // Check whether NFC is available on device
    if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
        // NFC is not available on the device.
        Toast.makeText(this, "The device does not has NFC hardware",
                Toast.LENGTH_SHORT).show();
    }
    // Check whether device is running Android 4.1 or higher
    else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        // Android Beam feature is not supported.
        Toast.makeText(this, "Wrong android version",
                Toast.LENGTH_SHORT).show();
    }

    keyguardManager =
            (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
    fingerprintManager =
            (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);

    if (!keyguardManager.isKeyguardSecure()) {

        Toast.makeText(this,
                "Lock screen security not enabled in Settings",
                Toast.LENGTH_LONG).show();
        return;
    }

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.USE_FINGERPRINT) !=
            PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this,
                "Fingerprint authentication permission not enabled",
                Toast.LENGTH_LONG).show();

        return;
    }

    if (!fingerprintManager.hasEnrolledFingerprints()) {

        // This happens when no fingerprints are registered.
        Toast.makeText(this,
                "Register at least one fingerprint in Settings",
                Toast.LENGTH_LONG).show();
        return;
    }

    generateKey();

    if (cipherInit()) {
        cryptoObject = new FingerprintManager.CryptoObject(cipher);
        //cryptoObject == the scanned fingerprint
        FingerprintHandler helper = new FingerprintHandler(this);
        helper.startAuth(fingerprintManager, cryptoObject, lock, unlock, start, stop, state);
    }

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    state(1, lock, unlock, start, stop, state);
}

public void sendFile(View view) {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);

    String command = "command";

    if(!nfcAdapter.isEnabled()){

        Toast.makeText(this, "Please enable NFC.",
                Toast.LENGTH_SHORT).show();
        startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
    }

    else if(!nfcAdapter.isNdefPushEnabled()) {

        Toast.makeText(this, "Please enable Android Beam.",
                Toast.LENGTH_SHORT).show();
        startActivity(new Intent(Settings.ACTION_NFCSHARING_SETTINGS));
    }

    else {

        if(view.getId() == R.id.lock) {

            command = "lock";

        }

        else if(view.getId() == R.id.unlock) {

            command = "unlock";

        }

        else if(view.getId() == R.id.start) {

            command = "start";

        }

        else if(view.getId() == R.id.stop) {

            command = "stop";

        }

        NdefRecord ndefRecord = NdefRecord.createMime("text/plain", command.getBytes());
        NdefMessage ndefMessage = new NdefMessage(ndefRecord);

        String fileName = "wallpaper.png";

        // Retrieve the path to the user's public pictures directory
        File fileDirectory = Environment
                .getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES);

        // Create a new file using the specified directory and name
        File fileToTransfer = new File(fileDirectory, fileName);
        fileToTransfer.setReadable(true, false);

        nfcAdapter.setBeamPushUris(
                new Uri[]{Uri.fromFile(fileToTransfer)}, this);
        nfcAdapter.setNdefPushMessage(ndefMessage, this);
    }
}

protected void generateKey() {
    try {
        keyStore = KeyStore.getInstance("AndroidKeyStore");
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        keyGenerator = KeyGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_AES,
                "AndroidKeyStore");
    } catch (NoSuchAlgorithmException |
            NoSuchProviderException e) {
        throw new RuntimeException(
                "Failed to get KeyGenerator instance", e);
    }

    try {
        keyStore.load(null);
        keyGenerator.init(new
                KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT |
                        KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(
                        KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build());
        keyGenerator.generateKey();
    } catch (NoSuchAlgorithmException |
            InvalidAlgorithmParameterException
            | CertificateException | IOException e) {
        throw new RuntimeException(e);
    }
}

public boolean cipherInit() {
    try {
        cipher = Cipher.getInstance(
                KeyProperties.KEY_ALGORITHM_AES + "/"
                        + KeyProperties.BLOCK_MODE_CBC + "/"
                        + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    } catch (NoSuchAlgorithmException |
            NoSuchPaddingException e) {
        throw new RuntimeException("Failed to get Cipher", e);
    }

    try {
        keyStore.load(null);
        SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
                null);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return true;
    } catch (KeyPermanentlyInvalidatedException e) {
        return false;
    } catch (KeyStoreException | CertificateException
            | UnrecoverableKeyException | IOException
            | NoSuchAlgorithmException | InvalidKeyException e) {
        throw new RuntimeException("Failed to init Cipher", e);
    }
}


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}


public void state (int s, FloatingActionButton lock, FloatingActionButton unlock, FloatingActionButton start, FloatingActionButton stop, TextView state) {

    if (s == 1) {
        state.setText(R.string.scan);
        state.setTextColor(0xFF970E0E);
        lock.setEnabled(false);
        lock.hide();
        unlock.setEnabled(false);
        unlock.hide();
        start.setEnabled(false);
        start.hide();
        stop.setEnabled(false);
        stop.hide();
    }

    if (s == 2) {
        state.setText(R.string.done);
        state.setTextColor(0xFF149926);
        lock.setEnabled(true);
        lock.show();
        unlock.setEnabled(true);
        unlock.show();
        start.setEnabled(true);
        start.show();
        stop.setEnabled(true);
        stop.show();
    }

    if (s == 3) {
        state.setText(R.string.error);
        state.setTextColor(0xFF970E0E);
        lock.setEnabled(false);
        lock.hide();
        unlock.setEnabled(false);
        unlock.hide();
        start.setEnabled(false);
        start.hide();
        stop.setEnabled(false);
        stop.hide();
    }
}
}

FingerprintHandler:

package com.gmtechnology.smartalarm;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.CancellationSignal;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;

public class FingerprintHandler extends
    FingerprintManager.AuthenticationCallback {

protected CancellationSignal cancellationSignal;
private Context appContext;


private FloatingActionButton mlock;
private FloatingActionButton mstart;
private FloatingActionButton munlock;
private FloatingActionButton mstop;
private TextView mstate;


public FingerprintHandler(Context context) {
    appContext = context;
}

public void startAuth(FingerprintManager manager,
                      FingerprintManager.CryptoObject cryptoObject, FloatingActionButton lock, FloatingActionButton unlock, FloatingActionButton start, FloatingActionButton stop, TextView state) {

    mlock = lock;
    munlock = unlock;
    mstart = start;
    mstop = stop;
    mstate = state;

    cancellationSignal = new CancellationSignal();

    if (ActivityCompat.checkSelfPermission(appContext,
            Manifest.permission.USE_FINGERPRINT) !=
            PackageManager.PERMISSION_GRANTED) {
        return;
    }
    manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}

@Override
public void onAuthenticationHelp(int helpMsgId,
                                 CharSequence helpString) {

    new MainActivity().state(3, mlock, munlock, mstart, mstop, mstate);
}

@Override
public void onAuthenticationFailed() {

    new MainActivity().state(3, mlock, munlock, mstart, mstop, mstate);
}

@Override
public void onAuthenticationSucceeded(
        FingerprintManager.AuthenticationResult result) {

    new MainActivity().state(2, mlock, munlock, mstart, mstop, mstate);
}
}

如果有人能指出我如何捕获并将扫描结果转换为我可以通过NFC发送它的格式,这将是非常棒的!

PS:我不是程序员,请放轻松我T ^ T

根据Micheal答案重申可能性: 无论如何都要使用NFC将传感器直接连接到服务器,以便数据可以直接发送到服务器进行身份验证而不保存?整个想法是认证是由外部服务器而不是智能手机完成的,这样可以使智能手机成为通用密钥&#34;,这样任何智能手机都可以用于使用正确的应用程序对任何服务器进行身份验证当然,或者可能以某种方式欺骗智能手机使用数据库通过NFC连接来比较指纹,这样当前信息在安全存储器上,但用于比较指纹的数据库在远程服务器上。我知道这些听起来很棘手,甚至可能是疯狂的#34;但是如果有可能在&#34;正确的&#34;之外做到这一点。可以采用的方式,仅适用于研究和研究的所有者。

1 个答案:

答案 0 :(得分:12)

Android指纹身份验证专门设计用于无法执行您想要的操作。

该设计确保指纹图像数据永远不会在Android OS 。即使您根设备或破坏内核,这些数据根本不可用。指纹图像需要从指纹扫描仪安全地传递到进行指纹匹配的安全硬件。这实际上是Android合规性要求。原因是指纹是重要的个人信息,不应泄漏。

关于你的替代建议,我无法想象为什么任何制造商都会这样做。

如果您想使用Android作为通用密钥,您应该执行以下操作:

  1. 使用AndroidKeyStore(我推荐EC)在设备上生成公钥/私钥对,指定该密钥只能用于指纹认证。
  2. 提取公钥并将其注册到服务器。
  3. 要使用通用密钥“解锁”,请与服务器一起执行质询 - 响应协议,例如:
    1. 在服务器上生成一个随机值,比如32个字节。
    2. 将随机值发送到手机。
    3. 使用AndroidKeyStore密钥创建一个Signature对象,将其初始化并将其包装在FingerprintManager.CryptoObject中。
    4. 进行指纹认证,并在完成后对随机值进行签名。
    5. 将签名随机值发送到服务器。
    6. 让服务器验证随机值和签名。
  4. 如果您想在服务器上进行指纹验证,则需要使用其他类型的指纹扫描仪。您无法使用Android(或iOS)手机执行此操作。