以下是一种在Android上存储RSA公钥的解决方法,包含代码示例:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
// 将私钥保存到SharedPreferences中
SharedPreferences sharedPreferences = getSharedPreferences("RSAKeys", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("privateKey", Base64.encodeToString(privateKey.getEncoded(), Base64.DEFAULT));
editor.apply();
PublicKey publicKey = keyPair.getPublic();
// 将公钥保存到文件中
File publicKeyFile = new File(getFilesDir(), "publicKey.pem");
FileWriter fileWriter = new FileWriter(publicKeyFile);
PemWriter pemWriter = new PemWriter(fileWriter);
pemWriter.writeObject(new PemObject("PUBLIC KEY", publicKey.getEncoded()));
pemWriter.close();
// 从SharedPreferences中获取私钥
String privateKeyString = sharedPreferences.getString("privateKey", null);
byte[] privateKeyBytes = Base64.decode(privateKeyString, Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
// 从文件中读取公钥
File publicKeyFile = new File(getFilesDir(), "publicKey.pem");
FileReader fileReader = new FileReader(publicKeyFile);
PemReader pemReader = new PemReader(fileReader);
PemObject pemObject = pemReader.readPemObject();
pemReader.close();
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pemObject.getContent());
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
这样,你就可以在Android上生成RSA密钥对,并将公钥存储到文件中,私钥存储到SharedPreferences中。
上一篇:Android存储权限