2012-01-09 49 views
0

所以我在我的PHP服務器上加密了一個字符串。Java:如何解碼使用已知密鑰在php上加密的字符串?

encrypt("http://google.com", "happy"); 

function encrypt($str, $key) 
{ 
    $block = mcrypt_get_block_size('des', 'ecb'); 
    $pad = $block - (strlen($str) % $block); 
    $str .= str_repeat(chr($pad), $pad); 

    return mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB); 
} 

順便說一句,這將返回一些奇怪的字符串...我所期待的字母和數字: ZöÞ ÔP»8

回到Java的,我需要解密此字符串的關鍵。

回答

1

我不太子港既成事實與mcrypt的,而是通過加密運行ASCII純文本沒有按」 t總是導致一個ASCII密文。當您嘗試將其解釋爲ASCII或unicode文本時,您生成的加密密文將會轉化爲「奇怪的字符串」。

0

首先,確保它不是單向加密。 秒,用於php和java中的逆向工程的算法和參數

0

我認爲這會很有用。請注意,字符集是UTF-8。

public class Foo { 

    public static void main(String[] args) { 
     try { 
      String cipherSpec = "DES/ECB/NoPadding"; 
      Cipher cipher = Cipher.getInstance(cipherSpec); 
      int blockSize = cipher.getBlockSize(); 

      String keyText = "happy"; 
      Key key = new SecretKeySpec(padRight(keyText, blockSize).getBytes("UTF-8"), "DES"); 

      String input = "http://google.com"; 
        input = padRight(input, input.length() + blockSize - (input.length() % blockSize)); 

      // encrypt 
      cipher.init(Cipher.ENCRYPT_MODE, key); 
      byte[] cipherText = cipher.doFinal(input.getBytes(CHARSET)); 
      System.out.println("\ncipher text: "); 
      System.out.println(new String(cipherText, CHARSET)); 

      // decrypt 
      cipher.init(Cipher.DECRYPT_MODE, key); 
      byte[] plainText = cipher.doFinal(cipherText); 
      System.out.println("\nplain text: "); 
      System.out.println(new String(plainText, CHARSET)); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    final static String CHARSET = "UTF-8"; 

    static String padRight(String s, int n) { 
     return String.format("%1$-" + n + "s", s); 
    } 
} 
+0

'new String(cipherText,CHARSET)'是錯誤的。 – 2012-01-09 23:38:01

相關問題