Java 使用RSA在Android中进行加密/解密
注意:由于我是stackoverflow的新成员,并且链接上的声誉受到限制,我将不得不在这里发布大量的代码 编辑:自从我发布这篇文章以来,我已经更新了我的GenyMoon设备和SDK,到目前为止,我已经成功地获得了解密的字节数组,但是有一堆前导零。为了实现这一点,我没有接触过一行代码。我运行应用程序的环境确实有些奇怪 我一直在尝试使用RSA加密和解密随机生成的AES密钥(及其IV),然后在加密服务器和android设备之间传输的数据时使用RSA。我一直在使用Genymotion设备测试我的代码,到目前为止,这就是我遇到这些问题的地方 这段代码已经过测试,以前在桌面上运行过,当我在androidstudio中复制到我的android项目时,问题才开始出现。我在桌面设置中使用了这些加密和解密方法,没有任何问题 我想我确实设法将问题定位在我的RSA加密中,加密了一些文本,但解密后没有得到相同的字节,尽管我不能完全排除其他错误:Java 使用RSA在Android中进行加密/解密,java,android,encryption,rsa,genymotion,Java,Android,Encryption,Rsa,Genymotion,注意:由于我是stackoverflow的新成员,并且链接上的声誉受到限制,我将不得不在这里发布大量的代码 编辑:自从我发布这篇文章以来,我已经更新了我的GenyMoon设备和SDK,到目前为止,我已经成功地获得了解密的字节数组,但是有一堆前导零。为了实现这一点,我没有接触过一行代码。我运行应用程序的环境确实有些奇怪 我一直在尝试使用RSA加密和解密随机生成的AES密钥(及其IV),然后在加密服务器和android设备之间传输的数据时使用RSA。我一直在使用Genymotion设备测试我的代码,
private byte[] decrypt(byte[] bytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/None/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, PRIVATE_KEY);
return cipher.doFinal(bytes);
}
private byte[] encrypt(byte[] bytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/None/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, SERVER_KEY);
return cipher.doFinal(bytes);
}
//Made this method to test my own keys, and whether or not encryption works
private byte[] encryptMyOwnKey(byte[] bytes) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/None/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, PUBLIC_KEY);
return cipher.doFinal(bytes);
}
在构造函数中,我刚刚添加了这段代码,以测试这两个方法
private ServerInterface(Context context) throws IOException {
//Some not so interesting code goes here
final KeyPair key = getKeyPair(context);
PRIVATE_KEY = (RSAPrivateKey) key.getPrivate();
PUBLIC_KEY = (RSAPublicKey) key.getPublic();
try {
//Some dummy text for testing
byte[] test = decrypt(encryptMyOwnKey("Decryption successful".getBytes()));
Log.i("ServerInterface", "Test result: "+new String(test));
} catch (Exception e) {
e.printStackTrace();
}
//More code that isn't interesting
}
用于获取密钥对的方法有:
private static KeyPair getKeyPair(Context context) {
final File keyFileDirectory = new File(context.getFilesDir(), "rsa/");
final File publicKeyFile = new File(keyFileDirectory, "sikkr_pub_key");
final File privateKeyFile = new File(keyFileDirectory, "sikkr_priv_key");
KeyPair key;
if (publicKeyFile.exists() && privateKeyFile.exists()) {
try {
key = getKeyPairFromFile(publicKeyFile, privateKeyFile);
} catch (Exception e) {
key = generateKeyPair(publicKeyFile, privateKeyFile);
}
} else {
key = generateKeyPair(publicKeyFile, privateKeyFile);
}
return key;
}
private static KeyPair getKeyPairFromFile(File publicKeyFile, File privateKeyFile) throws Exception {
Log.d("ServerInterface", "Getting the key pair from file");
byte[] publicKey = readByteDataFromFile(publicKeyFile);
byte[] privateKey = readByteDataFromFile(privateKeyFile);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(publicKey));
RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
return new KeyPair(pubKey, privKey);
}
private static KeyPair generateKeyPair(File publicKeyFile, File privateKeyFile) {
Log.d("ServerInterface", "Generating a key pair");
KeyPairGenerator keyGen;
KeyPair key = null;
if (publicKeyFile.exists()) {
publicKeyFile.delete();
}
if (privateKeyFile.exists()) {
privateKeyFile.delete();
}
try {
keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
key = keyGen.genKeyPair();
if (!publicKeyFile.getParentFile().exists()) {
publicKeyFile.getParentFile().mkdirs();
}
publicKeyFile.createNewFile();
privateKeyFile.createNewFile();
saveByteDataToFile(publicKeyFile, key.getPublic().getEncoded());
saveByteDataToFile(privateKeyFile, key.getPrivate().getEncoded());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void saveByteDataToFile(File file, byte[] data) throws IOException {
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
dos.write(data);
dos.flush();
dos.close();
}
private static void readByteDataFromFile(File file) throws IOException {
DataInputStream dis = new DataInputStream(new FileInputStream(file));
byte[] read = new byte[dis.available()];
dis.readFully(read);
dis.close();
return read;
}
我从运行应用程序中获得的日志包括:
10-18 13:55:16.472 1251-1265/edu.chalmers.sikkr I/ServerInterface﹕ Setting up an interface to the server
10-18 13:55:16.528 1251-1265/edu.chalmers.sikkr D/ServerInterface﹕ Generating a key pair
10-18 13:55:17.004 1251-1265/edu.chalmers.sikkr I/ServerInterface﹕ Test result: JNk9���N+!N^9__ `D�)̊#O�K��\���Q�eD�(���M�
&vK6���%M��,�9wg��!um7���t�9�w+�LGh�0ڼ{�s]���̅�����_͵b�-0��> ��fk@m}��Wx|�g�_��P8;��t��:��5��8��o�͐w�Ơ����o$��2��jS2�Z��j̪����j�l_HZ�k���~�����7�b��N�fޒ�Ի*)I.IE�
如您所见,测试结果与解密文本相差甚远,这很可能是测试所有函数时给我带来问题的原因。我不知道如何解决这个问题,因为大多数代码以前都在桌面环境中完美地工作过。非常感谢您的帮助
编辑:我之前提到的新输出:
10-18 20:45:44.969 1301-1314/edu.chalmers.sikkr I/ServerInterface﹕ Test result: ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Decryption successful
编辑:最后一个问题也得到了解决,从NoPadding改为PKCS1Padding。在generateKeyPair函数中,您有:
saveByteDataToFile(privateKeyFile, key.getPublic().getEncoded());
本应是:
saveByteDataToFile(privateKeyFile, key.getPrivate().getEncoded());
对不起,当我把文字从一台电脑复制到另一台电脑时,那是一个打字错误。原始代码与您所说的一样。还是给了我同样的结果。尽管如此,日志甚至没有说它从这个实例中的文件中读取(因为它是第一次运行的),这意味着它不应该在文件中查找密钥。我根据你的更正修改了我原来的问题,以避免将来的混淆。