2016-12-06 49 views
-1

我是PHP新手,现在我只是想将Java xor加密/解密代码转换为PHP,后者用于服务器和客户端之间的事务处理。 下面是Java代码XOR:Java Biginteger xor加密/解密PHP

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。我需要安装某些东西还是执行一些配置?

+0

欢迎来到StackOverflow。代码有什么问题?它不工作?你有没有收到任何错误讯息?请尽可能具体,因为这会带来更好的答案。 –

+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(); 
}