SoFunction
Updated on 2025-03-01

Detailed explanation of the commonly used data encryption method code of Android

Preface

Android requires data encryption in many occasions, such as: local login password encryption, network transmission data encryption, etc. The general encryption methods in android are as follows:

Or encrypted
AES encryption
RSA asymmetric encryption
MD5 encryption algorithm

Of course, there are other ways. Here we will introduce the above four encryption algorithms to use.

Or encryption algorithm

What is or encryption?

Or encryption is to perform or operate a certain byte, such as byte A^K = V, which is the encryption process;
When you put V^K, the result is A, that is, V^K = A, this is a reverse operation process, decryption process.

Or the operation efficiency is very high, of course, encryption is also a relatively simple encryption method, and the operation will not increase space, and the source data will still be as large as the encrypted data.

The sample code is as follows:

/**
    * Or encrypt and decrypt, suitable for encrypting parts of the entire file, such as the header and tail of the file
    * Encrypt the header and tail of the file, suitable for zip compression package encryption
    *
    * @param source Files that need to be encrypted
    * @param det Save the file name after encryption
    * @param key Encrypted key
    */
public static void encryptionFile(File source, File det, int key) {
	FileInputStream fis = null;
	FileOutputStream fos = null;
	try {
		fis = new FileInputStream(source);
		fos = new FileOutputStream(det);
		int size = 2048;
		byte buff[] = new byte[size];
		int count = (buff);
		/**zip package header encryption*/
		for (int i = 0; i < count; i++) {
			(buff[i] ^ key);
		}
		while (true) {
			count = (buff);
			/**zip package end encryption*/
			if (count < size) {
				for (int j = 0; j < count; j++) {
					(buff[j] ^ key);
				}
				break;
			}
			(buff, 0, count);
		}
		();
	}
	catch (IOException e) {
		();
	}
	finally {
		try {
			if (fis != null) {
				();
			}
			if (fos != null) {
				();
			}
		}
		catch (IOException e) {
			();
		}
	}
}
/**
    * Or encrypt and decrypt, suitable for encrypting the entire file
    *
    * @param source The path to encrypted files
    * @param det The path to save the file after encryption
    * @param key Encryption key
    */
private static void encryptionFile(String source, String det, int key) {
	FileInputStream fis = null;
	FileOutputStream fos = null;
	try {
		fis = new FileInputStream(source);
		fos = new FileOutputStream(det);
		int read;
		while ((read = ()) != -1) {
			(read ^ key);
		}
		();
	}
	catch (IOException e) {
		();
	}
	finally {
		try {
			if (fis != null) {
				();
			}
			if (fos != null) {
				();
			}
		}
		catch (IOException e) {
			();
		}
	}
}

Parts of the file can be encrypted, such as zip compression package, and the head and tail can be encrypted, because the zip head and tail hides information related to file compression. All, we only use or encryption algorithms for the head and tail to encrypt the entire zip file. If you do not decrypt and try to pressurize, it will fail.
You can also perform or encrypt the entire file or encrypt the algorithm, so when you decrypt it, it is actually a reverse process. You can use the same method and the same key to decrypt the encrypted file. Of course, the security of encryption in the future can be imagined, and it is not very secure, so encryption algorithms are generally used in less important scenarios. Since the algorithm is fast, the encryption speed is also fast.

AES encryption encryption algorithm

What is AES encryption

AES Symmetric Encryption

Advanced Encryption Standard (AES), also known as Rijndael encryption method in cryptography, is a block encryption standard adopted by the US federal government. This standard is used to replace the original DES, and has been analyzed by multiple parties and is widely used worldwide.

AES encryption key in Android must be 16/24/32 bit bytes, otherwise an exception will be thrown

Sample code:

private static final String TAG = "EncryptUtils";
private final static int MODE_ENCRYPTION = 1;
private final static int MODE_DECRYPTION = 2;
private final static String AES_KEY = "xjp_12345!^-=42#";
//AES key key must be 16 bitsprivate static byte[] encryption(int mode, byte[] content, String pwd) {
	try {
		Cipher cipher = ("AES/CFB/NoPadding");
		//AES encryption mode, CFB encryption mode		SecretKeySpec keySpec = new SecretKeySpec(("UTF-8"), "AES");
		//AES encryption method		IvParameterSpec ivSpec = new IvParameterSpec(("UTF-8"));
		(mode == MODE_ENCRYPTION ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, keySpec, ivSpec);
		return (content);
	}
	catch (NoSuchAlgorithmException | NoSuchPaddingException |
	        InvalidKeyException | IllegalBlockSizeException |
	        BadPaddingException | InvalidAlgorithmParameterException e) {
		();
		(TAG, "encryption failed... err: " + ());
	}
	catch (Exception e) {
		();
		(TAG, "encryption1 failed ...err: " + ());
	}
	return null;
}
/**
    * AES Encryption
    *
    * @param source The path to encrypted file
    * @param dest Encrypted file path
    */
public static void encryptByAES(String source, String dest) {
	encryptByAES(MODE_ENCRYPTION, source, dest);
}
public static void encryptByAES(int mode, String source, String dest) {
	(TAG, "start===encryptByAES");
	FileInputStream fis = null;
	FileOutputStream fos = null;
	try {
		fis = new FileInputStream(source);
		fos = new FileOutputStream(dest);
		int size = 2048;
		byte buff[] = new byte[size];
		byte buffResult[];
		while (((buff)) != -1) {
			buffResult = encryption(mode, buff, AES_KEY);
			if (buffResult != null) {
				(buffResult);
			}
		}
		(TAG, "end===encryptByAES");
	}
	catch (IOException e) {
		();
		(TAG, "encryptByAES failed err: " + ());
	}
	finally {
		try {
			if (fis != null) {
				();
			}
			if (fos != null) {
				();
			}
		}
		catch (IOException e) {
			();
		}
	}
}
/**
    * AES Decryption
    *
    * @param source The file path that needs to be decrypted
    * @param dest The path of the saved file after decryption
    */
public static void decryptByAES(String source, String dest) {
	encryptByAES(MODE_DECRYPTION, source, dest);
}

AES symmetric encryption, encryption and decryption are still a bit complicated compared to encryption, and their security is higher than encryption. AES encryption is not absolutely secure.

RSA asymmetric encryption

What is Rsa encryption?

The RSA algorithm is the most popular public key cryptography algorithm, using keys whose length can vary. RSA is the first algorithm that can be used for both data encryption and digital signatures.

The security of RSA depends on large-number decomposition. N less than 1024 bits has been proven to be unsafe. Moreover, since the RSA algorithm performs large-number calculations, the fastest case of RSA is also twice as slower than DES. This is the biggest defect of RSA, so it can only be used to encrypt a small amount of data or encryption keys, but RSA is still a high-intensity algorithm.

Code example:

/******************************************************************************
    * 1.What is RSA asymmetric encryption?
    * <p>
    * 2.
    *********************************************************
private final static String RSA = "RSA";
//Encryption method RSApublic final static int DEFAULT_KEY_SIZE = 1024;
private final static int DECRYPT_LEN = DEFAULT_KEY_SIZE / 8;
//Decryption lengthprivate final static int ENCRYPT_LEN = DECRYPT_LEN - 11;
//Encryption lengthprivate static final String DES_CBC_PKCS5PAD = "DES/CBC/PKCS5Padding";
//Encryption filling methodprivate final static int MODE_PRIVATE = 1;
//Private key encryptionprivate final static int MODE_PUBLIC = 2;
//Public key encryption/**
    * Randomly generate RSA key pairs, including PublicKey, PrivateKey
    *
    * @param keyLength The length of the key, the range is 512~2048, usually 1024
    * @return KeyPair
    */
public static KeyPair generateRSAKeyPair(int keyLength) {
	try {
		KeyPairGenerator kpg = ("RSA");
		(keyLength);
		return ();
	}
	catch (NoSuchAlgorithmException e) {
		();
		return null;
	}
}
/**
    * Get the private key
    *
    * @return PrivateKey
    * @throws NoSuchAlgorithmException
    * @throws InvalidKeySpecException
    */
public static PrivateKey getPrivateKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
	byte[] privateKey = (key, Base64.URL_SAFE);
	PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
	KeyFactory kf = (RSA);
	return (keySpec);
}
/**
    * Get the public key
    *
    * @param key
    * @return PublicKey
    * @throws NoSuchAlgorithmException
    * @throws InvalidKeySpecException
    */
public static PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
	byte[] publicKey = (key, Base64.URL_SAFE);
	X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
	KeyFactory kf = (RSA);
	return (keySpec);
}
/**
    * Private key encryption
    *
    * @param data
    * @param key
    * @return
    * @throws Exception
    */
public static byte[] encryptByRSA(byte[] data, Key key) throws Exception {
	// Data encryption	Cipher cipher = (RSA);
	(Cipher.ENCRYPT_MODE, key);
	return (data);
}
/**
    * Public key decryption
    *
    * @param data to be decrypted
    * @param key
    * @return byte[] Decrypt data
    */
public static byte[] decryptByRSA(byte[] data, Key key) throws Exception {
	// Data decryption	Cipher cipher = (RSA);
	(Cipher.DECRYPT_MODE, key);
	return (data);
}
public static void encryptByRSA(String source, String dest, Key key) {
	rasEncrypt(MODE_ENCRYPTION, source, dest, key);
}
public static void decryptByRSA(String source, String dest, Key key) {
	rasEncrypt(MODE_DECRYPTION, source, dest, key);
}
public static void rasEncrypt(int mode, String source, String dest, Key key) {
	(TAG, "start===encryptByRSA mode---&gt;&gt;" + mode);
	FileInputStream fis = null;
	FileOutputStream fos = null;
	try {
		fis = new FileInputStream(source);
		fos = new FileOutputStream(dest);
		int size = mode == MODE_ENCRYPTION ? ENCRYPT_LEN : DECRYPT_LEN;
		byte buff[] = new byte[size];
		byte buffResult[];
		while (((buff)) != -1) {
			buffResult = mode == MODE_ENCRYPTION ? encryptByRSA(buff, key) : decryptByRSA(buff, key);
			if (buffResult != null) {
				(buffResult);
			}
		}
		(TAG, "end===encryptByRSA");
	}
	catch (IOException e) {
		();
		(TAG, "encryptByRSA failed err: " + ());
	}
	catch (Exception e) {
		();
	}
	finally {
		try {
			if (fis != null) {
				();
			}
			if (fos != null) {
				();
			}
		}
		catch (IOException e) {
			();
		}
	}
}

MD5 encryption algorithm:

public String getMD5Code(String info) {
	try {
		MessageDigest md5 = ("MD5");
		(("UTF-8"));
		byte[] encryption = ();
		StringBuffer strBuf = new StringBuffer();
		for (int i = 0; i < ; i++) {
			if ((0xff & encryption[i]).length() == 1) {
				("0").append( 
				            (0xff & encryption[i]));
			} else {
				((0xff & encryption[i]));
			}
		}
		return ();
	}
	catch (Exception e) {
		// TODO: handle exception 
		return "";
	}
}

Public key encryption, private key decryption
Encryption time
The data will become larger after encryption

Summarize

The above is all the detailed explanation of the commonly used data encryption method code in Android, and I hope it will be helpful to everyone. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site.