2016-12-06 50 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(); 
}