我正在尝试使用RSA加密数据。到目前为止一切都很好。我可以生成Private-Public密钥,我可以成功加密和解密字符串。 现在我想在SharedPreference中存储公钥。我可以把它存储为字符串。我可以将其检索为字符串。我需要将其转换为Key,以传递给密码。没有发生从字符串到原始格式的转换。
这是我试过的
validates Project.find(:project_id).schedule_mode, exclusion: { in: %w(free) }
在这里,我在cipher.init(Cipher.ENCRYPT_MODE,publicKey)面临问题; publicKey包含从SahredPreferences中提取的存储的PublicKey。它是String类型!如何将其转换为Key?
PS:这只是示例代码,在现实生活中我将私钥存储在服务器中,公钥将发给用户。
答案 0 :(得分:2)
希望这能帮到你
public void generateKeys(){
try {
SharedPreferences SP;
SharedPreferences.Editor SPE;
KeyPairGenerator generator;
generator = KeyPairGenerator.getInstance("RSA", "BC");
generator.initialize(256, new SecureRandom());
KeyPair pair = generator.generateKeyPair();
pubKey = pair.getPublic();
privKey = pair.getPrivate();
byte[] publicKeyBytes = pubKey.getEncoded();
String pubKeyStr = new String(Base64.encode(publicKeyBytes));
byte[] privKeyBytes = privKey.getEncoded();
String privKeyStr = new String(Base64.encode(privKeyBytes));
SPE = SP.edit();
SPE.putString("PublicKey", pubKeyStr);
SPE.putString("PrivateKey", privKeyStr);
SPE.commit();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
}
public PublicKey getPublicKey(){
String pubKeyStr = SP.getString("PublicKey", "");
byte[] sigBytes = Base64.decode(pubKeyStr);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(sigBytes);
KeyFactory keyFact = null;
try {
keyFact = KeyFactory.getInstance("RSA", "BC");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
try {
return keyFact.generatePublic(x509KeySpec);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
public String getPublicKeyAsString(){
return SP.getString("PublicKey", "");
}
public PrivateKey getPrivateKey(){
String privKeyStr = SP.getString("PrivateKey", "");
byte[] sigBytes = Base64.decode(privKeyStr);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(sigBytes);
KeyFactory keyFact = null;
try {
keyFact = KeyFactory.getInstance("RSA", "BC");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
try {
return keyFact.generatePrivate(x509KeySpec);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
public String getPrivateKeyAsString(){
return SP.getString("PrivateKey", "");
}
答案 1 :(得分:1)
尝试此代码我正在使用此代码: -
private static final int MODE_PRIVATE = 0;
Editor editor;
SharedPreferences pref;
pref = getApplicationContext().getSharedPreferences("MyPref",
MODE_PRIVATE);
editor = pref.edit();
editor.putString("full_name", edtfullname.getText()
.toString());
editor.commit();
//another activity or class you can access that
full_name = pref.getString("full_name", "");