📜  如何使用密码术在Android中加密和解密文本?

📅  最后修改于: 2021-05-09 17:21:28             🧑  作者: Mango

密码术是一种通过使用代码来保护信息和通信的技术,这样,只有那些希望获得该信息的人才能理解和处理该信息。从而防止未经授权的信息访问。前缀“ crypt”表示“隐藏”,后缀图形表示“写入”。

项目概况

在本文中,我们将构建一个Android应用程序,该应用程序可以分别使用Encoding和Decoding算法对消息进行加密解密。该应用程序的主页将为用户提供两个选项:

  1. 加密:这是将可读消息转换为不可读消息的过程。为此,我们使用编码算法。
  2. 解密:这是将数据或信息从不可读形式转换为可读形式的过程。为此,我们使用解码算法。

下面给出了一个示例GIF,以了解我们将在本文中做些什么。注意,我们将使用Java语言实现该项目。

使用加密示例GIF在Android中加密和解密文本

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

第2步:首先进入编码部分,您必须做一些准备工作

修改colors.xml文件:

XML
 
 
    #6200EE 
    #3700B3 
    #03DAC5 
    #0F9D58


XML

    
    


XML


  
    
    
  
        
  
    
  
    
  
        
        


Java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    Button enc, dec;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // link both the button variables with its id
        enc = findViewById(R.id.btVar1);
        dec = findViewById(R.id.btVar2);
          
        // onClick function for encryption
        enc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Intent function to move to another activity
                Intent intent = new Intent(getApplicationContext(), Encoder.class);
                startActivity(intent);
            }
        });
  
        // onClick function for decryption
        dec.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Intent function to move to another activity
                Intent intent = new Intent(getApplicationContext(), Decoder.class);
                startActivity(intent);
            }
        });
    }
}


Java
public class Encode {
    public static String encode(String s) {
        // create a string to add in the initial
        // binary code for extra security
        String ini = "11111111";
        int cu = 0;
          
        // create an array
        int arr[] = new int[11111111];
          
        // iterate through the string
        for (int i = 0; i < s.length(); i++) {
            // put the ascii value of 
            // each character in the array
            arr[i] = (int) s.charAt(i);
            cu++;
        }
        String res = "";
          
        // create another array
        int bin[] = new int[111];
        int idx = 0;
          
        // run a loop of the size of string
        for (int i1 = 0; i1 < cu; i1++) {
              
            // get the ascii value at position
            // i1 from the first array
            int temp = arr[i1];
              
            // run the second nested loop of same size 
            // and set 0 value in the second array
            for (int j = 0; j < cu; j++) bin[j] = 0;
            idx = 0;
              
            // run a while for temp > 0
            while (temp > 0) {
                // store the temp module 
                // of 2 in the 2nd array
                bin[idx++] = temp % 2;
                temp = temp / 2;
            }
            String dig = "";
            String temps;
              
            // run a loop of size 7
            for (int j = 0; j < 7; j++) {
                  
                // convert the integer to string
                temps = Integer.toString(bin[j]);
                  
                // add the string using 
                // concatenation function
                dig = dig.concat(temps);
            }
            String revs = "";
              
            // reverse the string
            for (int j = dig.length() - 1; j >= 0; j--) {
                char ca = dig.charAt(j);
                revs = revs.concat(String.valueOf(ca));
            }
            res = res.concat(revs);
        }
        // add the extra string to the binary code
        res = ini.concat(res);
          
        // return the encrypted code
        return res;
    }
}


Java
import android.util.Log;
  
public class Decode {
    public static String decode(String s) {
        String invalid = "Invalid Code";
  
        // create the same initial
        // string as in encode class
        String ini = "11111111";
        Boolean flag = true;
  
        // run a loop of size 8
        for (int i = 0; i < 8; i++) {
            // check if the initial value is same
            if (ini.charAt(i) != s.charAt(i)) {
                flag = false;
                break;
            }
        }
        String val = "";
  
        // reverse the encrypted code
        for (int i = 8; i < s.length(); i++) {
            char ch = s.charAt(i);
            val = val.concat(String.valueOf(ch));
        }
  
        // create a 2 dimensional array
        int arr[][] = new int[11101][8];
        int ind1 = -1;
        int ind2 = 0;
  
        // run a loop of size of the encrypted code
        for (int i = 0; i < val.length(); i++) {
  
            // check if the position of the
            // string if divisible by 7
            if (i % 7 == 0) {
                // start the value in other
                // column of the 2D array
                ind1++;
                ind2 = 0;
                char ch = val.charAt(i);
                arr[ind1][ind2] = ch - '0';
                ind2++;
            } else {
                // otherwise store the value
                // in the same column
                char ch = val.charAt(i);
                arr[ind1][ind2] = ch - '0';
                ind2++;
            }
        }
        // create an array
        int num[] = new int[11111];
        int nind = 0;
        int tem = 0;
        int cu = 0;
  
        // run a loop of size of the column
        for (int i = 0; i <= ind1; i++) {
            cu = 0;
            tem = 0;
            // convert binary to decimal and add them
            // from each column and store in the array
            for (int j = 6; j >= 0; j--) {
                int tem1 = (int) Math.pow(2, cu);
                tem += (arr[i][j] * tem1);
                cu++;
            }
            num[nind++] = tem;
        }
        String ret = "";
        char ch;
        // convert the decimal ascii number to its
        // char value and add them to form a decrypted
        // string using conception function
        for (int i = 0; i < nind; i++) {
            ch = (char) num[i];
            ret = ret.concat(String.valueOf(ch));
        }
        Log.e("dec", "text 11 - " + ret);
  
        // check if the encrypted code was
        // generated for this algorithm
        if (val.length() % 7 == 0 && flag == true) {
            // return the decrypted code
            return ret;
        } else {
            // otherwise return an invalid message
            return invalid;
        }
    }
}


XML


  
    
  
        
        
  
    
  
    
  
        
  
            
            
  
        
  
        
  
            
  
            
            
  
            
            


XML


  
    
  
        
        
  
    
  
    
  
        
  
            
            
  
        
  
        
  
            
            
  
            
  
            
            


Java
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class Encoder extends AppCompatActivity {
  
    EditText etenc;
    TextView enctv;
    ClipboardManager cpb;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_encoder);
  
        // link the edittext and textview with its id
        etenc = findViewById(R.id.etVar1);
        enctv = findViewById(R.id.tvVar1);
          
        // create a clipboard manager variable to copy text
        cpb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    }
  
    // onClick function of encrypt button
    public void enc(View view) {
        // get text from edittext
        String temp = etenc.getText().toString();
          
        // pass the string to the encryption 
        // algorithm and get the encrypted code
        String rv = Encode.encode(temp);
          
        // set the code to the edit text
        enctv.setText(rv);
    }
  
    // onClick function of copy text button
    public void cp2(View view) {
        // get the string from the textview and trim all spaces
        String data = enctv.getText().toString().trim();
          
        // check if the textview is not empty
        if (!data.isEmpty()) {
              
            // copy the text in the clip board
            ClipData temp = ClipData.newPlainText("text", data);
            cpb.setPrimaryClip(temp);
              
            // display message that the text has been copied
            Toast.makeText(this, "Copied", Toast.LENGTH_SHORT).show();
        }
    }
}


Java
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class Decoder extends AppCompatActivity {
  
    EditText etdec;
    TextView dectv;
    ClipboardManager cplboard;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_decoder);
  
        // link the edittext and textview with its id
        etdec = findViewById(R.id.etVar1);
        dectv = findViewById(R.id.tvVar2);
          
        // create a clipboard manager variable to copy text
        cplboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    }
  
    // onClick function of encrypt button
    public void dec(View view) {
        // get code from edittext
        String temp = etdec.getText().toString();
        Log.e("dec", "text - " + temp);
          
        // pass the string to the decryption algorithm 
        // and get the decrypted text
        String rv = Decode.decode(temp);
          
        // set the text to the edit text for display
        dectv.setText(rv);
        Log.e("dec", "text - " + rv);
    }
  
    // onClick function of copy text button
    public void cpl(View view) {
          
        // get the string from the textview and trim all spaces
        String data = dectv.getText().toString().trim();
          
        // check if the textview is not empty
        if (!data.isEmpty()) {
              
            // copy the text in the clip board
            ClipData temp = ClipData.newPlainText("text", data);
              
            // display message that the text has been copied
            Toast.makeText(this, "Copied", Toast.LENGTH_SHORT).show();
        }
    }
}


修改style.xml文件:将AppTheme更改为NoActionBar

XML格式


    
    

创建用于编码和解码算法的Java类:

我们需要创建两个Java类,分别用于编码和解码算法。为此,右键单击并选择新的Java类选项并创建它们,并将文件命名为EncodeDecode

为加密和解密屏幕创建空活动:

我们需要为加密和解密屏幕分别创建两个活动。为此,请右键单击并选择新的Empty Activity选项,然后创建两个活动,并将它们分别命名为EncoderDecoder

步骤3:建立应用程式的首页

XML代码用于构建活动的结构及其样式部分。在主页上,我们将在活动中心有两个用于加密和解密的按钮。在顶部,我们将使用TextView作为应用程序的标题。以下是activity_main.xml文件的代码:

XML格式



  
    
    
  
        
  
    
  
    
  
        
        

输出界面:

步骤4:使用MainActivity。 Java文件

MainActivity文件中,我们将使两个按钮起作用以打开新活动。为此,我们将使用一个意图 函数使我们能够从一项活动转移到另一项活动。 Intent函数的两个参数是当前活动的类和下一个活动的类。我们将在两个按钮的onClickListener内部调用此函数。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    Button enc, dec;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // link both the button variables with its id
        enc = findViewById(R.id.btVar1);
        dec = findViewById(R.id.btVar2);
          
        // onClick function for encryption
        enc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Intent function to move to another activity
                Intent intent = new Intent(getApplicationContext(), Encoder.class);
                startActivity(intent);
            }
        });
  
        // onClick function for decryption
        dec.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Intent function to move to another activity
                Intent intent = new Intent(getApplicationContext(), Decoder.class);
                startActivity(intent);
            }
        });
    }
}

步骤5:添加编码和解码算法

编码算法用于将文本转换为不可读的形式,而解码算法用于将编码文本转换为可读的形式。有许多算法可用于执行加密和解密。在此算法中,我们将使用加密算法将文本转换为二进制数。对于此项目,我们将使用自定义算法。您还可以在Java使用基本类型编码和解码算法。将以下代码添加到我们在步骤2中创建的Java编码和解码类中。

编码。 Java:在此类中,我们创建了一个返回函数,该函数将使用String变量的单个参数,并以String的形式返回加密的代码。

Java

public class Encode {
    public static String encode(String s) {
        // create a string to add in the initial
        // binary code for extra security
        String ini = "11111111";
        int cu = 0;
          
        // create an array
        int arr[] = new int[11111111];
          
        // iterate through the string
        for (int i = 0; i < s.length(); i++) {
            // put the ascii value of 
            // each character in the array
            arr[i] = (int) s.charAt(i);
            cu++;
        }
        String res = "";
          
        // create another array
        int bin[] = new int[111];
        int idx = 0;
          
        // run a loop of the size of string
        for (int i1 = 0; i1 < cu; i1++) {
              
            // get the ascii value at position
            // i1 from the first array
            int temp = arr[i1];
              
            // run the second nested loop of same size 
            // and set 0 value in the second array
            for (int j = 0; j < cu; j++) bin[j] = 0;
            idx = 0;
              
            // run a while for temp > 0
            while (temp > 0) {
                // store the temp module 
                // of 2 in the 2nd array
                bin[idx++] = temp % 2;
                temp = temp / 2;
            }
            String dig = "";
            String temps;
              
            // run a loop of size 7
            for (int j = 0; j < 7; j++) {
                  
                // convert the integer to string
                temps = Integer.toString(bin[j]);
                  
                // add the string using 
                // concatenation function
                dig = dig.concat(temps);
            }
            String revs = "";
              
            // reverse the string
            for (int j = dig.length() - 1; j >= 0; j--) {
                char ca = dig.charAt(j);
                revs = revs.concat(String.valueOf(ca));
            }
            res = res.concat(revs);
        }
        // add the extra string to the binary code
        res = ini.concat(res);
          
        // return the encrypted code
        return res;
    }
}

解码。 Java:在此类中,我们创建了一个返回函数,该函数将使用加密代码的String变量的单个参数,并以String的形式返回解密的文本。

Java

import android.util.Log;
  
public class Decode {
    public static String decode(String s) {
        String invalid = "Invalid Code";
  
        // create the same initial
        // string as in encode class
        String ini = "11111111";
        Boolean flag = true;
  
        // run a loop of size 8
        for (int i = 0; i < 8; i++) {
            // check if the initial value is same
            if (ini.charAt(i) != s.charAt(i)) {
                flag = false;
                break;
            }
        }
        String val = "";
  
        // reverse the encrypted code
        for (int i = 8; i < s.length(); i++) {
            char ch = s.charAt(i);
            val = val.concat(String.valueOf(ch));
        }
  
        // create a 2 dimensional array
        int arr[][] = new int[11101][8];
        int ind1 = -1;
        int ind2 = 0;
  
        // run a loop of size of the encrypted code
        for (int i = 0; i < val.length(); i++) {
  
            // check if the position of the
            // string if divisible by 7
            if (i % 7 == 0) {
                // start the value in other
                // column of the 2D array
                ind1++;
                ind2 = 0;
                char ch = val.charAt(i);
                arr[ind1][ind2] = ch - '0';
                ind2++;
            } else {
                // otherwise store the value
                // in the same column
                char ch = val.charAt(i);
                arr[ind1][ind2] = ch - '0';
                ind2++;
            }
        }
        // create an array
        int num[] = new int[11111];
        int nind = 0;
        int tem = 0;
        int cu = 0;
  
        // run a loop of size of the column
        for (int i = 0; i <= ind1; i++) {
            cu = 0;
            tem = 0;
            // convert binary to decimal and add them
            // from each column and store in the array
            for (int j = 6; j >= 0; j--) {
                int tem1 = (int) Math.pow(2, cu);
                tem += (arr[i][j] * tem1);
                cu++;
            }
            num[nind++] = tem;
        }
        String ret = "";
        char ch;
        // convert the decimal ascii number to its
        // char value and add them to form a decrypted
        // string using conception function
        for (int i = 0; i < nind; i++) {
            ch = (char) num[i];
            ret = ret.concat(String.valueOf(ch));
        }
        Log.e("dec", "text 11 - " + ret);
  
        // check if the encrypted code was
        // generated for this algorithm
        if (val.length() % 7 == 0 && flag == true) {
            // return the decrypted code
            return ret;
        } else {
            // otherwise return an invalid message
            return invalid;
        }
    }
}

步骤6:创建加密布局

在“加密”布局中,我们将在活动顶部具有一个TextView来显示其标题。接下来,我们将有一个视图来创建边距线。接下来,将有TextView和一个EditText来输入要加密的文本。在此之下,我们将有一个用于加密文本的按钮。为了显示加密的代码,我们有另一个带有按钮的TextView来复制它。以下是activity_encoder.xml文件的XML代码。

XML格式



  
    
  
        
        
  
    
  
    
  
        
  
            
            
  
        
  
        
  
            
  
            
            
  
            
            

输出界面:

步骤7:创建解密布局

解密布局中,我们将在活动顶部具有一个TextView来显示其标题。接下来,我们将有一个视图来创建边距线。接下来,将有TextViewEditText输入要解密的加密代码。在此之下,我们将有一个用于解密文本的按钮。为了显示解密的代码,我们有另一个带有按钮的TextView来复制它。以下是activity_decoder.xml文件的XML代码。

XML格式



  
    
  
        
        
  
    
  
    
  
        
  
            
            
  
        
  
        
  
            
            
  
            
  
            
            

输出界面:

步骤8:使用编码器。 Java文件

编码器中。 Java文件,我们会调用该函数,我们在第5步(编码Java)文件中创建。首先,我们将从EditText获得String,然后将值传递给encode函数。这将返回给我们该字符串的加密代码。之后,我们将代码设置为TextView ,如果不为空,我们将允许用户将代码复制到剪贴板中。要执行加密函数,请在按钮中使用onClick方法。同样,我们还设置了onClick()函数,用于将代码复制到剪贴板中的按钮上。以下是编码器的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class Encoder extends AppCompatActivity {
  
    EditText etenc;
    TextView enctv;
    ClipboardManager cpb;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_encoder);
  
        // link the edittext and textview with its id
        etenc = findViewById(R.id.etVar1);
        enctv = findViewById(R.id.tvVar1);
          
        // create a clipboard manager variable to copy text
        cpb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    }
  
    // onClick function of encrypt button
    public void enc(View view) {
        // get text from edittext
        String temp = etenc.getText().toString();
          
        // pass the string to the encryption 
        // algorithm and get the encrypted code
        String rv = Encode.encode(temp);
          
        // set the code to the edit text
        enctv.setText(rv);
    }
  
    // onClick function of copy text button
    public void cp2(View view) {
        // get the string from the textview and trim all spaces
        String data = enctv.getText().toString().trim();
          
        // check if the textview is not empty
        if (!data.isEmpty()) {
              
            // copy the text in the clip board
            ClipData temp = ClipData.newPlainText("text", data);
            cpb.setPrimaryClip(temp);
              
            // display message that the text has been copied
            Toast.makeText(this, "Copied", Toast.LENGTH_SHORT).show();
        }
    }
}

步骤9:使用解码器。 Java文件

解码器中。 Java文件,我们将调用在步骤5 (解码Java )文件中创建的函数。首先,我们将从EditText获取加密的代码,然后将其值传递给解码函数。这将返回给我们该字符串的解密文本。之后,我们将文本设置为TextView ,如果不为空,我们将允许用户将代码复制到剪贴板中。要执行解密函数,在按钮中使用onClick()方法。同样,我们还设置了onClick()函数,用于将代码复制到剪贴板中的按钮上。以下是解码器的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class Decoder extends AppCompatActivity {
  
    EditText etdec;
    TextView dectv;
    ClipboardManager cplboard;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_decoder);
  
        // link the edittext and textview with its id
        etdec = findViewById(R.id.etVar1);
        dectv = findViewById(R.id.tvVar2);
          
        // create a clipboard manager variable to copy text
        cplboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    }
  
    // onClick function of encrypt button
    public void dec(View view) {
        // get code from edittext
        String temp = etdec.getText().toString();
        Log.e("dec", "text - " + temp);
          
        // pass the string to the decryption algorithm 
        // and get the decrypted text
        String rv = Decode.decode(temp);
          
        // set the text to the edit text for display
        dectv.setText(rv);
        Log.e("dec", "text - " + rv);
    }
  
    // onClick function of copy text button
    public void cpl(View view) {
          
        // get the string from the textview and trim all spaces
        String data = dectv.getText().toString().trim();
          
        // check if the textview is not empty
        if (!data.isEmpty()) {
              
            // copy the text in the clip board
            ClipData temp = ClipData.newPlainText("text", data);
              
            // display message that the text has been copied
            Toast.makeText(this, "Copied", Toast.LENGTH_SHORT).show();
        }
    }
}

输出:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!