Java中是否有与PHP中的bin2hex和hex2bin等效的函数?

3

我正在尝试将这个php代码转换成Java:

$pwd = "j7dR2f6Ywi01t+~P"; // This is key
$data = "10203010"; // This is Password

$encrypted = encrypt(pwd, $data);
$encrypted =  bin2hex($encrypted);
echo $encrypted;
echo '<br />';
$decrypted = decrypt($pwd, hex2bin($encrypted));
echo $decrypted;

function encrypt ($pwd, $data)
    {
        $key[] = '';
        $box[] = '';
        $cipher = '';
        $pwd_length = strlen($pwd);
        $data_length = strlen($data);
        for ($i = 0; $i < 256; $i++)
        {
            $key[$i] = ord($pwd[$i % $pwd_length]);
            $box[$i] = $i;
        }
        /***************************************
            for($z=0; $z<256; $z++)
            {
                echo $key[$z].'<br />';
            }
            exit;
        /***************************************/
        for ($j = $i = 0; $i < 256; $i++)
        {
            $j = ($j + $box[$i] + $key[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for ($a = $j = $i = 0; $i < $data_length; $i++)
        {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $k = $box[(($box[$a] + $box[$j]) % 256)];
            $cipher .= chr(ord($data[$i]) ^ $k);
        }
        return $cipher;
    }

    function decrypt ($pwd, $data)
    {
        return encrypt($pwd, $data);
    }

除了bin2hex和hex2bin函数之外,它已经完美地转换为Java,转换如下:
package pkgfinal;
public class Final { 
    public static   String convertHexToString(String hex){

      StringBuilder sb = new StringBuilder();
      StringBuilder temp = new StringBuilder();

      //49204c6f7665204a617661 split into two characters 49, 20, 4c...
      for( int i=0; i<hex.length()-1; i+=2 ){

          //grab the hex in pairs
          String output = hex.substring(i, (i + 2));
          //convert hex to decimal
          int decimal = Integer.parseInt(output, 16);
          //convert the decimal to character
          sb.append((char)decimal);

          temp.append(decimal);
      }
      System.out.println("Decimal : " + temp.toString());

      return sb.toString();
  }


    public static void RC4(String pwd ,String  data)
 {
   int[] key = new int[256];
   int[] box = new int[256];
   int i ;
   int a ;
   int j;
   int temp ;
   int  k ;
   StringBuilder cipher = new StringBuilder();
   StringBuilder output = new StringBuilder();

   int pwd_length = pwd.length();
   int data_length = data.length();
   for (   i = 0 ; i < 256 ; i++ )
    {
        key[i]= pwd.charAt(i % pwd.length());
        box[i]=i;
    }

  i = 0 ;
  j = 0 ;
  for ( ; i < 256 ; i++ )
  {
   j= (j + box[i]+ key[i] ) % 256    ;
   temp = box[i];
   box[i] = box[j];
   box[j]=temp;
  }
  j = 0;
  i = 0 ;
  a = 0 ;
  for( ; i < data_length ; i++)
  {
      a = (a+1) %256 ;
      j= (j + box[a])%256;
      temp = box[a];
      box[a] = box[j];
      box[j]= temp;
////      k = box[((box[a]+box[j])%256 )] ;              
      cipher.append((char)(data.charAt(i)^k));     
  }
  System.out.println(cipher.toString()); 
  //String o = cipher.toString();
  //byte[] bytes = o.getBytes();
  //System.out.println( Hex.encodeHexString( bytes ) );
 }
    public static void main(String[] args) 
    {
         Final.RC4("j7dR2f6Ywi01t+~P","10203010");        
    }

}

有没有一种类似于bin2hex用于加密和q的函数来将最终结果转换为十六进制的方法?
5个回答

7

之前的答案都不适用于我!

我通过以下方法解决:

DatatypeConverter.parseHexBinary(hexString);

DatatypeConverter.printHexBinary(byteArray);

来自javax.xml.bind.DatatypeConverter包。


1
尝试这个...
public String Bin2String(String hex){
    StringBuilder output = new StringBuilder();
    for (int i = 0; i < hex.length(); i+=2) {
        String str = hex.substring(i, i+2);
        output.append((char)Integer.parseInt(str, 16));
    }
    return output.toString();
}

1

首先,你需要将十六进制转换为十进制,然后再将十进制转换为二进制。

从十六进制到二进制

    String binStr = Integer.toString(Integer.parseInt("ff", 16),2);

从二进制到十六进制

    String hexStr = Integer.toString(Integer.parseInt("1111", 2),16);

二进制(字节数组)到十六进制的转换函数中,二进制部分(字节数组)在哪里? - Gandalf
我将其直接转换为整数。因此,整数保留字节。对于整数情况,它可以保留4个字节。如果您需要无限数量的字节,则可以将输入二进制字符串拆分为32位长度的字符串。并且您可以使用以上方法。 - Adem

1
这是我几乎完整的优化函数来执行它!
/**
 * Decodes a hexadecimally encoded binary string.
 * <p>
 * Note that this function does <em>NOT</em> convert a hexadecimal number to
 * a binary number.
 *
 * @param hex Hexadecimal representation of data.
 * @return The byte[] representation of the given data.
 * @throws NumberFormatException If the hexadecimal input string is of odd
 * length or invalid hexadecimal string.
 */
public static byte[] hex2bin(String hex) throws NumberFormatException {
    if (hex.length() % 2 > 0) {
        throw new NumberFormatException("Hexadecimal input string must have an even length.");
    }
    byte[] r = new byte[hex.length() / 2];
    for (int i = hex.length(); i > 0;) {
        r[i / 2 - 1] = (byte) (digit(hex.charAt(--i)) | (digit(hex.charAt(--i)) << 4));
    }
    return r;
}

private static int digit(char ch) {
    //TODO Optimize this
    int r = Character.digit(ch, 16);
    if (r < 0) {
        throw new NumberFormatException("Invalid hexadecimal string: " + ch);
    }
    return r;
}

public static String bin2hex(byte[] in) {
    StringBuilder sb = new StringBuilder(in.length * 2);
    for (byte b : in) {
        sb.append(
                forDigit((b & 0xF0) >> 4)
        ).append(
                forDigit(b & 0xF)
        );
    }
    return sb.toString();
}

public static char forDigit(int digit) {
    if (digit < 10) {
        return (char) ('0' + digit);
    }
    return (char) ('A' - 10 + digit);
}

谢谢@Daniel!我正在使用你的方法,它非常好用! - Ninja

0

是的。有{{link1:Integer.parseInt(String s,int radix)}}和{{link2:Integer.toString(int i,int radix)}}。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接