The implementation of encrypting and decrypting files in Android _android

Source: Internet
Author: User
Tags decrypt integer division

Now there is a need in the project, the video and documents downloaded in the project are not allowed to play through other players, in training institutions such a lot of demand. To prevent someone from handing over a piece of money, copy all the courseware to someone else. The training institutions are certainly unwilling to do such things. Now there is a demand in my project. Here is a description of my implementation.

Process and principle of file encryption and decryption

1, encryption methods: storage files, from the input stream to intercept the file byte array, the byte array encryption, as the encryption of the way and algorithm can be based on the requirements, and then the encrypted byte array written to the file, the final generation of encrypted files;

2, decryption method: the same as the encryption method, but the byte data to decrypt, and finally generate clear documents;

3, encryption algorithm: The Android system itself introduced the Javax package of the cipher class, this class provides a variety of general encryption, such as AES symmetric encryption, etc., the program has a Cipherutil tool class, There are some simple use of cipher AES encryption and decryption method; Of course, it is best to study the use of cipher class;

4, Attention matters:

    1. How to tell if a file is an encrypted file, the simplest way is to encrypt the file after the unified addition of a suffix name, and then after decryption to remove the suffix name, restore back to the original file format; For example, the unified suffix of the ciphertext file is named ". Cipher", and the plaintext file is named "Test. txt". Encrypted ciphertext file should be "test. Txt.cipher";
    2. There is an important note to encrypt the file, that is, the encrypted ciphertext and the length of the clear text is the same, if the file read all byte array at a time to encrypt the words do not worry about this problem, but when the file read the encryption or segmented encryption, you have to consider this problem, The most convenient way is to ensure that the plaintext and encryption after the length of the cipher is the same; if the length is different, because it is segmented encryption, the cipher is a section of the ciphertext mosaic, decryption will not find every piece of ciphertext, because I do not know the length of the cipher text is how much;

Main code

/** Custom implements a simple file encryption decryption tool * Created by Zhangshuo on 2016/6/28.  */public class Customfilecipherutil {/** * The suffix of the encrypted file/public static final String Cipher_text_suffix = 
 
  ". Cipher"; 
 
  /** * Encryption and decryption in 32K bytes for the Add and decrypt calculation * * private static final int cipher_buffer_lenght = 32 * 1024; /** * Encryption, here is mainly to demonstrate the principle of encryption, not with what the actual encryption algorithm * * @param filePath Clear Text File absolute path * @return/public static Boolean 
      Encrypt (String FilePath, Cipherlistener Listener) {try {long starttime = System.currenttimemillis (); 
      File F = new file (FilePath); 
      Randomaccessfile RAF = new Randomaccessfile (f, "RW"); 
      Long totallenght = Raf.length (); 
 
      FileChannel channel = Raf.getchannel (); 
      Long multiples = totallenght/cipher_buffer_lenght; 
 
      Long remainder = totallenght% Cipher_buffer_lenght; 
      Mappedbytebuffer buffer = null; 
      BYTE tmp; 
 
      BYTE Rawbyte; 
    First encrypt the partial division for (int i = 0; i < multiples i++) {    Buffer = Channel.map (FileChannel.MapMode.READ_WRITE, I * cipher_buffer_lenght, (i + 1) * cipher_buffer_l 
 
        Enght); 
          The encryption method here is simple, just a simple XOR or calculation for (int j = 0; j < cipher_buffer_lenght; ++j) {rawbyte = Buffer.get (j); 
          TMP = (byte) (rawbyte ^ j); 
 
          Buffer.put (J, TMP); 
          if (null!= listener) {listener.onprogress (i * cipher_buffer_lenght + j, totallenght); 
        } buffer.force (); 
      Buffer.clear (); //The remainder part encryption buffer = Channel.map (FileChannel.MapMode.READ_WRITE, multiples * cipher_buffer_len 
 
      GHT, multiples * cipher_buffer_lenght + remainder); 
        for (int j = 0; j < remainder; ++j) {rawbyte = Buffer.get (j); 
        TMP = (byte) (rawbyte ^ j); 
 
        Buffer.put (J, TMP); 
        if (null!= listener) {listener.onprogress (Multiples * cipher_buffer_lenght + j, totallenght); }} BUFFER.FORce (); 
 
      Buffer.clear (); 
      Channel.close (); 
 
      Raf.close (); 
      Rename the encrypted file to add the. CIPHER suffix//f.renameto (New File (F.getpath () + Cipher_text_suffix)); 
      LOG.D ("Encrypted When:", (System.currenttimemillis ()-starttime)/1000 + "s"); 
    return true; 
      catch (Exception e) {e.printstacktrace (); 
    return false; }/** * Decryption, here is mainly to demonstrate the principle of encryption, not with what the actual encryption algorithm * * @param filePath Ciphertext file absolute path, the file needs to be. Cipher end will think that in fact can decrypt the text * @return */public static Boolean decrypt (String FilePath, Cipherlistener Listener) {try {long Startti 
      me = System.currenttimemillis (); 
File F = new file (FilePath);  
if (!f.getpath (). toLowerCase (). EndsWith (Cipher_text_suffix)) {////suffix is different, the ciphertext//return false is considered not to be decrypted; 
      } randomaccessfile RAF = new Randomaccessfile (f, rw); 
      Long totallenght = Raf.length (); 
 
      FileChannel channel = Raf.getchannel (); Long multiples = Totallenght/cipher_Buffer_lenght; 
 
      Long remainder = totallenght% Cipher_buffer_lenght; 
      Mappedbytebuffer buffer = null; 
      BYTE tmp; 
 
      BYTE Rawbyte; First decrypt the integer division for (int i = 0; i < multiples i++) {buffer = Channel.map (FILECHANNEL.MAPMODE.R 
 
        Ead_write, I * cipher_buffer_lenght, (i + 1) * cipher_buffer_lenght); 
          The decryption method here is simple, just a simple XOR or calculation for (int j = 0; j < cipher_buffer_lenght; ++j) {rawbyte = Buffer.get (j); 
          TMP = (byte) (rawbyte ^ j); 
 
          Buffer.put (J, TMP); 
          if (null!= listener) {listener.onprogress (i * cipher_buffer_lenght + j, totallenght); 
        } buffer.force (); 
      Buffer.clear (); //The remainder part of the decryption buffer = Channel.map (FileChannel.MapMode.READ_WRITE, multiples * cipher_buffer_len 
 
      GHT, multiples * cipher_buffer_lenght + remainder); for (int j = 0; j < remainder; ++j) {rawbyte = Buffer.gET (j); 
        TMP = (byte) (rawbyte ^ j); 
 
        Buffer.put (J, TMP); 
        if (null!= listener) {listener.onprogress (Multiples * cipher_buffer_lenght + j, totallenght); 
      } buffer.force (); 
 
      Buffer.clear (); 
      Channel.close (); 
 
      Raf.close (); Rename the encrypted file to add the. CIPHER suffix//f.renameto (New File (F.getpath (). substring (F.getpath (). toLowerCase (). IndexOf (Cipher_ 
 
      Text_suffix))); 
      LOG.D ("When decrypted:", (System.currenttimemillis ()-StartTime)/1000 + "s"); 
    return true; 
      catch (Exception e) {e.printstacktrace (); 
    return false; }/** * Listener for decryption progress/public interface cipherlistener{void OnProgress (long, long 
  ); 
 } 
}

Effect as shown:

The code is so much, there are comments. This need can be used directly in the future. The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.