In Android, various data encryption operations are required, such as data encryption for text message backup, password encryption for User Account Login, and encryption for transferring important data through server connections.
Here we will introduce MD5 encryption:
Case-driven:
12345678910111213141516171819202122232425262728 |
public class MD5Utils { // Perform md5 encryption. public static String encode(String password) { // MessageDigest is a class specifically used for encryption. try { MessageDigest messageDigest = MessageDigest.getInstance( "MD5" ); byte [] result = messageDigest.digest(password.getBytes()); // Obtain the encrypted number of character groups StringBuffer sb = new StringBuffer(); for ( byte b : result) { int num = b & 0xff ; // Here we want to increase the number of bytes to the int type, so that the original negative number is converted to a positive number. String hex = Integer.toHexString(num); // Convert the int value to a hexadecimal value. // The hexadecimal value may be the length of 1. In this case, you must add 0 in front of it, if (hex.length() == 1 ) { sb.append( 0 ); } sb.append(hex); } return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null ; } } } |
The MD5 encryption implementation method is blocked by Google, so this can only be used to understand its role like the black box test, in this case, the incoming string is converted into a 16-bit hexadecimal string to encrypt the string. & 0Xff has been explained in the middle. Here, I will record the basic knowledge of java, so it is easier to forget it.
Java 8 basic data types:
Type length (in bytes, one byte is 8 bits, that is, 0000 0000. If it is a word, it is 16 bits, 0000, 0000, and 0000)
Boolean-> 1
Char-> 2
Byte-> 1
Short-> 2
Int-> 4
Long-> 8
Float-> 4
Double-> 8
PS: in java, there is a string operation
Case-driven:
12345678910 |
public void test3() { <span style= "text-decoration: underline;" >String</span> password = "1203" ; byte [] bytes = password.getBytes(); for ( byte b: bytes) { System.out.println(b); } } |
The basic explanation is that java converts the content in the string to a byte array for output. The rule is as follows: