【问题标题】:Swift Biginteger xor encrypt/decryptSwift Biginteger xor 加密/解密
【发布时间】:2017-12-18 02:22:23
【问题描述】:

我是 Swift 新手,现在我只想将 java xor 加密/解密代码翻译成 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 xor 加密的信息,并在下面的链接中尝试了答案:

XOR Encryption in Swift IOS

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

Swift Simple XOR Encryption

但是与我的 java 代码相比,它们都无法获得相同的加密字符串,现在我的 java 代码是实时的,没有办法改变它。

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

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

非常感谢谁能帮助我解决这个问题!我一整天都在研究这个!

再次感谢。

【问题讨论】:

    标签: swift encryption hex biginteger xor


    【解决方案1】:

    已解决,代码如下。

    基于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 库做出贡献的人,这就是代码看起来如此简单的原因。

    【讨论】:

    • 你有 Swift 4 版本吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多