2013-02-02 25 views
1

我正在嘗試編寫一個加密類,以允許iPhone向Android發送加密文本,反之亦然。雖然這是Android的非常簡單(以下代碼)適用於iPhone和Android的加密功能相同

private static final String CIPHER_ALGORITHM = "AES"; 
private static final String RANDOM_GENERATOR_ALGORITHM = "SHA1PRNG"; 
private static final int RANDOM_KEY_SIZE = 128; 

// Encrypts string and encode in Base64 
public static String encrypt(String password, String data) throws Exception 
{ 
    byte[] secretKey = generateKey(password.getBytes()); 
    byte[] clear = data.getBytes(); 

    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, CIPHER_ALGORITHM); 
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); 
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); 

    byte[] encrypted = cipher.doFinal(clear); 
    String encryptedString = Base64.encodeToString(encrypted, Base64.DEFAULT); 

    return encryptedString; 
} 

// Decrypts string encoded in Base64 
public static String decrypt(String password, String encryptedData) throws Exception 
{ 
    byte[] secretKey = generateKey(password.getBytes()); 

    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, CIPHER_ALGORITHM); 
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); 
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); 

    byte[] encrypted = Base64.decode(encryptedData, Base64.DEFAULT); 
    byte[] decrypted = cipher.doFinal(encrypted); 

    return new String(decrypted); 
} 

public static byte[] generateKey(byte[] seed) throws Exception 
{ 
    KeyGenerator keyGenerator = KeyGenerator.getInstance(CIPHER_ALGORITHM); 
    SecureRandom secureRandom = SecureRandom.getInstance(RANDOM_GENERATOR_ALGORITHM); 
    secureRandom.setSeed(seed); 
    keyGenerator.init(RANDOM_KEY_SIZE, secureRandom); 
    SecretKey secretKey = keyGenerator.generateKey(); 
    return secretKey.getEncoded(); 
} 
} 

我已經看到了類似主題的答案几萬,但沒有得到的代碼爲iOS給出了相同的結果真的工件上。大部分代碼甚至不能正確編譯。有人有一個真正的代碼工作?

回答

2

請參閱iOS上的RNCryptor和適用於Java的JNCryptor。他們實現相同的文件格式。它使用隨機IV,PBKDF2生成的隨機鹽密碼正確處理AES-CBC-256,並驗證HMAC用於數據驗證和完整性。

+0

我已經下載並將檢查它。謝謝。 – men

相關問題