【发布时间】:2015-11-06 07:22:08
【问题描述】:
我正在尝试使用 RSA 加密数据。到目前为止一切都很好。我可以生成私钥,我可以成功加密和解密字符串。 现在我想在 SharedPreference 中存储公钥。我可以将它存储为字符串。我可以将它作为字符串检索。我需要将其转换为密钥,以传递给密码。没有发生从字符串到原始格式的转换。
这是我尝试过的
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); //generate key using RSA
KeyPair keypair=keyPairGenerator.generateKeyPair(); //get generated key
Cipher cipher =Cipher.getInstance("RSA/ECB/PKCS1Padding");
SharedPreferences sharedPreferences=context.getSharedPreferences("rsakey", MODE_PRIVATE);//Initializing SharedPerference
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("public",keypair.getPublic().toString());
editor.putString("private",keypair.getPrivate().toString());
editor.commit();//store key in sharedpreference
final String sampletext="abcde";
//getting stored key
String publicKey = sharedPreferences.getString("public", null);
String privateKey = sharedPreferences.getString("private", null);
//publicKey must of type "KEY", so i need to convert publicKey to KEY, But its not happening
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
byte[] encryptedtext=cipher.doFinal(sampletext.getBytes());
String encrypted_text=new String(Base64.encode(encryptedtext,Base64.NO_WRAP));
//privateKey is string, it supposed to be of type KEY
cipher.init(Cipher.DECRYPT_MODE,privateKey);
encryptedtext=Base64.decode(encrypted_text.getBytes(), Base64.NO_WRAP);
encryptedtext=cipher.doFinal(encryptedtext);
String decrypted_text=new String(encryptedtext);
在这里,我在 cipher.init(Cipher.ENCRYPT_MODE,publicKey); 中遇到问题 publicKey 包含存储的 PublicKey,从 SahredPreferences 中提取。它是字符串类型!怎么转成Key?
PS:这只是示例代码,在现实生活中我会将私钥存储在服务器中,然后将公钥发给用户。
【问题讨论】:
标签: java android encryption sharedpreferences