In Android, you need to encrypt various kinds of data, such as the data encryption of user's SMS backup, password encryption of user account login and encryption which is applied to the server connection to pass important data, which is very useful.
Here is an introduction to MD5 encryption:
Case-driven:
12345678910111213141516171819202122232425262728 |
public
class
MD5Utils {
// 进行md5的加密运算
public
static
String encode(String password) {
// MessageDigest专门用于加密的类
try
{
MessageDigest messageDigest = MessageDigest.getInstance(
"MD5"
);
byte
[] result = messageDigest.digest(password.getBytes());
// 得到加密后的字符组数
StringBuffer sb =
new
StringBuffer();
for
(
byte
b : result) {
int
num = b &
0xff
;
// 这里的是为了将原本是byte型的数向上提升为int型,从而使得原本的负数转为了正数
String hex = Integer.toHexString(num);
//这里将int型的数直接转换成16进制表示
//16进制可能是为1的长度,这种情况下,需要在前面补0,
if
(hex.length() ==
1
) {
sb.append(
0
);
}
sb.append(hex);
}
return
sb.toString();
}
catch
(NoSuchAlgorithmException e) {
e.printStackTrace();
return
null
;
}
}
}
|
MD5 encryption implementation is blocked by Google, so this can only think of the black box test to understand its role, then this is to convert the incoming string into a 16-bit 16-character string to play the role of encryption, the middle of the &0XFF has also been explained. Here by the way to record the basic knowledge of Java, not really more easily forgotten.
Java 8 basic data types:
Type length (in bytes, one byte is 8 bits that is 0000 0000, if the word is 16 bits 0000 0000 0000 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 you need to make here is that Java converts the contents of a string into a byte array for output, as follows:
- The English word one corresponds to one byte
- A number is usually a number corresponding to a byte
- Chinese words are generally a Chinese equivalent of 3 bytes to indicate. (Here is not very clear, why a Chinese corresponds to 3 bytes)
Android's simple encryption –MD5 encryption