Get data from SharedPreferences

0

I have 2 stored strings with sharedpreferences in a login class, inside the onClick of a Button.

SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
            editor.putString("rut",loginText.toString());
            editor.putString("pass",passwordText.toString());
            editor.apply();

These values are received in another Activity by invoking the method created getValue (String keyPref).

public byte[] obtenerValor(String keyPref) {


    SharedPreferences _prefs = getPreferences(MODE_PRIVATE);


    //String valorPassPreferences = _prefs.getString(keyPref, "jjj");

    return _prefs.getString(keyPref.toString(), "JJJ").getBytes();

    }

I need to encrypt one of these data after an onAuthenticationSucceeded of the FingerPrint class that is in another Activity. CipherInit is the method that performs encryption.

fingerPrintActivity is previously instantiated.

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

    try {

        fingerPrintActivity.cipherInit();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    Toast.makeText(appContext,
            "Authentication succeeded.",
            Toast.LENGTH_LONG).show();
}



public boolean cipherInit() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
    try {

        plainBytes = obtenerValor("pass");
        Log.i(TAG, "cipherInit: valor plainBytes: " + plainBytes);
        // Generate the key first
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);  // Key size
        Key key = keyGen.generateKey();

        // Create Cipher instance and initialize it to encrytion mode
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  // Transformation of the algorithm
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] cipherBytes = cipher.doFinal(plainBytes);

        final String encryptedString = new String(cipherBytes, "UTF-8");
        Log.i(TAG, "EncryptString: encryptedString " + encryptedString);

        // Reinitialize the Cipher to decryption mode
        cipher.init(Cipher.DECRYPT_MODE, key, cipher.getParameters());
        byte[] plainBytesDecrypted = cipher.doFinal(cipherBytes);

        final String unencryptedString = new String(plainBytesDecrypted, "UTF-8");
        Log.i(TAG, "decryptString: desencript " + unencryptedString);

        //decryptString();
        return true;
    } catch (NoSuchAlgorithmException |
            NoSuchPaddingException e) {
        throw new RuntimeException("Failed to get Cipher", e);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }

    return false;
}

}

The error occurs when from cipherInit () I call getValue ("pass") passing it as a parameter the data that I need to encrypt. When entering this method, and when performing

   SharedPreferences _prefs = getPreferences(MODE_PRIVATE);

gives me the error E/AndroidRuntime: FATAL EXCEPTION: main Process: ---, PID: 6783 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132) at android.app.Activity.getLocalClassName(Activity.java:5559) at android.app.Activity.getPreferences(Activity.java:5592) at --.ui.fingerprint.FingerPrintActivity.obtenerValor(FingerPrintActivity.java:109) at --.fingerprint.FingerPrintActivity.cipherInit(FingerPrintActivity.java:123) at --fingerprint.FingerprintUiHelper.onAuthenticationSucceeded(FingerprintUiHelper.java:113) at android.hardware.fingerprint.FingerprintManager$MyHandler.sendAuthenticatedSucceeded(FingerprintManager.java:894) at android.hardware.fingerprint.FingerprintManager$MyHandler.handleMessage(FingerprintManager.java:842) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6165) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)

But when calling the getValue () method from the onCreate of the app, I have no problems and it brings me the data correctly. What may be happening?

log with getsharedpreferences.

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: ---, PID: 32581
                                                                        java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
                                                                            at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:164)
                                                                            at .factoring.ui.fingerprint.FingerPrintActivity.obtenerValor(FingerPrintActivity.java:110)
                                                                            at .factoring.ui.fingerprint.FingerPrintActivity.cipherInit(FingerPrintActivity.java:124)
                                                                            at .factoring.ui.fingerprint.FingerprintUiHelper.onAuthenticationSucceeded(FingerprintUiHelper.java:114)
                                                                            at android.hardware.fingerprint.FingerprintManager$MyHandler.sendAuthenticatedSucceeded(FingerprintManager.java:894)
                                                                            at android.hardware.fingerprint.FingerprintManager$MyHandler.handleMessage(FingerprintManager.java:842)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:154)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6165)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)

******** I add FingerPrintActivity Complete Code ********

package .factoring.ui.fingerprint;

import android.Manifest;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;

import android.os.Bundle;

import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;

import .factoring.R;

import static android.app.PendingIntent.getActivity;


public class FingerPrintActivity extends Activity {
private static final String TAG = FingerPrintActivity.class.getSimpleName();


private Cipher cipher;
private Key key;
private FingerprintManager.CryptoObject cryptoObject;
private FingerprintManager fingerprintManager;
private KeyguardManager keyguardManager;
private Context context;
private SharedPreferences prefs;


private String DEFAULT_KEY_NAME = "default_key_name";

final String PREFS_NAME = "my_name_preferences";
private byte[] plainBytes;
List<byte[]> arrPlainBytes;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   // setContentView(R.layout.fingerprint_dialog_container);
   // LayoutInflater inflater = this.getLayoutInflater();
   //  View frame = inflater.inflate(R.layout.fingerprint_dialog_container, null);
    ValidaHuella();
    keyguardManager =
            (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
    fingerprintManager =
            (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);


    if (!keyguardManager.isKeyguardSecure()) {

        Toast.makeText(this,
                   "La seguridad de la pantalla de bloqueo no está habilitada en Configuración",
                Toast.LENGTH_LONG).show();
        return;
    }

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.USE_FINGERPRINT) !=
            PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this,
                "El permiso de autenticación de huellas digitales no está habilitado",
                Toast.LENGTH_LONG).show();

        return;
    }

    if (!fingerprintManager.hasEnrolledFingerprints()) {

        // This happens when no fingerprints are registered.
        Toast.makeText(this,
                "Debes registrar por lo menos una huella en la Configuración de seguridad",
                Toast.LENGTH_LONG).show();
        return;
    }
    cryptoObject = new FingerprintManager.CryptoObject(cipher);
    FingerprintUiHelper helper = new FingerprintUiHelper(this);
    helper.fingerprintHandler(fingerprintManager, cryptoObject);

    obtenerValor("rut");
    obtenerValor("pass");

}

public byte[] obtenerValor(String keyPref) {

    Log.i(TAG, "obtenerValor keyPref: "+keyPref);

    SharedPreferences _prefs = getSharedPreferences("myPref",MODE_PRIVATE);
    Log.i(TAG, "obtenerValor valor prefs " + _prefs);
    // String valorPassPreferences = prefs.getResources().getString(R.string.pass_Shared);
    //String valorPassPreferences = _prefs.getString(keyPref, "jjj");


    Log.i(TAG, "obtenerValor: valor " +  _prefs.getString(keyPref, "jjj").getBytes());
    return _prefs.getString(keyPref.toString(), "JJJ").getBytes();

}

public boolean cipherInit() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
    try {

        plainBytes = obtenerValor("pass");
        Log.i(TAG, "cipherInit: valor plainBytes: " + plainBytes);
        // Generate the key first
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);  // Key size
        Key key = keyGen.generateKey();

        // Create Cipher instance and initialize it to encrytion mode
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  // Transformation of the algorithm
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] cipherBytes = cipher.doFinal(plainBytes);

        final String encryptedString = new String(cipherBytes, "UTF-8");
        Log.i(TAG, "EncryptString: encryptedString " + encryptedString);

        // Reinitialize the Cipher to decryption mode
        cipher.init(Cipher.DECRYPT_MODE, key, cipher.getParameters());
        byte[] plainBytesDecrypted = cipher.doFinal(cipherBytes);

        final String unencryptedString = new String(plainBytesDecrypted, "UTF-8");
        Log.i(TAG, "decryptString: desencript " + unencryptedString);

        //decryptString();
        return true;
    } catch (NoSuchAlgorithmException |
            NoSuchPaddingException e) {
        throw new RuntimeException("Failed to get Cipher", e);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }

    return false;
}

private void ValidaHuella (){



        FingerprintAuthenticationDialogFragment fragment
                = new FingerprintAuthenticationDialogFragment();

        fragment.show(getFragmentManager(), "Dialog Fragment TAG");

      /*  fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
        boolean useFingerprintPreference = mSharedPreferences
                .getBoolean(getString(R.string.use_fingerprint_to_authenticate_key),
                        true);
        if (useFingerprintPreference) {
            fragment.setStage(
                    FingerprintAuthenticationDialogFragment.Stage.FINGERPRINT);
        } else {
            fragment.setStage(
                    FingerprintAuthenticationDialogFragment.Stage.PASSWORD);
        }
        fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
    } else {

        FingerprintAuthenticationDialogFragment fragment
                = new FingerprintAuthenticationDialogFragment();
        fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
        fragment.setStage(
                FingerprintAuthenticationDialogFragment.Stage.NEW_FINGERPRINT_ENROLLED);
        fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
    }

* /     }

}

    
asked by Rodrigo 16.04.2018 в 18:06
source

2 answers

1

Beyond the use of getPreferences() and getSharedPreferences() the problem resided in the call to the method that reported the context error. The call to the method initCipher() was made from an activity created as varible through the instantiation FingerPrintActivity activity = new FingerprintActivity() , activity.initCipher() . When instantiating the activity in this way, it did not have the context of the Android framework, so when wanting to access the previously created preference, an error occurred.

The solution was to add a callback to the call of FingerprintUiHelper.onAuthenticationSucceeded() through an interface that implements the class FingerPrintActivity . In this way the activity can be notified at the moment of identifying a footprint successfully. So it is no longer necessary to have an instance of the activity in FingerprintUiHelper since it does not have a context within the Android Framework.

    
answered by 17.04.2018 / 18:28
source
0

When calling this line of code:

 SharedPreferences _prefs = getPreferences(MODE_PRIVATE);

You get the error:

  

NullPointerException: Attempt to invoke virtual method   'java.lang.String android.content.Context.getPackageName ()' on a null   object reference

The problem is that your class called FingerPrintActivity does not extend from Activity , AppCompatActivity or similar.

This Activity must be registered in AndroidManifest.xml

    
answered by 16.04.2018 в 18:27