注意:由于在这里是一个新的成员,因此在链接上使用了stackoverflow和信誉限制,因此我将不得不在此处发布大型代码块。使用RSA的Android中的加密/解密
编辑:我已经发布了这个更新了我的Genymotion设备和我的SDK,到目前为止我已经设法得到解密的字节数组,但有一堆前导零。为了做到这一点,我还没有触及一行代码。对于我正在运行应用程序的环境来说,某些东西看起来确实很奇怪。
我一直在尝试使用RSA加密和解密随机生成的AES密钥(以及其IV),然后使用RSA在加密服务器和Android设备之间传输的数据时使用。我一直在使用Genymotion设备测试我的代码,这是迄今为止我遇到过这些问题的地方。
该代码已经过测试,并且已经在桌面设置上工作过,并且问题仅在我复制到Android Studio中的Android项目时才开始显示。我在桌面设置上使用了这些加密和解密方法,没有任何问题。
我觉得我没有管理本地化的问题,通过加密一些文字在我的RSA加密被解密后没有得到相同的字节,虽然我不能完全排除其他错误:
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��> ��[email protected]}��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。
对不起,这是一个错字,当我复制的文本从一台计算机到另一台。原始代码就像你说的那样。仍然给我同样的结果。在这种情况下,日志甚至没有说它从文件中读取(因为它是第一次运行),这意味着它不应该在文件中查找关键字。根据您的更正,我改变了我原来的问题,以避免将来的混淆。 – Sweed 2014-10-18 15:31:46