如何解密使用RSA对数Android加密的数据

时间:2018-09-17 08:11:18

标签: android android-studio encryption android-security

我目前正在开发一个需要我加密聊天消息的应用程序。此外,我设法使用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
{
    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);
}

**加密方法**

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

*对于加密部分,所有事情都按预期运行* **解密代码** 对于解密部分,我已经在OnbindView持有者中调用了解密方法

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

0 个答案:

没有答案