以安全的方式从字段访问密码

时间:2016-07-20 09:12:57

标签: android security passwords

String basicAuth = "Basic " + Base64.encodeToString( (emailText.getText().toString() + ":" + passwordText.getText().toString()).getBytes(), Base64.NO_WRAP);

如何处理这个问题。我需要制作基本的身份验证令牌。输入密码后,您可以在EditText passwordText中的调试器中找到密码。会在内存转储中显示吗?不仅如此,getText()。toString()会使字符串在内存中保留一段时间吗?我知道你可以很容易地找到令牌,但这不是重点,关键是没有人能够找到你的密码。我该怎么办?

1 个答案:

答案 0 :(得分:-1)

这就是我正在使用的。用于存储敏感的AES加密

package com.myapp.utilities;

import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Base64;

import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Security {
    private static final String TAG = Security.class.getSimpleName();

    private Cipher cipher;
    private SecretKeySpec key;
    private AlgorithmParameterSpec spec;

    public Security(Context context) throws Exception {
        // hash password with SHA-256 and crop the output to 128-bit for key
        MessageDigest digest = MessageDigest.getInstance("SHA-256");

        String secret = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
//        secret = "asjldknfajlsdbc DCNJANSDKJNACSDCnmcnc ###";

        digest.update(secret.getBytes("UTF-8"));
        byte[] keyBytes = new byte[32];
        System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);

        cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        key = new SecretKeySpec(keyBytes, "AES");
        spec = getIV();
    }

    public AlgorithmParameterSpec getIV(){
        byte[] iv = {
                (byte) 0x8E, 0x12, 0x39, (byte) 0x9C, 0x07, 0x72, 0x6F, 0x5A,
                (byte) 0x8E, 0x12, 0x39, (byte) 0x9C, 0x07, 0x72, 0x6F, 0x5A
        };
        IvParameterSpec ivParameterSpec;
        ivParameterSpec = new IvParameterSpec(iv);

        return ivParameterSpec;
    }

    public String encrypt(String plainText) throws Exception{
        if (!TextUtils.isEmpty(plainText)) {
            cipher.init(Cipher.ENCRYPT_MODE, key, spec);
            return new String(Base64.encode(cipher.doFinal(plainText.getBytes("UTF-8")), Base64.DEFAULT), "UTF-8");
        }
        return null;
    }

    public String decrypt(String cryptedText) throws Exception {
        if (!TextUtils.isEmpty(cryptedText)) {
            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            return new String(cipher.doFinal(Base64.decode(cryptedText, Base64.DEFAULT)), "UTF-8");
        }
        return null;
    }
}

关于内存转储的问题,它仍然在手机内,并且没有泄漏到手机外。您将通过网络而不是简单数据发送加密数据。显然,键盘记录器或类似设备可以轻松检测到这一切,但有多少人会这样做呢?那个将在输入密码的同时加密字符串的人是谁?