如何在客户端Android上解密数据

时间:2018-09-16 05:31:25

标签: android firebase encryption-asymmetric android-security

我正在使用Firebase数据库存储数据,并使用RSA算法对聊天消息进行加密。实际上,我能够加密数据并将其存储在其中,但是不幸的是,我无法解密数据,也不清楚应该在哪里调用解密方法。我有一个称为RSA的类,其中包含两个方法。第一个被加密,可以很好地工作,第二个被称为解密,我不在应有的地方。 ** RSA类代码**

   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, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException {
        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;

    }

    //TODO:Here is the decryption methos
    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);
    }


}

消息类别

    public class Messages {
    private String Name, from;
    private String Message;
    private long Time;



    public Messages() {
    }

    public Messages(String name, String message, long time, String from) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
        Name = name;
        Message = message;
        Time = time;
        this.from = from;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public String getMessage() {
        return Message;
    }

    public void setMessage(String message) {
        Message = message;
    }

    public long getTime() {
        return Time;
    }

    public void setTime(long time) {
        Time = time;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }
}

聊天类

    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());
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        }

    private void DisplayMessage() {

UserMesages.child("Messages").child(Registerid).child(ChatUserKey).addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s)
    {
        Messages messages = dataSnapshot.getValue(Messages.class);
        Messageslistt.add(messages);
        messagesAdapter.notifyDataSetChanged();



    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

最后一次破坏适配器类

    public class MessagesAdapter  extends 
    RecyclerView.Adapter<MessagesAdapter.messagesViewHolder>{
    private FirebaseAuth Mauth;
    private List<Messages>UserMessagesList ;



    public MessagesAdapter(List<Messages>UserMessagesList)
    {
        this.UserMessagesList = UserMessagesList;
    }

    @NonNull
    @Override
    public messagesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext()).
                inflate(R.layout.chat_msg_row,parent,false);
        Mauth = FirebaseAuth.getInstance();
        return new messagesViewHolder(v);

    }

    @Override
    public void onBindViewHolder(@NonNull messagesViewHolder holder, int position) {
        String CurrentUser = Mauth.getCurrentUser().getUid();

        Messages messages = UserMessagesList.get(position);
         String SenderID = messages.getFrom();

        System.out.println("From"+SenderID);

        if (SenderID.equals(CurrentUser)){
            System.out.println("SenderID"+SenderID);
            holder.messagesText.setBackgroundResource(R.drawable.bubble1);
            holder.messageUser.setTextColor(Color.GREEN);
            holder.messagesText.setGravity(Gravity.END);
            holder.messageUser.setGravity(Gravity.END);
        }else {
            holder.messagesText.setBackgroundResource(R.drawable.bubble2);
            holder.messageUser.setTextColor(Color.BLUE);
            holder.messagesText.setGravity(Gravity.START);
            holder.messageUser.setGravity(Gravity.START);
        }
        holder.messageUser.setText(messages.getName());
        holder.messagesText.setText(messages.getMessage());

    }
private void ChatAppearance(boolean isMe, RecyclerView.ViewHolder holder){

}
    @Override
    public int getItemCount() {

        return UserMessagesList.size();
    }

    public class messagesViewHolder extends RecyclerView.ViewHolder
    {
        public TextView messagesText;
        public TextView messageUser;

        public messagesViewHolder(View view)
        {
            super(view);


            messagesText = (TextView)view.findViewById(R.id.Sendmessagetxt);
            messageUser = (TextView)view.findViewById(R.id.author);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您应该在onBindViewHolder中调用RSA的Decrypt方法,并将解密后的文本设置为messagetextView。

RSA rsa = new RSA():
String decryptedMessage = rsa.Decrypt(messages.getMessage());
holder.messagesText.setText(decryptedMessage);