-1

I have a problem while encrypting/decrypting with RSA in spongycastle on android. enctext contains encrypted text while dectext contains the text after decryption. In debugger, dectext matches plain text message "test" but when passed to smssend(string,string) function as string, some unknown format is shown. here is code.

{

    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)
    {
    }

Whats wrong with the code?? Is it some format issue?? Which format should I use??

Eshaal
  • 125
  • 2
  • 13

1 Answers1

0

instead of

dectext.toString()

you want to use

new String(dectext)

Furthermore, you should specify an encoding explicitly when converting between bytes and String:

message.getBytes("UTF-8")
new String(dectext, "UTF-8")
Henry
  • 42,982
  • 7
  • 68
  • 84
  • I have another problem!! String decstr= new String(dectext); worked perfect but when i test this encstr = new String(enctext); byte[] new_encarr=encstr.getBytes(); i dnt get same value back in new_encarr:(,... i am new to programming...in learning phase...can you please help – Eshaal Jan 26 '14 at 09:02
  • What do you mean by not the same value? It will be another object (i.e. `==` will give false) but the bytes contained in the array should be the same. I will extend the answer with an example to use an explicit encoding. This helps if you have issues interpreting the bytes on different machines. – Henry Jan 26 '14 at 09:13
  • values are not same!! debugger show different values in new_encarr and enctext (which should be same) – Eshaal Jan 27 '14 at 12:10