2016-09-25 77 views
-1

我想從字節數組創建一個字符串,但它給了我一些隨機值。字節數組是加密的,所以我不確定我是否正確解密。隨機值看起來像 - [B @ 1uy3798。每次它給不同的隨機值。我該如何解決這個問題?String.valueOf()給出隨機值

public class MainActivity { 
    public static void main(String[] args) { 

    Key publicKey = null; 
    Key privateKey = null; 
    byte[] encoded; 
    byte[] text = new byte[0]; 

    try { 
     text = "This is my secret message".getBytes(); 

     Cipher c = Cipher.getInstance("RSA"); 
     c.init(Cipher.ENCRYPT_MODE, publicKey); 
     encoded = c.doFinal(text); 

     c = Cipher.getInstance("RSA"); 
     c.init(Cipher.DECRYPT_MODE, privateKey); 
     text = c.doFinal(encoded); 

     } catch (Exception e) { 
     System.out.println("Exception encountered. Exception is " + e.getMessage()); 
     } 
     System.out.println(String.valueOf(text)); //get random values here 
    } 
    } 
+0

它看起來像你在字節數組上調用'toString()'。 – SLaks

+0

你應該報告你所遇到的任何異常,而不是默默地忽略它們。也許你錯過了一個簡單的錯誤? –

回答

2

String.valueOf(text)不會做你認爲它做的事。你想要的是new String(text)

String.valueOf(text)返回指向數組(它的哈希碼)的指針的字符串表示形式。你想把數組轉換成一個String,所以使用適當的構造函數。

要解釋爲什麼你得到這個返回值,你應該看看的toString()在java.lang.Object中的合同:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method. The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode()) 

爲了把它放在一起,你會得到 - [B @ 1uy3798,因爲[B是類byte []的名稱(如果反彙編類文件,您將在字節碼中看到此內容),然後是「@」,然後是1uy3798。如果要再次運行該類並在byte []文本上調用hashCode(),則會看到哈希碼與您在Toast中看到的值相匹配。

+0

那麼,如何解決這個錯誤哥們,可以給我一個例子代碼,使用新的String(文本)將解決問題? –

+0

重新閱讀我的答案。它包含解決方案。使用'new String(text)'。如果它解決了問題,請將此答案標記爲正確。 – mttdbrd

+0

現在我得到這個錯誤:java.lang.NullPointerException:嘗試在java.lang.String處獲得空數組 的長度。 (String.java:119) at chatra.alert.MainActivity $ 1.onClick(MainActivity.java:122) –