2016-04-26 262 views
0

我有一些問題將字節[]轉換爲字符串。 這裏是我的功能:Java - 將字節[]轉換爲字符串

private byte[] encryptrc4(String toEncrypt, String key) throws Exception{ 
     // create a binary key from the argument key (seed) 
     SecureRandom sr = new SecureRandom(key.getBytes()); 

     KeyGenerator kg = KeyGenerator.getInstance("RC4"); 
     kg.init(sr); 
     SecretKey sk = kg.generateKey(); 

     // create an instance of cipher 
     Cipher cipher = Cipher.getInstance("RC4"); 

     // initialize the cipher with the key 
     cipher.init(Cipher.ENCRYPT_MODE, sk); 

     // enctypt! 
     byte[] encrypted = cipher.doFinal(toEncrypt.getBytes()); 

     return encrypted; 
    } 

這是我的主要代碼行:

String message = "some message"; 
String key = "keystring"; 

byte[] msgEncrypted=encryptrc4(message, key); 

我已經試過的System.out.println(msgEncripted.toString()); 但它不起作用。

如何將msgEncrypted轉換爲字符串?

+0

假設我有進口的所有要求。 –

+1

嘗試'System.out.println(new String(msgEncripted));代替。如果你得到垃圾,請嘗試使用編碼的構造函數。 – Kayaman

+0

@Kayaman構造函數? –

回答

2

要轉換字節[]爲String您可以使用:

String s = new String(bytes);