1

I would like to create few java function to add in a android studio application.The purpose of those function is begin able to send encrypted message with RSA encryption.

I first generate both keys. Then I use the public one to encrypt my message and it works. Then , I translate the encrypted message from byte[] to String() because I would like to send the message by SMS. All those parts works. Then i try to reuse the SMS that i should receive in the SMS but it doesn't work.I obtain the following mistake :

"javax.crypto.BadPaddingException: Decryption error" <br/>

in this line:
"descryptedData = cipher.doFinal(decrypt); " // (cf code below)

i use .toString() function to translate the message encrypted from bytes to String. If I skip the part where I translate from bytes to String for sending the SMS and from String to bytes for decrypt the data, it works perfectly.

Here is the part of the code that could interest you :

PrivateKey privateKey = null;
privateKey = appMob.getPrivKey(keys[1]); //return the privatekey      
System.out.println("\n--- Decryption started--- \n");
byte[] descryptedData = null;

try{
    byte[] decrypt = smsWithCryptedData.getBytes("UTF-8");
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE,privateKey);
    descryptedData = cipher.doFinal(decrypt);
    String smsFinal = new String(descryptedData);

    System.out.println("decrypt \n smsFinal");


}catch(Exception e)
    {
        e.printStackTrace();

    }

I suppose that the error comes from converting String to byte and byte to string but i don't know how to solve it. Does somebody have an idea ?

  • 1
    *"i use ".toString()" function to translate the message encrypted from bytes to String"* - and this is what you shouldn't have done. `String` is not a container for arbitrary binary data. – Artjom B. Jun 10 '17 at 16:56
  • does somebody have an idea of any solution i could use to convert byte data so string in a reusable way ? –  Jun 10 '17 at 17:14
  • 1
    Didn't you read the answer I linked to? – Artjom B. Jun 10 '17 at 17:33
  • Yes i did, and i finally found a solution. By converting byte into Biginteger(type used during encryption) and then BigInteger into String. It's working now :) Thank you for telling me that i couldn't do it by a direct way! –  Aug 07 '17 at 16:10

1 Answers1

1

usually people uses something like base64 encoder/decoder to convert byte array to/from string, as simple casting to UTF-8 can loose some data, no one can guarantee that random byte sequence have correct representation as a UTF-8 string.

for instance, check out an example for android, it's a bit different question, but I believe with exact same answer that you need. Alternatives for DatatypeConverter in Android

Павел
  • 677
  • 6
  • 21