Java Biginteger xor加密/解密PHP

时间:2016-12-06 07:38:19

标签: php biginteger

我是PHP的新手,现在我只想将java xor加密/解密代码翻译成PHP,用于服务器和客户端之间的事务。 下面是Java xor代码:

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 "";
    }
}

我做了一些研究并在http://phpseclib.sourceforge.net/documentation/math.html中找到了一些信息,但无法使其发挥作用。我在服务器上的PHP版本是5.4.36。我是否需要安装或执行某些配置?

1 个答案:

答案 0 :(得分:0)

让它奏效。下面是PHP代码

function encrypt($string, $key)
{
    $bi_passwd = new Math_BigInteger($string, 256);
    $bi_r0 = new Math_BigInteger($key);
    $bi_r1 = $bi_r0->bitwise_xor($bi_passwd);
    return $bi_r1->toHex();
}

function decrypt($string, $key)
{
    $bi_confuse = new Math_BigInteger($key);
    $bi_r1 = new Math_BigInteger($string, 16);
    $bi_r0 = $bi_r1->bitwise_xor($bi_confuse);
    return $bi_r0->toBytes();
}