2016-09-25 74 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) –