java - Android Studio 无法解密 AES 中的消息

标签 java android-studio encryption aes

嗨,我尝试在一些开源代码消息应用程序中实现 aes。对于加密消息,我发现它的工作。但我很难解密回消息。

在这个类(class)中,我可以加密消息并且工作正常。

MessageActivity.java

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.message);

    messageView = (TextView) findViewById(R.id.message_view);

    final Button button = (Button) findViewById(R.id.btn_send);
    final EditText message = (EditText) findViewById(R.id.edit_message);

    this.setTitle("Group Chat");

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            String str = message.getText().toString();
            byte[] cipherText = null;
            try {
                cipherText = AESEncryption.encryptText(str, AESEncryption.thisKey());
            } catch (Exception e) {
                e.printStackTrace();
            }
            String msgStr = new String(cipherText);
            addMessage("This phone", str);
            message.setText("");

            // Send to other clients as a group chat message
            for (AllEncompasingP2PClient c : MeshNetworkManager.routingTable.values()) {
                if (c.getMac().equals(MeshNetworkManager.getSelf().getMac()))
                    continue;
                Sender.queuePacket(new Packet(Packet.TYPE.MESSAGE, msgStr.getBytes(), c.getMac(),
                        WiFiDirectBroadcastReceiver.MAC));
            }

        }
    });

接收器.java

/////////////// this messsage receiver part///////////////////////

byte[] thisMsg = p.getData();
String decryptedText = null;
 try {
 decryptedText = AESEncryption.decryptText(thisMsg, AESEncryption.thisKey());
 } catch (Exception e) {
  e.printStackTrace();
 }

final String message = p.getSenderMac() + " says:\n" + decryptedText;
final String msg = new String(p.getData());
final String name = p.getSenderMac();

//////////////////////////////////////


if (!MeshNetworkManager.routingTable.contains(p.getSenderMac())) {
    /*
     * Update your routing table if for some reason this
    * guy isn't in it
   */
MeshNetworkManager.routingTable.put(p.getSenderMac(),
new AllEncompasingP2PClient(p.getSenderMac(), p.getSenderIP(), 
p.getSenderMac(),
MeshNetworkManager.getSelf().getGroupOwnerMac()));
}

activity.runOnUiThread(new Runnable() {

@Override
public void run() {
if (activity.isVisible) {
Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
} else {
MessageActivity.addMessage(name, msg);
}
}
    });
updatePeerList();

AESEncryption.java

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
//import javax.xml.bind.DatatypeConverter;

public class AESEncryption {

public static SecretKey getSecretEncryptionKey() throws Exception{
    KeyGenerator generator = KeyGenerator.getInstance("AES");
    generator.init(128); // The AES key size in number of bits
    SecretKey secKey = generator.generateKey();
    return secKey;
}

public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
    byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
    return byteCipherText;
}

public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception {
    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.DECRYPT_MODE, secKey);
    byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
    return new String(bytePlainText);
}

public static SecretKey thisKey() throws Exception{

    SecretKey secKey = AESEncryption.getSecretEncryptionKey();

    return secKey;
}

}

在这个类中,我对解密的消息进行编码。但是当我运行代码时,消息不会解密并显示密文。如果有人可以纠正我,那就太好了。

最佳答案

同一消息的加密和解密必须使用相同的 key 。

加密和解密似乎没有使用相同的 key ,这两种方法都调用 SecretKey thisKey() 这似乎生成了一个随 secret 钥。

加密时调用SecretKey thisKey(),使用它进行加密并保存 key 以供解密时使用。解密时不要调用 SecretKey thisKey(),而是使用为加密创建的 key 。

关于java - Android Studio 无法解密 AES 中的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47643166/

相关文章:

android - "Program type already present"是什么意思?

Android Studio + Volley = NoClassDefFounderror?

python - 如何编码/解码一个简单的字符串

java - 服务内部的测试方法

java - Cellbrowser 在单元格上单击事件

java - 在没有监听器的情况下读取 RealtimeDatabase

c# - C# 中的 AES-XTS 实现

ios - 在 ios 上使用不受信任的证书加密数据

java - 如何在 Chrome 扩展中使用 GWT 获取当前页面 URL?

java - 如何找到将启动给定文件的程序的名称?