2014-10-18 23 views
3

注意:由於在這裏是一個新的成員,因此在鏈接上使用了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: JNk9���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。

回答

0

在你generateKeyPair功能,您有:

saveByteDataToFile(privateKeyFile, key.getPublic().getEncoded()); 

它應該是:

saveByteDataToFile(privateKeyFile, key.getPrivate().getEncoded()); 
+0

對不起,這是一個錯字,當我複製的文本從一臺計算機到另一臺。原始代碼就像你說的那樣。仍然給我同樣的結果。在這種情況下,日誌甚至沒有說它從文件中讀取(因爲它是第一次運行),這意味着它不應該在文件中查找關鍵字。根據您的更正,我改變了我原來的問題,以避免將來的混淆。 – Sweed 2014-10-18 15:31:46