java - JAVA中String到byte[]和byte[]到String的相互转换

标签 java string byte

我一直在尝试使用“DESede”加密对一些数据进行编码和解码。 编码进展顺利,但我面临解码问题。 我得到的编码数据格式类似于“[B@7764dc81”(只是一个示例值),它应该是 byte[] 格式,但我得到的是字符串形式的数据(这是一个要求),现在,我希望将“[B@7764dc81”(只是一个示例值)从字符串转换为 byte[] 形式,但不幸的是,它不适合我。

函数 String.getBytes();一次又一次返回不同的结果,其中调用该方法的String对象是相同的。但是通过方法 (Arrays.toString(String.getBytes())) 获取的 Array 值返回相同的值,这让我很困惑。

基本上,我想根据机器主板的序列号和 MAC 地址对一些值进行编码,连接两个 key ,并生成一个新 key 。之后,我想解码获得的 key ,将其拆分回来,并检查该 key 是否与MAC地址和主板序列号的原始值完全匹配。我在后面的程序中遇到了问题。我得到两个“[B@f56dec29”(只是一个示例值)格式的切片字符串值,我希望它们采用 byte[] 格式,以便我可以将它们传递到我的 ObjectCrypter.decryptF() 函数中。此外,该函数还引发了一个异常,即“ key 长度必须是 8 的倍数...”。 main 函数对于可视化日期有很大帮助,正确的人可能第一眼就能猜到到底发生了什么。 我有两个文件,代码如下: 安全.java

public class Security {

public static void main(String[] args) throws NoSuchAlgorithmException,UnknownHostException, SocketException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, UnsupportedEncodingException
{
    String algorithm = "DESede";
    ObjectCrypter obj = null;
    Key symKey = KeyGenerator.getInstance(algorithm).generateKey();
    Cipher c = Cipher.getInstance(algorithm);
    String serial = getSerialNumber();
    String mac = getMacAddress();


    serial = getSerialNumber();
    mac = getMacAddress();
    byte[] encryptionBytes1 = obj.encryptF(serial,symKey,c);
    System.out.println("Serial: " + serial);
    System.out.println("Encr: " + encryptionBytes1);
    System.out.println("Decr: " + obj.decryptF(encryptionBytes1, symKey, c));
    byte[] encryptionBytes2 = obj.encryptF(mac,symKey,c);
    System.out.println("MAC: " + mac);
    System.out.println("Encr: " + encryptionBytes2);
    System.out.println("Decr: " + obj.decryptF(encryptionBytes2, symKey, c));


    System.out.println("EncryptionBytes: "+encryptionBytes1);
    System.out.println("Array EncBytes: "+Arrays.toString(encryptionBytes1));
    String ts = encryptionBytes1.toString();
    System.out.println("TesString: "+ts);
    System.out.println("TesString ConvBytes: "+ts.getBytes("ISO-8859-1"));
    System.out.println("TesString ConvBytes2: "+ts.getBytes("ISO-8859-1"));
    System.out.println("ts array: "+Arrays.toString(ts.getBytes("ISO-8859-1")));
    byte[] tsec = ts.getBytes("ISO-8859-1");
    System.out.println("tsec array: "+Arrays.toString(tsec));
    System.out.println("esTrEncrypt: "+tsec);
    System.out.println("esTrEncryptBytes1: "+tsec.toString().getBytes("ISO-8859-1"));
    System.out.println("esTRarray1: "+Arrays.toString(tsec));
    System.out.println("esTrEncryptBytes2: "+tsec.toString().getBytes("ISO-8859-1"));
    System.out.println("esTRarray1: "+Arrays.toString(tsec));
    System.out.println("esTrEncryptBytes3: "+tsec.toString().getBytes("ISO-8859-1"));
    System.out.println("esTRarray1: "+Arrays.toString(tsec));
    String decoded = new String(encryptionBytes1, "ISO-8859-1");
    System.out.println("Decoded: "+decoded);
    byte[] encoded = decoded.getBytes("ISO-8859-1");
    System.out.println("Encoded: "+encoded);
    System.out.println("ArrayEncoded: "+Arrays.toString(encoded));
    String decrypted = obj.decryptF(encoded, symKey, c);
    System.out.println("decrypted: "+decrypted);

    serial = getSerialNumber();
    mac = getMacAddress();
    byte[] encryptionBytes12 = obj.encryptF(serial,symKey,c);
    System.out.println("Serial: " + serial);
    System.out.println("Encr: " + encryptionBytes12);
    System.out.println("Decr: " + obj.decryptF(encryptionBytes1, symKey, c));
    byte[] encryptionBytes22 = obj.encryptF(mac,symKey,c);
    System.out.println("MAC: " + mac);
    System.out.println("Encr: " + encryptionBytes22);
    System.out.println("Decr: " + obj.decryptF(encryptionBytes2, symKey, c));
}//end test
public static String generateData() throws NoSuchAlgorithmException, NoSuchPaddingException, UnknownHostException, SocketException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException
{
    String part1 = null, part2 = null;
    String algorithm = "DESede";
    ObjectCrypter obj = null;
    Key symKey = KeyGenerator.getInstance(algorithm).generateKey();
    Cipher c = Cipher.getInstance(algorithm);
    String serial = getSerialNumber();
    String mac = getMacAddress();
    byte[] encryptionBytes = obj.encryptF(serial, symKey, c);
    part1 = encryptionBytes.toString();
    byte[] encryptionBytes2 = obj.encryptF(mac, symKey, c);
    part2 = encryptionBytes2.toString();
    part1 = sliceString(part1);
    part2 = sliceString(part2);
    return part1+part2;
}//end generateData


public static boolean checkLicense(String license) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnknownHostException, SocketException, UnsupportedEncodingException
{
    String part1 = null, part2 = null;
    String genSerial = null, genMac = null;
    if (license.length() == 16)
    {
        part1 = "[B@" + license.substring(0, 8);
        part2 = "[B@" + license.substring(8, license.length());
    }//end if
    else if (license.length() == 15)
    {
        part1 = "[B@" + license.substring(0, 7);
        part2 = "[B@" + license.substring(7, license.length());
    }//end if
    else
    {
        return false;
    }//end else


    byte[] bpart1 = part1.getBytes("ISO-8859-1");
    byte[] bpart2 = part2.getBytes("ISO-8859-1");

    System.out.println("bytes: "+bpart1 + "\t" + bpart2);

    System.out.println("parts: "+part1 + "\t" + part2);
    String algorithm = "DESede";
    ObjectCrypter obj = null;
    Key symKey = KeyGenerator.getInstance(algorithm).generateKey();
    Cipher c = Cipher.getInstance(algorithm);
    genSerial = sliceString(obj.decryptF(bpart1, symKey, c));
    genMac = sliceString(obj.decryptF(bpart2, symKey, c));
    System.out.println(genSerial + "\t" + genMac);
    System.out.println(getSerialNumber() + "\t" + getMacAddress());
    if (genSerial == getSerialNumber() && genMac == getMacAddress())
    {
        return true;
    }//end if
    else
    {
        return false;
    }//end else
}//end checkLicense
public static String sliceString(String arg)
{
    return arg.substring(3);
}//end sliceString

public static String getSerialNumber()
{
    String output = "";
    try 
    { 
        Process p=Runtime.getRuntime().exec("wmic baseboard get serialnumber"); 
        //p.waitFor(); 
        BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
        String line = "";
        int index = 0;
        while((line = reader.readLine()) != null)
        {
            if (line.length() > 0)
            {
                output = line;
            }//end if
        }//end while
    } 
    catch(IOException e1) {}
    return output;
}//end extractMBSerialNumber

public static String getMacAddress() throws UnknownHostException, SocketException
{
    InetAddress ip;
    ip = InetAddress.getLocalHost();

    NetworkInterface network = NetworkInterface.getByInetAddress(ip);
    byte[] mac = network.getHardwareAddress();

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < mac.length; i++) {
        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
    }
    return sb.toString();
}

}

ObjectCrypter.java 的代码是:

public class ObjectCrypter {
static String algorithm = "DESede";

static byte[] encryptF(String input,Key pkey,Cipher c) throws InvalidKeyException, BadPaddingException,

IllegalBlockSizeException {

    c.init(Cipher.ENCRYPT_MODE, pkey);

    byte[] inputBytes = input.getBytes();

    return c.doFinal(inputBytes);
}

static String decryptF(byte[] encryptionBytes,Key pkey,Cipher c) throws InvalidKeyException,

BadPaddingException, IllegalBlockSizeException {

    c.init(Cipher.DECRYPT_MODE, pkey);

    byte[] decrypt = c.doFinal(encryptionBytes);

    String decrypted = new String(decrypt);
    return decrypted;
}

}

最佳答案

您的[B@7764dc81只是 toString () 的结果在byte []上。如果您想根据字节创建一个字符串,则需要使用 String bytes = new String (yourbytearray);

或者更好

new String (yourbytes, Charset.forName ("utf-8"));

您不应该按照字面上的方式使用这些字符串。

“[B@”只是数组 [ 的缩写 字节数 B地址 @加上地址...

同样从字符串到字节[]的转换是:

  byte [] bytedata = yourstring.getBytes (Charset.forName ("utf-8"));

关于java - JAVA中String到byte[]和byte[]到String的相互转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34379255/

相关文章:

c++ - 在 Turbo C++ 中将字符串分配给结构中的 char 数组

java - 使用 BufferedReader 从文件中读取 Long 和 String

java - 在特定字符之前插入字符 Java

java - 如何使用接受用户输入的循环将元素添加到树集中?

java - 如何处理 lambda 中的已检查异常?

Java HttpResponse 澄清

java - Java中如何使用ByteBuffer的Wrap方法

java - 为什么在 JAVA 中按位 AND with byte 这样做?

java - 将字节转换为位

java - 带有 XMLStreamReader 和 StreamFilter 的 JAXB 未最终确定