将byte []转换为字符串时出现问题

时间:2016-09-15 11:13:08

标签: java

我将byte[]转换为string时遇到问题。 我使用encryptText()加密,它返回byte[]。然后我使用byte[]传递byteToString()转换为字符串。

byte[]转换为String

    s = bytesToString(cipherText);      //junk value getting here, i'm expecting 

在将byte []转换为字符串

之后,此处的加密值相同
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.prefs.Preferences;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.xml.bind.DatatypeConverter;

public class Test {
    private Test() {  } 
    /**
     * gets the AES encryption key. 
     * @return
     * @throws Exception
     */
    public static SecretKey getSecretEncryptionKey() throws Exception 
    {
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(128); 
        SecretKey secKey = generator.generateKey();
        return secKey;
    } 
    /**
     * Encrypts password in AES using the secret key.
     * @param passWord
     * @param secKey
     * @return
     * @throws Exception
     */
    public static byte[] encryptText(String passWord,SecretKey secKey) throws Exception 
    {        
        Cipher aesCipher = Cipher.getInstance("AES");
        aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
        byte[] byteCipherText = aesCipher.doFinal(passWord.getBytes());
        return byteCipherText;
    }
    /**
     * Decrypts encrypted byte array using the key used for encryption.
     * @param byteCipherText
     * @param secKey
     * @return
     * @throws Exception
     */
    public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception 
    {
        Cipher aesCipher = Cipher.getInstance("AES");
        aesCipher.init(Cipher.DECRYPT_MODE, secKey);
        byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
        return new String(bytePlainText);
    }
    //converting byte[] to string
    private static String bytesToString(byte[] bytesArray)
    {         
        StringBuffer stringBuffer = new StringBuffer();         
        for (int i = 0; i < bytesArray.length; i++) {             
            stringBuffer.append((char) bytesArray[i]);         
        }         
        return stringBuffer.toString();     
    }

    public static void main(String args[]) throws Exception 
    {
        SecretKey secKey = getSecretEncryptionKey();        
        String s = null;        
        String Username = null;
        String Password = null;     
        String value = null;    
        try 
        {
            if(args[0] != null)
                Username = args[0];
            if(args[1] != null)
                Password = args[1];     
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException caught");
        }
        finally {           
        } 
        byte[] cipherText = encryptText(Password, secKey);
        s = bytesToString(cipherText);      //junk value getting here, i'm expecting same encrypted value here even after converting byte[] to string
        System.out.println("Encrypted cipherText = " + cipherText);
        System.out.println("Encrypted Password = " + s);        
        System.out.println("Done." );
    }
}

2 个答案:

答案 0 :(得分:2)

简答:使用new String(bytes, "utf8")(或您拥有的任何其他字符集字节)。

但是在你的情况下,加密函数返回的字节可能无法转换为utf8-string。您不能只接受任意字节并将其转换为字符串,因为某些字节序列无法解释为有效的utf8。

您可能希望使用一些单字节字符集来解决问题。但我通常建议不要转换为不是字符串的字符串字节。

答案 1 :(得分:2)

加密内容不应被人阅读,因为它是纯二进制内容,但如果您确实需要使其可读,则应将其编码为十六进制值使用Apache Commons Codec

您的方法将是:

private static String bytesToString(byte[] bytesArray){ 
   return Hex.encodeHexString(bytesArray); 
}

另一种方法可能是append每个byte直接stringBuffer,而不是先将char作为下一个投放:

private static String bytesToString(byte[] bytesArray) {
    StringBuilder stringBuffer = new StringBuilder();
    for (int i = 0; i < bytesArray.length; i++) {
        stringBuffer.append(bytesArray[i]);
    }
    return stringBuffer.toString();
}
  

s = new String(cipherText,“utf8”);不工作!

它无法工作,因为cipherText不是给定UTF8的{​​{1}}编码版本,而是与加密内容对应的字节数组。换句话说,它在某种程度上等同于使用给定算法对String进行编码,并尝试使用完全不同的算法的解码函数对其进行解码,它根本无法工作。