解密文本时的格式问题(Spongycastle)

时间:2014-01-26 06:05:30

标签: java android spongycastle

我在android上的spongycastle中使用RSA加密/解密时遇到问题。 enctext包含加密文本,而dectext包含解密后的文本。在调试器中,dectext匹配纯文本消息“test”但是当作为字符串传递给smssend(string,string)函数时,会显示一些未知格式。这是代码。

{

    byte[] enctext;
    byte[] dectext;
    String message="test";

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "SC");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SC");
    keyGen.initialize(1024, random);
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();


    Cipher  rsaCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding","SC");
    rsaCipher.init(Cipher.ENCRYPT_MODE, pub);
    enctext=rsaCipher.doFinal(message.getBytes());

    Cipher rsaCipher2 = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding","SC");
    rsaCipher2.init(Cipher.DECRYPT_MODE, priv);
    dectext=rsaCipher2.doFinal(enctext);
    sendSMS("5554",dectext.toString());// in debugger dectext shows equivalent "test" values in decimal but when passed as string to sendSMS func it shows some unknown format...

    }

    private void sendSMS(final String phoneNumber,String message)
    {
    }

代码有什么问题?是格式问题吗?我应该使用哪种格式?

1 个答案:

答案 0 :(得分:0)

而不是

dectext.toString()

你想用

new String(dectext)

此外,在字节和字符串之间进行转换时,应明确指定编码:

message.getBytes("UTF-8")
new String(dectext, "UTF-8")