简体   繁体   English

在JAVA中将String互转换为byte []和byte []转换为String

[英]Interconversion of String into byte[] and byte[] into String in JAVA

I've been trying to encode and decode some data using "DESede" encryption. 我一直在尝试使用“ DESede”加密对一些数据进行编码和解码。 Encoding goes fine, but I'm facing problems with the decoding. 编码进行得很好,但是我在解码方面遇到了问题。 I get the encoded data in the format like "[B@7764dc81" (just an example value), which is supposed to be in byte[] format, but I get this data in the form of a string (It's a requirement), and now, I want "[B@7764dc81"(just an example value) to be converted from string into byte[] form, but unluckily, it's not working out for me. 我以“ [B @ 7764dc81””的格式获取编码数据(只是一个示例值),应该以byte []格式获取,但是我以字符串形式获取此数据(这是必要条件),现在,我希望将“ [B @ 7764dc81”(只是一个示例值)从字符串转换为字节[]形式,但是不幸的是,它对我来说不起作用。

The function String.getBytes(); 函数String.getBytes(); return different results again and again, where the String object calling this method is the same. 一次又一次返回不同的结果,其中调用此方法的String对象是相同的。 But the Array values obtained through the method (Arrays.toString(String.getBytes())) returns the same values, and this is messing my mind. 但是通过方法(Arrays.toString(String.getBytes()))获得的Array值返回相同的值,这使我很困惑。

Basically, I want to encode some values, based on the machine's Motherboard's serial number, and the MAC address, concatenate both the keys, and generate a new key. 基本上,我想根据计算机的主板序列号和MAC地址对一些值进行编码,将两个密钥连接起来,并生成一个新密钥。 After that, I want to decode the the obtained key, split it back, and check if the key exactly matches the original values of the MAC address and the Motherboard's serial number, or not. 之后,我要解码所获得的密钥,将其拆分,然后检查该密钥是否与MAC地址的原始值和主板的序列号完全匹配。 I'm having a problem with the later procedure. 我在后面的过程中遇到了问题。 I get two sliced string values in a "[B@f56dec29"(just an example value) format, and I want them to be in byte[] format, so that I may pass them into my ObjectCrypter.decryptF() function. 我得到了两个以[[B @ f56dec29](只是示例值)格式的切片的字符串值,并且我希望它们以字节[]格式,以便可以将它们传递给我的ObjectCrypter.decryptF()函数。 Also, this function raises an exception with the statement, that says "key length must be a multiple of 8...". 此外,此函数在语句中引发异常,即“密钥长度必须是8的倍数...”。 The main function helps a lot in visualizing the date, and the right person may guess at the first glance that what actually is going on. 主要功能在可视化日期方面有很大帮助,正确的人乍看之下可能会猜测实际发生的情况。 I've two files, and the code is given below: Security.java 我有两个文件,代码如下:Security.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();
}

} }

The code for ObjectCrypter.java is: 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;
}

} }

Your [B@7764dc81 is just the result of toString () on a byte [] . 您的[B@7764dc81只是toString ()byte [] If you want to create a string based on the bytes you'll need to use String bytes = new String (yourbytearray); 如果要基于字节创建字符串,则需要使用String bytes = new String (yourbytearray);

Or better 或更好

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

You should not use these strings literally the way you do. 您不应该按原样使用这些字符串。

"[B@" is just short for an array [ of bytes B at address @ plus the address... “[B @”只是短用于阵列[字节B在地址@地址加...

Likewise the conversion from string to byte [] is: 同样,从字符串到字节[]的转换为:

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

When you call toString() on a byte[] . 当您在byte[]上调用toString()时。 you get something like [B@7764dc81 . 您会得到类似[B@7764dc81

The actual values in the array are not part of the text representation, so if you're receiving [B@7764dc81 , then you already lost all the values. 数组中的实际值不是文本表示的一部分,因此,如果您收到[B@7764dc81 ,则您已经丢失了所有值。

You cannot use bytes (binary) as a String. 您不能将字节(二进制)用作字符串。 It's a misunderstanding. 这是一个误会。

You should convert it . 您应该将其转换。 Several manners. 几种方式。 Base64 or Hexa, for example 例如Base64或Hexa

with base64, it gives this: 使用base64,它可以实现以下功能:

import javax.xml.bind.DatatypeConverter ;

byte[] bt= ... // what you get

// Conversion B64
String encodedb64=DatatypeConverter.printBase64Binary(bt);

// CONVERSION base 64 => byte => String
// base 64 => byte
byte [] byteArrayreverse=DatatypeConverter.parseBase64Binary(encodedb64);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM