【问题标题】:how to encrypt/decrypt text in android studio on different activities如何在不同活动的android studio中加密/解密文本
【发布时间】:2019-04-12 17:26:58
【问题描述】:

我尝试在 android studio 中开发一个文本加密/解密应用程序。所以在 MainActivity.java 上我运行了一个加密和解密的示例代码。

MainActivity.java

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class MainActivity extends AppCompatActivity {

Button btn,btn2;
static final String TAG = "SymmetricAlgorithmAES";
String secr="k";
String secr2="d";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //code to use my specified defined key
    byte[] key = new byte[0];
    try {
        key = (secr+secr2).getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    MessageDigest sha = null;
    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    key = sha.digest(key);
    key = Arrays.copyOf(key, 16); // use only first 128 bit

    SecretKeySpec sks = new SecretKeySpec(key, "AES");

    // Original text
    String theTestText = "This is just a simple test";
    TextView tvorig = (TextView)findViewById(R.id.tvorig);
    tvorig.setText("\n[ORIGINAL]:\n" + theTestText + "\n");

    // Encode the original data with AES
    byte[] encodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.ENCRYPT_MODE, sks);
        encodedBytes = c.doFinal(theTestText.getBytes());
    } catch (Exception e) {
        Log.e(TAG, "AES encryption error");
    }
    TextView tvencoded = (TextView)findViewById(R.id.tvencoded);
    tvencoded.setText("" +
            Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "\n");

    // Decode the encoded data with AES
    byte[] decodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.DECRYPT_MODE, sks);
        decodedBytes = c.doFinal(encodedBytes);
    } catch (Exception e) {
        Log.e(TAG, "AES decryption error");
    }
    TextView tvdecoded = (TextView)findViewById(R.id.tvdecoded);
    tvdecoded.setText("[DECODED]:\n" + new String(decodedBytes) + "\n");

   }

上面的代码在正确的输出下正常工作。但是当我尝试修改代码并尝试在不同的活动中编写加密和解密时,但解密部分无法正常工作。

这是加密部分的代码,可以正常工作,没有任何错误。

加密.java

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Encryption extends AppCompatActivity {

static final String TAG = "SymmetricAlgorithmAES";
String secr="k";
String secr2="d";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.encryption);
    enc_text_edt=(EditText)findViewById(R.id.enc_text_edt);
    enc_text_btn=(Button)findViewById(R.id.enc_text_btn);
    enctv=(TextView)findViewById(R.id.enctv);

    //code to use my specified defined key
    byte[] key = new byte[0];
    try {
        key = (secr+secr2).getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    MessageDigest sha = null;
    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    key = sha.digest(key);
    key = Arrays.copyOf(key, 16); // use only first 128 bit

    SecretKeySpec sks = new SecretKeySpec(key, "AES");

    final SecretKeySpec finalSks = sks;
    enc_text_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            try {

                // Encode the original data with AES
                byte[] encodedBytes = null;
                try {
                    Cipher c = Cipher.getInstance("AES");
                    c.init(Cipher.ENCRYPT_MODE, finalSks);
                    encodedBytes = c.doFinal(enc_text_edt.getText().toString().getBytes());
                } catch (Exception e) {
                    Log.e(TAG, "AES encryption error");
                }


                enctv.setText("[ENCRYPTED]:\n" +
                        Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "\n");


                enc_text_edt.setText("");


            } catch (Exception e) {

                e.printStackTrace();
            }

        }
    });
}
}

解密代码

解密.java

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Decryption extends AppCompatActivity {

Button dec_text_btn;
TextView dec_edtext_view, dectv;

static final String TAG = "SymmetricAlgorithmAES";
String secr = "k";
String secr2 = "d";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.decryption);
    dec_text_btn = (Button) findViewById(R.id.dec_text_btn);
    dec_edtext_view = (EditText) findViewById(R.id.dec_edtext_view);
    dectv = (TextView) findViewById(R.id.dectv);


    //code to use my specified defined key
    byte[] key = new byte[0];
    try {
        key = (secr + secr2).getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    MessageDigest sha = null;
    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    key = sha.digest(key);
    key = Arrays.copyOf(key, 16); // use only first 128 bit

    SecretKeySpec sks = new SecretKeySpec(key, "AES");


    final SecretKeySpec finalSks = sks;
    dec_text_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            try {

                // Decode the encoded data with AES

                byte[] decodedBytes = null;
                try {
                    Cipher c = Cipher.getInstance("AES");
                    c.init(Cipher.DECRYPT_MODE, finalSks);
                    decodedBytes= c.doFinal(dec_edtext_view.getText().toString().getBytes());
                    } catch (Exception e) {
                        Log.e(TAG, "AES encryption error");
                    }

                    dectv.setText("[DECRYPTED]:\n" + new String(decodedBytes) + "\n");


                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "creptography exception see log cat....", Toast.LENGTH_SHORT).show();
                }
        }
    });
}
}

请帮我解决错误。在执行解密部分时直接显示异常“creptography exception see log cat”

【问题讨论】:

  • logcat 包含什么?
  • 另外,请检查嵌套的try-catch中是否存在任何异常并分享它,请

标签: java android encryption text cryptography


【解决方案1】:

阅读您的代码后,我认为我发现了问题,您编码为 Base64 但从未解码。在Encryption 中,您执行以下操作

enctv.setText("[ENCRYPTED]:\n" +
                        Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "\n");

我可以猜到用户将其复制到解密字段,但在他们点击按钮后你就这样做了

decodedBytes= c.doFinal(dec_edtext_view.getText().toString().getBytes());

而不是从 Base64 解码。 我还想补充几点: 你的安全不安全,当钥匙在这样的飞机站点时,你几乎没有获得任何安全层。

注1:

应使用SecureRandom 随机生成密钥。 您可以通过执行以下操作轻松做到这一点:

byte[] key = new byte[16];
        new SecureRandom().nextBytes(key);

注2:

使用initialization vector aka IV 这在用户输入相同消息的情况下很有用。例如,考虑以下场景,您加密“Hello World”,结果为“ABCDEFGHIJK”。现在你再次发送它,它又是“ABCDEFGHIJK”。 使用 IV,只要您为每条消息生成一个新的 IV,它每次都会有所不同,您应该将此 IV 附加到消息中,以便稍后在解密时提取它。

注3:

当声明Cipher 时,使用多个AES。 有一篇关于如何提高安全性和知识的好文章:article link

注4:

如果发生异常,不要像什么都没发生一样继续,您应该正确处理它,而不是继续执行取决于导致异常的代码。

注5:

更深入地学习 Java,而不是跳到密码学,你的字段应该是私有的,如果你可能打算稍后使用它,如果你确实检查它是否为 null,一些 final 不要声明 null。不要在获取字节中声明“UTF-8”,有一个常量声明 Charset,例如“UTF-8”,这很容易用 Charset.forName("UTF-8") 完成

【讨论】:

    【解决方案2】:

    我同意 OughtToPrevail 所说的一切。

    此外,您可能应该将所有这些从您的活动中取出并放入一个助手类中。这样它就可以重复使用,并且您可以使用如下所示的内容来测试它的输入和输出(无需复制和粘贴):

        public void myEncryptionTest(){
        String message = "This is the message to encrypt and decrypt.";
        String pass = "pass";
        String encryption = Crypto.myEncrypt(message.getBytes(), pass);
        byte[] decryption = Crypto.myDecrypt(encryption, pass);
        String decrypted = new String(decryption);
        Log.d("****DECRYPTION:  ", decrypted);
    }
    

    帮助程序类称为“Crypto”,您正在测试的两个静态函数是“myEncrypt”和“myDecrypt”。

    【讨论】:

      猜你喜欢
      • 2013-03-01
      • 2011-05-15
      • 2016-01-03
      • 1970-01-01
      • 2016-03-11
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多