Swift 大整数异或 encrypt/decrypt

Swift Biginteger xor encrypt/decrypt

我是Swift的新手,现在我只想将java异或encrypt/decrypt代码翻译成Swift,用于服务器和客户端之间的交易.下面是 Java 异或代码:

public static String encrypt(String password, String key) {
    if (password == null)
        return "";
    if (password.length() == 0)
       return "";

    BigInteger bi_passwd = new BigInteger(password.getBytes());

    BigInteger bi_r0 = new BigInteger(key);
    BigInteger bi_r1 = bi_r0.xor(bi_passwd);

    return bi_r1.toString(16);
}

public static String decrypt(String encrypted, String key) {
    if (encrypted == null)
        return "";
    if (encrypted.length() == 0)
        return "";

    BigInteger bi_confuse = new BigInteger(key);

    try {
        BigInteger bi_r1 = new BigInteger(encrypted, 16);
        BigInteger bi_r0 = bi_r1.xor(bi_confuse);

        return new String(bi_r0.toByteArray());
    } catch (Exception e) {
        return "";
    }
}

我搜索了很多关于 swift 异或加密的信息,并尝试了以下链接中的答案:

https://coderwall.com/p/timkvw/simple-xor-encryption-and-decryption-in-swift-playground-code

但是与我的java代码相比,他们都无法获得相同的加密字符串,现在我的java代码已经生效,并且无法更改它。

我认为可能是十六进制引起的,但是在swift中,我找不到任何关于swift xor hexadecimal.

所以我需要的是 swift 代码可以得到与我粘贴的 java 代码完全相同的加密字符串,我的 java 客户端生成的加密字符串可以是在我的 iOS 客户端中解密。

非常感谢能帮我解决这个问题的人!我已经沉浸其中一整天了!

再次感谢。

已解决,下面是代码。

基于 https://github.com/lorentey/BigInt

的出色工作
func encrypt(str:String, key:BigUInt)->String
{
    let value = BigUInt(str.data(using: String.Encoding.utf8)!)
    let encrypt = key ^ value
    return String(encrypt, radix: 16)
}

func decrypt(str:String, key:BigUInt)->String
{
    let value = BigUInt(str, radix: 16)!
    let decrypt = key ^ value
    return String(data: decrypt.serialize(), encoding: String.Encoding.utf8)!
}

再次感谢所有为 BigInt 库做出贡献的人,这就是代码看起来如此简单的原因。