[英]RSA Encryption Decryption Android
我有一个设置屏幕,我希望用户在其中填写个人详细信息。 我想将它们保留在sharedpreferences中。 我想先加密数据,然后再保存到Sharedpreferences中。 仅当使用它时,它才在另一个应用程序活动中解密共享首选项中存在的内容并使用它。 为此,我在设置屏幕中加密了信息,并将加密后的字符串保存到共享首选项中。 为了解密,我需要相同的privateKey,但我不知道如何将其移至其他活动。 我尝试使用sharedpreferences,但程序运行正常。
希望得到帮助
码:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.