我有一个设置屏幕,希望用户在其中填写个人详细信息。我想把它们保存在共享引用中。我想在保存到SharedReferences之前对数据进行加密。只有当它被使用时,它才会在另一个应用程序活动中解密共享引用中存在的内容并使用它。为此,我对设置屏幕中的信息进行了加密,并将加密后的字符串保存到共享引用中。为了解密,我需要相同的privateKey,我不知道如何将其移动到其他活动。我试着使用共享引用,但程序运行得很快。
非常感谢的帮助
代码:
try{
SharedPreferences.Editor editor =getActivity().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
afterEncryptCvv = Encrypt((String) newValue,editor);
editor.putString("cvvValue", afterEncryptCvv);
editor.commit();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
加密功能:
public static String Encrypt(String plain, SharedPreferences.Editor editor)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException
{
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
Gson gson4 = new Gson();
String json4 = gson4.toJson(privateKey);
editor.putString("privateKey", json4);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
encrypted = bytesToString(encryptedBytes);
return encrypted;
}
在第二个活动中:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
try {
Gson gson4 = new Gson();
String json4 = prefs.getString("privateKey", "");
privateKey = gson4.fromJson(json4, PrivateKey.class);
cvvValue = prefs.getString(Cvv, "");
String temp = Decrypt(cvvValue);
cvvValue =temp;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
解密功能:
public String Decrypt (String result) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
BadPaddingException
{
cipher1= Cipher.getInstance("RSA");
cipher1.init(Cipher.DECRYPT_MODE, privateKey);
decryptedBytes = cipher1.doFinal(stringToBytes(result));
decrypted = new String(decryptedBytes);
return decrypted;
}
您不应该将密钥存储在内部存储器上。有根设备的人可以很容易地提取它。
相反,生成密钥对后,您可以将其保存在Android密钥存储中(请参阅此处:http://developer.android.com/training/articles/keystore.html)并在需要时使用。
例如:
KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
KeyStore.Entry entry = ks.getEntry(alias, null);