情况:
我想要一个使用RSA加密字符串的应用程序.我将公钥存储在res/raw中,并且因为密钥是1024位,所以生成的字符串必须是128字节长.但是,加密后得到的字符串长124,结果解密崩溃.
我用来恢复公钥的功能是:
private PublicKey getPublicKey() throws Exception {
InputStream is = getResources().openRawResource(R.raw.publickey);
DataInputStream dis = new DataInputStream(is);
byte [] keyBytes = new byte [(int) is.available()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
Run Code Online (Sandbox Code Playgroud)
以及我用来加密的函数的代码:
private String rsaEncrypt (String plain) {
byte [] encryptedBytes;
Cipher cipher = Cipher.getInstance("RSA");
PublicKey publicKey = getPublicKey();
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
String encrypted = new String(encryptedBytes);
return encrypted;
Run Code Online (Sandbox Code Playgroud)
}
PD:代码在桌面应用程序中完美运行,它只是在Android中崩溃.
我真的很感激任何帮助,
非常感谢你.
我正在编写一个Android应用程序,每5分钟获取一次用户位置,将其存储在数据库中并将其发送到服务器.
我已经阅读了许多方法,我将做以下事情:
但我已经看到它可以通过"远程服务"(http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html)或与一个AlarmManager,用于安排每5分钟启动一次该服务.
该服务需要始终运行:重要的是,在每个间隔(5分钟)之后,它将被执行.
我想我需要一些清晰度.
谢谢您的帮助,