AES encryption makes different result in iOS and Android

前端 未结 2 1488
北海茫月
北海茫月 2021-02-04 15:16

Trying to encrypt sample data using AES128 algorithm with CBC and PKCS7 padding in Android and iOS, but results are different :(

Android code:

private s         


        
相关标签:
2条回答
  • 2021-02-04 15:35

    I vaguely recall I had once similar issue of "synchronizing" the encryption between Android and iPhone, and the solution was in proper IV (initialization vector) usage. So probably switching on an explicit IV usage in Android could help:

    final byte[] iv = new byte[16];
    Arrays.fill(iv, (byte) 0x00);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    .. // the rest of preparations
    ecipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
    

    Because when on iPhone you pass NULL as the IV, it may internally use a default one that corresponds to the just stated above.

    But in production environment you should use a (cryptographically secure pseudo-)random initialization vector, stored together with the data. Then it is safe for all modes of operations. [1]

    0 讨论(0)
  • 2021-02-04 15:44

    The Android code uses explicitly CBC mode. But the iOS code does not specify this. At least I don't see it there.

    Also when you use CBC mode, you must also specify Initialization Vector:

    byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; // use different random value
    AlgorithmParameterSpec algorithmSpec = new IvParameterSpec(iv);
    Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
    ecipher.init(Cipher.ENCRYPT_MODE, skeySpec, algorithmSpec);
    

    You should use the same initialization vector on iOS and also specify you are using CBC mode.

    0 讨论(0)
提交回复
热议问题