0

I am currently developing an application that requires me to encrypt chatting messages. In addition, I managed to encrypt the data Using RSA algorithm but I am not able to decrypt it. below is a snapshots of my encryption and decryption code RSA Class

public class RSA {
KeyPairGenerator kpg;
KeyPair kp;
PublicKey publicKey;
PrivateKey privateKey;
byte[] encryptedBytes, decryptedBytes;
Cipher cipher, cipher1;
String encrypted, decrypted;


//TODO:implementing Encryption method
public String Encrypt (String plain) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
    kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);
    kp = kpg.genKeyPair();
    publicKey = kp.getPublic();
    privateKey = kp.getPrivate();

    cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    encryptedBytes = cipher.doFinal(plain.getBytes());

    encrypted = bytesToString(encryptedBytes);
    return encrypted;

}

public String Decrypt (String result) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{

    cipher1=Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, privateKey);
    decryptedBytes = cipher1.doFinal(stringToBytes(result));
    decrypted = new String(decryptedBytes);
    return decrypted;

}

public  String bytesToString(byte[] b) {
    byte[] b2 = new byte[b.length + 1];
    b2[0] = 1;
    System.arraycopy(b, 0, b2, 1, b.length);
    return new BigInteger(b2).toString(36);
}

public  byte[] stringToBytes(String s) {
    byte[] b2 = new BigInteger(s, 36).toByteArray();
    return Arrays.copyOfRange(b2, 1, b2.length);
}

**Encrypt method **

private void PostMessages() {
            reference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                String key = dataSnapshot.getKey();
                String input = mInputText.getText().toString();
                String name = dataSnapshot.child("Name").getValue().toString();
                if (!input.equals("")) {

                    final String MessagesText = mInputText.getText().toString();

                    final String TextMessages = MessagesText;

                    if (MessagesText==""){
                        Toast.makeText(MainChatActivity.this, "please write a message ",Toast.LENGTH_SHORT).show();

                    }else {
                        try {
                            DataEncrypte =  EncrypteandDicrypye.Encrypt(TextMessages).toString();
                        } catch (NoSuchAlgorithmException e) {
                            e.printStackTrace();
                        } catch (NoSuchPaddingException e) {
                            e.printStackTrace();
                        } catch (InvalidKeyException e) {
                            e.printStackTrace();
                        } catch (IllegalBlockSizeException e) {
                            e.printStackTrace();
                        } catch (BadPaddingException e) {
                            e.printStackTrace();
                        }

                        String messagngerSender = "Messages/" + Registerid + "/" + ChatUserKey;
                        String messangerReciverId = "Messages/" + ChatUserKey + "/" + Registerid;

                        final DatabaseReference MessagesId = UserMesages.child("Messages").
                                child(Registerid).child(ChatUserKey).push();
                        String messages_pushId = MessagesId.getKey();

                        //String EncrypteMessage = Encrypte.Encrypt(MessagesText).toString();


                        Map messagesTextBody = new HashMap();
                        messagesTextBody.put("Message",DataEncrypte);
                        messagesTextBody.put("Name", name);
                        messagesTextBody.put("Time", ServerValue.TIMESTAMP);
                        messagesTextBody.put("from",Registerid);
                        Map messageDetails = new HashMap();
                        messageDetails.put(messagngerSender + "/" + messages_pushId, messagesTextBody);
                        messageDetails.put(messangerReciverId + "/" + messages_pushId, messagesTextBody);
                        UserMesages.updateChildren(messageDetails, new DatabaseReference.CompletionListener() {
                            @Override
                            public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                                if (databaseError != null) {
                                    System.out.println("ChatError" + databaseError.getMessage().toString());
                                }
                                mInputText.setText("");
                            }

                        });

                    }


                    }

                System.out.println("Data is exist " + dataSnapshot.child("User type").getValue().toString());
            }
        }

*For encrytion part every thing is working as expected * **Decryption code ** For decrytion part i have call the decrypt method in OnbindView holder

       RSA rsa = new RSA();



    try {
        String decryptedMessage = rsa.Decrypt(messages.getMessage());
        holder.messagesText.setText(decryptedMessage.toString());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }
    holder.messageUser.setText(messages.getName());
Alex
  • 77
  • 1
  • 9
  • not the exact answer but maybe gives you an idea : https://stackoverflow.com/a/51381469/8064640 – Bayar Şahintekin Sep 17 '18 at 08:20
  • What exception / problem exactly do you have? (Bayar is right, the best practice is to use symmetric encryption to encrypt data and RSA to encrypt the symmetric key). – gusto2 Sep 17 '18 at 08:45
  • The problem is when I retrieve the data from firebase database and call the decryption method in order to decrypt the data. the decryption method not working for no reason. I was thinking about symmetric encryption but the problem is that data encrypted and decrypt with the same key – Alex Sep 17 '18 at 13:08

0 Answers0