适用于iPhone和Android的加密功能

时间:2013-02-02 21:09:45

标签: android iphone encryption

我正在尝试编写一个加密类,允许iPhone将加密文本发送到Android,反之亦然。虽然这在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代码,可以提供相同的结果。大多数代码甚至都没有正确编译。有人为此提供了真正的代码吗?

1 个答案:

答案 0 :(得分:2)

请参阅iOS上的RNCryptor和Java上的JNCryptor。它们实现相同的文件格式。它使用随机IV正确处理AES-CBC-256,使用随机盐生成的PBKDF2密码,并验证HMAC的数据验证和完整性。