iOS和Android的AES加密(Java中无UINT)

4

大家好,

我对加密技术还比较新,所以我不确定需要分享哪些信息才能得到帮助;但是随着我了解如何正确提问,我会编辑这个问题的 :)

我正在对通过蓝牙与设备通信的iOS和安卓应用程序执行AES加密。 我正在使用AES CTR加密,它已在iOS上完全实现并正常工作。 我遇到的问题是,当我将诸如我的IV之类的项目转换为字节数组时,Java字节是有符号的,而Swift字节是无符号的,因此尽管我可以在Java上加密和解密字符串,但结果与在iOS上看到的结果不同。

其他人如何处理这个无符号整数问题? 我觉得肯定有一些我做错了的简单的东西。 我真的不知道要发布哪些代码。 对于Android,我在stackoverflow上找到的十六进制字符串到字节转换函数运行正确...只是有符号而不是无符号,因此值与iOS中的无符号字节数组不同。

iOS实现:

let aesPrivateKey = "********************************"

print("MacAddress:-> \(macAddress)")

var index = 0

let aesPrivateKeyStartIndex = aesPrivateKey.startIndex
let macAddressStartIndex = macAddress.startIndex

//Perform an XOR to get the device key
var deviceKeyArray: Array<Character> = Array(repeating: "?", count: 32)
for _ in macAddress {
    let nextPrivateKeyIndex = aesPrivateKey.index(aesPrivateKeyStartIndex, offsetBy: index)
    let nextMacAddressIndex = macAddress.index(macAddressStartIndex, offsetBy: index)

    let nextPrivateKeyString = String(aesPrivateKey[nextPrivateKeyIndex])
    let nextMacAddressString = String(macAddress[nextMacAddressIndex])

    let nextPrivateKeyByte = Int(nextPrivateKeyString, radix: 16)
    let nextMacAddressByte = Int(nextMacAddressString, radix: 16)

    let nextCombinedByte = nextPrivateKeyByte! ^ nextMacAddressByte!

    let nextCombinedString = nextCombinedByte.hexString

    deviceKeyArray[index] = nextCombinedString[nextCombinedString.index(nextCombinedString.startIndex, offsetBy: 1)]

    index+=1
}
while(index < 32) {

    let nextPrivateKeyIndex = aesPrivateKey.index(aesPrivateKeyStartIndex, offsetBy: index)
    deviceKeyArray[index] = aesPrivateKey[nextPrivateKeyIndex]
    index += 1
}

//Convert the device key to a byte array
let deviceKey = "0x" + String(deviceKeyArray)
let deviceKeyByte = Array<UInt8>(hex: deviceKey)

//Convert the password to a byte array
let passwordByte : Array<UInt8> = password.bytes

//Convert the initialization vector to a byte array
let aesIVHex = "0x" + AESIV
let aesIVByte = Array<UInt8>(hex: aesIVHex)

//Encrypt the password
var encrypted = [Unicode.UTF8.CodeUnit]()
do{
    encrypted = try AES(key: deviceKeyByte, blockMode: CTR(iv: aesIVByte)).encrypt(passwordByte)
}
catch{
    print(error)
}

print("The Encrypted Password Data: \(encrypted)")

let encryptedData = encrypted.toHexString()

//Write password to bluetooth and check result
UserDefaultUtils.setObject(encryptedData as AnyObject, key: userDefaults.password)
DeviceLockManager.shared().isEncrypted = false.
DeviceLockManager.share().setVerifyPasswordForDevice(isGunboxDevice:true)

Android实现:

System.out.println("ble_ Password:"+str_password+"\nble_ AesKey:"+aesDeviceKey+"\nble_ AesIV:"+aesIV);

byte[] encryptedData = encrypt(
        str_password.getBytes(),
        Utility.getInstance().hexStringToByteArray(aesDeviceKey),
        Utility.getInstance().hexStringToByteArray(aesIV));

String encryptedPassword = Utility.getInstance().bytesToHexString(encryptedData);
System.out.println("ble_ AES Encrypted password " + encryptedPassword);
byte[] decryptedData = decrypt(encryptedData, aesDeviceKey.getBytes(), aesIV.getBytes());
System.out.println("ble_ Cipher Decrypt:"+new String(decryptedData));

//Write password to bluetooth and check result
deviceManager.writePassword(encryptedPassword);
Utility.getInstance().sleep(100);
deviceManager.readPasswordResult();

所有输入值在调用函数hextStringtoByteArray之前都完全匹配。此时,iOS字节数组是无符号的,而android字节数组是有符号的。

以下是该函数的参考代码:

public static byte[] hexStringToByteArray(String s){
    byte[] b = new byte[s.length() / 2];
    for (int i = 0; i < b.length; i++) {
        int index = i * 2;
        int v = Integer.parseInt(s.substring(index, index + 2), 16);
        b[i] = (byte) v;
    }
    return b;
}

示例 IV 字节数组:

iOS 与 Android:

43、34、95、101、59、150、75、100、250、178、194、70、253、236、92、70

43、34、95、101、59、-106、75、100、-6、-78、-62、70、-3、-20、92、70


1
当编码/解码字符串时,有符号和无符号字节应该没有区别。但是使用的字符集可能会有所不同(Java中的默认字符集可能因操作系统而异!)。因此,为了提供解决方案,您需要解释您正在执行的操作(或更好的方法是展示一些代码)。 - n247s
我改变了我的实现方式,直接使用bigInteger,并获得了与使用我的hexStringToByteArray函数相同的结果;字节数组具有相同的值,只是有符号而不是无符号的。 - Eric
1个回答

3

你可能注意到这两个打印出来的数组之间存在差异,因为Java默认将字节显示为有符号值。但实际上它们是相等的。为了更清楚地说明,我将添加一个小表格,其中包含您提供的示例IV数组的最后5个值。

|----------------------------------------|
| hex      |  46 |  FD |  EC |  5C |  46 |
|----------------------------------------|
| unsigned |  70 | 253 | 236 |  92 |  70 |
|----------------------------------------|
| signed   |  70 | -3  | -20 |  92 |  70 |
|----------------------------------------|

因此,它们在位上实际上是相同的,只是因为被解释为不同的值而以不同的方式打印。如果你想确保正确性,建议使用编程模式计算器查看一些数字。通常有一种设置字节/字长度的方法,这样您就可以玩转相同十六进制值的有符号与无符号解释(该值还应具有位表示)。
作为替代方案,我发现了一个包含有符号与无符号类型位/十六进制转换器的小型网站,也能达到同样的效果。(请确保选择char类型,否则有符号值将不正确)
因此,在代码的IV-bytes部分不应该有任何问题。但是,如果您仅使用一个字节数组作为参数来创建字符串,则可能会出现问题。例如:
byte[] decryptedData = decrypt(encryptedData, aesDeviceKey.getBytes(), aesIV.getBytes());
System.out.println("ble_ Cipher Decrypt:" + new String(decryptedData));

由于使用的字符集很可能不是UTF-8(您可以调用Charset#defaultCharset来确定并检查其值),因此另一种选择是:

new String(decryptedData, StandardCharsets.UTF_8)

或者:

new String(decryptedData, "UTF-8");

1
只是想补充一下,我在安卓中设置填充时出现了错误;接受无符号字节与有符号字节之间的区别没有影响让我找到了正确的解决方案。 - Eric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接