tengo 2 string almacenados con sharedpreferences en una clase login, dentro del onClick de un Button.
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("rut",loginText.toString());
editor.putString("pass",passwordText.toString());
editor.apply();
Estos valores los recibo en otra Activity invocando el método creado obtenerValor(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();
}
Necesito cifrar uno de estos datos posterior a un onAuthenticationSucceeded de la clase FingerPrint que se encuentra en otra Activity. CipherInit es el método que realiza el cifrado.
fingerPrintActivity está instanciada anteriormente.
@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;
}
}
El error se produce cuando desde cipherInit() llamo a obtenerValor("pass") pasándole como parámetro el dato que requiero cifrar. Al entrar a este metodo, y al realizar
SharedPreferences _prefs = getPreferences(MODE_PRIVATE);
me entrega el 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)
Pero al realizar el llamado al método obtenerValor() desde el onCreate de la app no tengo problemas y me trae correctamente el dato. Qué puede estar ocurriendo?
log con 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)
********Agrego Código Completo de FingerPrintActivity********
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);
}
*/ }
}
getSharedPreferences(APP_ID, Context.MODE_PRIVATE)
donde APP_ID es el nombre de la preferences. De este modo podes especificar una preferences dedicada para tu aplicación.