【问题标题】:AES Encryption Android <-> iOS different results on message length > 15 byteAES 加密 Android <-> iOS 消息长度 > 15 字节的不同结果
【发布时间】:2013-10-31 11:35:13
【问题描述】:

我在理解这两种设备上的密码器时遇到了真正的问题。

1。 如果我们在 iOS 和 Android 上使用 Cipher AES 加密消息并且字符串的字符长度不大于 16(例如“abcdefghijklmno”),我们在使用相同的密钥/密码对其进行加密后得到相同的结果。

2。 但如果接收更长的消息,我们会在 iOS 和 Android 上得到不同的结果(例如“abcdefghijklmnop”)

我做了很多研究如何为两种设备获取相同的参数,起初我认为它是安全的。

这是我的加密密码:

public String encode(Context context, String password, String text)
        throws NoPassGivenException, NoTextGivenException {
    if (password.length() == 0 || password == null) {
        throw new NoPassGivenException("Please give Password");
    }

    if (text.length() == 0 || text == null) {
        throw new NoTextGivenException("Please give text");
    }

    try {
        SecretKeySpec skeySpec = getKey(password);
        byte[] clearText = text.getBytes("UTF8");


        //IMPORTANT TO GET SAME RESULTS ON iOS and ANDROID
        final byte[] iv = new byte[16];
        Arrays.fill(iv, (byte) 0x00);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        // Cipher is not thread safe
                    //EDITED AFTER RIGHT ANSWER FROM
                    //*** Cipher cipher = Cipher.getInstance("AES");   ***//
                    // TO  
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");


        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);

        String encrypedValue = Base64.encodeToString(
                cipher.doFinal(clearText), Base64.DEFAULT);
        Log.d(TAG, "Encrypted: " + text + " -> " + encrypedValue);
        return encrypedValue;

    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
    return "";
}


public SecretKeySpec getKey(String password)
        throws UnsupportedEncodingException {


    int keyLength = 128;
    byte[] keyBytes = new byte[keyLength / 8];
    // explicitly fill with zeros
    Arrays.fill(keyBytes, (byte) 0x0);

    // if password is shorter then key length, it will be zero-padded
    // to key length
    byte[] passwordBytes = password.getBytes("UTF-8");
    int length = passwordBytes.length < keyBytes.length ? passwordBytes.length
            : keyBytes.length;
    System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
    return key;
}

这是我同事的 iOS 挂件:

- (NSData *)AES128EncryptWithKey:(NSString *)key {

    // 'key' should be 32 bytes for AES256,
    // 16 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES128 + 1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // insert key in char array
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;

    // the encryption method, use always same attributes in android and iPhone (f.e. PKCS7Padding)
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCKeySizeAES128,
                                          NULL                      /* initialization vector (optional) */,
                                          [self bytes], dataLength, /* input */
                                          buffer, bufferSize,       /* output */
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {

        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }

    free(buffer);
    return nil;
}

我真的很想了解差异可能是什么以及如何避免它。使用大于 15 个字符的字符串进行精确测试给了我一个提示,但我不知道为什么:)

提前谢谢大家!

【问题讨论】:

  • 检查两个系统上使用的填充。不同的填充将导致不同的输出。不要依赖默认值,而是显式设置两边的填充。您的第二个代码片段明确设置 PKCS7 填充。在两端都使用它。
  • 哦,谢谢,请回答Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
  • 您的密钥派生功能非常弱,密钥可能会被暴力破解。您应该使用适当的密钥派生函数,例如 PBKDF2 或 bcrypt。您也不应该使用静态 IV,因为这会破坏 CBC 模式的某些安全属性。
  • 为什么不应该使用固定 IV:crypto.stackexchange.com/q/5094

标签: java android ios iphone cryptography


【解决方案1】:

检查两个系统上使用的填充。不同的填充将导致不同的输出。不要依赖默认值,而是显式设置两边的填充。您的第二个代码片段明确设置 PKCS7 填充。在两端都使用它。

作为一般规则,不要不依赖不同系统之间的默认值。显式设置 IV、模式、填充、随机数或其他任何需要的东西。如果即使是最细微的细节不匹配,加密也会严重失败。

【讨论】:

  • 感谢您的成功:Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
  • 请注意,非 Android Java 将其称为“PKCS5Padding”而不是“PKCS7Padding”。
  • 是的,如果你使用 PKCS7Padding 会慢很多。在 JellyBean 及更高版本中使用 AES/CBC/PKCS5Padding 会更快。
猜你喜欢
  • 2021-03-08
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 2017-04-26
相关资源
最近更新 更多