Java encryption 1

Source: Internet
Author: User
Encryption and decryption were once an important component of my graduation project. After many years of work, it was too simple to recall the encryption and decryption algorithm at that time.
To put it bluntly, here we mainly describe some encryption and decryption algorithms implemented by Java, and finally introduce digital certificates.
For example, the basic one-way encryption algorithm:

• Base64 strictly speaking, it is an encoding format, not an encryption algorithm
• MD5 (Message Digest algorithm 5, information digest algorithm)
• Sha (secure hash algorithm, Security Hash Algorithm)
• HMAC (Hash Message Authentication code, hash message authentication code)

Complex Symmetric encryption (DES, PBE) and asymmetric encryption algorithms:

• Des (Data Encryption Standard, data encryption algorithm)
• PBE (password-based encryption, password-based verification)
• RSA (algorithm name: Ron Rivest, adishamir, and Leonard Adleman)
• DH (Diffie-Hellman algorithm, key consistency Protocol)
• DSA (digital signature algorithm, digital signature)
• ECC (elliptic curves cryptography, Elliptic Curve Cryptography)

This article briefly introduces several methods of base64, MD5, Sha, and HMAC.
MD5, Sha, and HMAC encryption algorithms are non-reversible encryption methods that cannot be decrypted. We usually only use them as the basis for encryption. The preceding three types of encryption are not reliable.

Base64
According to rfc2045, base64 is defined as base64 content Transfer Encoding. It is designed to describe the 8-bit bytes of any sequence as a form that is not easily recognized by people. (The base64 content-transfer-encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable .)
Common in mail and HTTP encryption, intercepting HTTP information, you will find that the username and password fields for login operations are encrypted by base64.

The Java code is as follows:

Java code
1 ./**
2. * base64 decryption
3 .*
4. * @ Param key
5. * @ return
6. * @ throws exception
7 .*/
8. Public static byte [] decryptbase64 (string key) throws exception {
9. Return (New base64decoder (). decodebuffer (key );
10 .}
11.
12 ./**
13. * base64 Encryption
14 .*
15. * @ Param key
16. * @ return
17. * @ throws exception
18 .*/
19. Public static string encryptbase64 (byte [] Key) throws exception {
20. Return (New base64encoder (). encodebuffer (key );
21 .}
/**
* Base64 decryption
*
* @ Param key
* @ Return
* @ Throws exception
*/
Public static byte [] decryptbase64 (string key) throws exception {
Return (New base64decoder (). decodebuffer (key );
}

/**
* Base64 Encryption
*
* @ Param key
* @ Return
* @ Throws exception
*/
Public static string encryptbase64 (byte [] Key) throws exception {
Return (New base64encoder (). encodebuffer (key );
}

The main classes are base64encoder and base64decoder. We only need to know how to use them. In addition, the number of BITs generated after base encryption is a multiple of 8. If the number of BITs is not enough, fill the bits with =.

MD5
MD5 -- message-Digest algorithm 5 (Information-Digest algorithm) is widely used in encryption and decryption technologies and is often used for file verification. Verification? No matter how large the file is, the unique MD5 value can be generated after MD5. For example, the current ISO verification is MD5 verification. How to use it? Of course, the ISO is generated after MD5. A friend who downloads Linux-ISO has seen the MD5 string next to the download link. Is used to verify whether the files are consistent.

The Java code is as follows:

Java code
1 ./**
2. * MD5 Encryption
3 .*
4. * @ Param data
5. * @ return
6. * @ throws exception
7 .*/
8. Public static byte [] encryptmd5 (byte [] data) throws exception {
9.
10. messagedigest MD5 = messagedigest. getinstance (key_md5 );
11. md5.update (data );
12.
13. Return md5.digest ();
14.
15 .}
/**
* MD5 Encryption
*
* @ Param data
* @ Return
* @ Throws exception
*/
Public static byte [] encryptmd5 (byte [] data) throws exception {

Messagedigest MD5 = messagedigest. getinstance (key_md5 );
Md5.update (data );

Return md5.digest ();

}

We usually do not directly use the above MD5 encryption. Usually, the byte array generated by MD5 is sent to base64 and then encrypted to obtain the corresponding string.

Sha
SHA (secure hash algorithm, Security Hash Algorithm), digital signatures, and other important cryptographic tools are widely used in information security fields such as e-commerce. Although Sha and MD5 are cracked through the collision method, Sha is still recognized as a secure encryption algorithm, which is more secure than MD5.

The Java code is as follows:

Java code
1 ./**
2. * Sha Encryption
3 .*
4. * @ Param data
5. * @ return
6. * @ throws exception
7 .*/
8. Public static byte [] encryptsha (byte [] data) throws exception {
9.
10. messagedigest Sha = messagedigest. getinstance (key_sha );
11. Sha. Update (data );
12.
13. Return Sha. Digest ();
14.
15 .}
16 .}
/**
* Sha Encryption
*
* @ Param data
* @ Return
* @ Throws exception
*/
Public static byte [] encryptsha (byte [] data) throws exception {

Messagedigest Sha = messagedigest. getinstance (key_sha );
Sha. Update (data );

Return Sha. Digest ();

}
}

HMAC
HMAC (Hash Message Authentication code, hash message authentication code, and key-based hash algorithm authentication protocol. The message authentication code uses a public function and a key to generate a fixed-length value as the authentication identifier, which identifies the integrity of the message. Use a key to generate a small data block of a fixed size, that is, Mac, and add it to the message for transmission. The receiver uses the key shared with the sender for authentication.

The Java code is as follows:

Java code
1 ./**
2. * initialize the HMAC key
3 .*
4. * @ return
5. * @ throws exception
6 .*/
7. Public static string initmackey () throws exception {
8. keygenerator = keygenerator. getinstance (key_mac );
9.
10. secretkey = keygenerator. generatekey ();
11. Return encryptbase64 (secretkey. getencoded ());
12 .}
13.
14 ./**
15. * HMAC Encryption
16 .*
17. * @ Param data
18. * @ Param key
19. * @ return
20. * @ throws exception
21 .*/
22. Public static byte [] encrypthmac (byte [] data, string key) throws exception {
23.
24. secretkey = new secretkeyspec (decryptbase64 (key), key_mac );
25. Mac = Mac. getinstance (secretkey. getalgorithm ());
26. Mac. INIT (secretkey );
27.
28. Return Mac. dofinal (data );
29.
30 .}

/**
* Initialize the HMAC key.
*
* @ Return
* @ Throws exception
*/
Public static string initmackey () throws exception {
Keygenerator = keygenerator. getinstance (key_mac );

Secretkey = keygenerator. generatekey ();
Return encryptbase64 (secretkey. getencoded ());
}

/**
* HMAC Encryption
*
* @ Param data
* @ Param key
* @ Return
* @ Throws exception
*/
Public static byte [] encrypthmac (byte [] data, string key) throws exception {

Secretkey = new secretkeyspec (decryptbase64 (key), key_mac );
Mac = Mac. getinstance (secretkey. getalgorithm ());
Mac. INIT (secretkey );

Return Mac. dofinal (data );

}

A complete class is provided as follows:

Java code
1. Import java. Security. messagedigest;
2.
3. Import javax. crypto. keygenerator;
4. Import javax. crypto. Mac;
5. Import javax. crypto. secretkey;
6.
7. Import sun. Misc. base64decoder;
8. Import sun. Misc. base64encoder;
9.
10 ./**
11. * basic encryption component
12 .*
13. * @ author liangdong
14. * @ versions 1.0
15. * @ since 1.0
16 .*/
17. Public abstract class coder {
18. Public static final string key_sha = "Sha ";
19. Public static final string key_md5 = "MD5 ";
20.
21 ./**
22. * The Mac algorithm can be any of the following algorithms:
23 .*
24 .*

  25.     * HmacMD5   26.     * HmacSHA1   27.     * HmacSHA256   28.     * HmacSHA384   29.     * HmacSHA512  30.     * 

31 .*/
32. Public static final string key_mac = "hmacmd5 ";
33.
34 ./**
35. * base64 decryption
36 .*
37. * @ Param key
38. * @ return
39. * @ throws exception
40 .*/
41. Public static byte [] decryptbase64 (string key) throws exception {
42. Return (New base64decoder (). decodebuffer (key );
43 .}
44.
45 ./**
46. * base64 Encryption
47 .*
48. * @ Param key
49. * @ return
50. * @ throws exception
51 .*/
52. Public static string encryptbase64 (byte [] Key) throws exception {
53. Return (New base64encoder (). encodebuffer (key );
54 .}
55.
56 ./**
57. * MD5 Encryption
58 .*
59. * @ Param data
60. * @ return
61. * @ throws exception
62 .*/
63. Public static byte [] encryptmd5 (byte [] data) throws exception {
64.
65. messagedigest MD5 = messagedigest. getinstance (key_md5 );
66. md5.update (data );
67.
68. Return md5.digest ();
69.
70 .}
71.
72 ./**
73. * Sha Encryption
74 .*
75. * @ Param data
76. * @ return
77. * @ throws exception
78 .*/
79. Public static byte [] encryptsha (byte [] data) throws exception {
80.
81. messagedigest Sha = messagedigest. getinstance (key_sha );
82. Sha. Update (data );
83.
84. Return Sha. Digest ();
85.
86 .}
87.
88 ./**
89. * initialize the HMAC key
90 .*
91. * @ return
92. * @ throws exception
93 .*/
94. Public static string initmackey () throws exception {
95. keygenerator = keygenerator. getinstance (key_mac );
96.
97. secretkey = keygenerator. generatekey ();
98. Return encryptbase64 (secretkey. getencoded ());
99 .}
100.
101 ./**
102. * HMAC Encryption
103 .*
104. * @ Param data
105. * @ Param key
106. * @ return
107. * @ throws exception
108 .*/
109. Public static byte [] encrypthmac (byte [] data, string key) throws exception {
110.
111. secretkey = new secretkeyspec (decryptbase64 (key), key_mac );
112. Mac = Mac. getinstance (secretkey. getalgorithm ());
113. Mac. INIT (secretkey );
114.
115. Return Mac. dofinal (data );
116.
117 .}
118 .}
Import java. Security. messagedigest;

Import javax. crypto. keygenerator;
Import javax. crypto. Mac;
Import javax. crypto. secretkey;

Import sun. Misc. base64decoder;
Import sun. Misc. base64encoder;

/**
* Basic encryption component
*
* @ Author liangdong
* @ Version 1.0
* @ Since 1.0
*/
Public abstract class coder {
Public static final string key_sha = "Sha ";
Public static final string key_md5 = "MD5 ";

/**
* The Mac algorithm can be any of the following algorithms:
*
*

 * HmacMD5  * HmacSHA1  * HmacSHA256  * HmacSHA384  * HmacSHA512 * 

*/
Public static final string key_mac = "hmacmd5 ";

/**
* Base64 decryption
*
* @ Param key
* @ Return
* @ Throws exception
*/
Public static byte [] decryptbase64 (string key) throws exception {
Return (New base64decoder (). decodebuffer (key );
}

/**
* Base64 Encryption
*
* @ Param key
* @ Return
* @ Throws exception
*/
Public static string encryptbase64 (byte [] Key) throws exception {
Return (New base64encoder (). encodebuffer (key );
}

/**
* MD5 Encryption
*
* @ Param data
* @ Return
* @ Throws exception
*/
Public static byte [] encryptmd5 (byte [] data) throws exception {

Messagedigest MD5 = messagedigest. getinstance (key_md5 );
Md5.update (data );

Return md5.digest ();

}

/**
* Sha Encryption
*
* @ Param data
* @ Return
* @ Throws exception
*/
Public static byte [] encryptsha (byte [] data) throws exception {

Messagedigest Sha = messagedigest. getinstance (key_sha );
Sha. Update (data );

Return Sha. Digest ();

}

/**
* Initialize the HMAC key.
*
* @ Return
* @ Throws exception
*/
Public static string initmackey () throws exception {
Keygenerator = keygenerator. getinstance (key_mac );

Secretkey = keygenerator. generatekey ();
Return encryptbase64 (secretkey. getencoded ());
}

/**
* HMAC Encryption
*
* @ Param data
* @ Param key
* @ Return
* @ Throws exception
*/
Public static byte [] encrypthmac (byte [] data, string key) throws exception {

Secretkey = new secretkeyspec (decryptbase64 (key), key_mac );
Mac = Mac. getinstance (secretkey. getalgorithm ());
Mac. INIT (secretkey );

Return Mac. dofinal (data );

}
}

Then a test class is provided:

Java code
1. Import static org. JUnit. Assert .*;
2.
3. Import org. JUnit. test;
4.
5 ./**
6 .*
7. * @ author liangdong
8. * @ Version 1.0
9. * @ since 1.0
10 .*/
11. Public class codertest {
12.
13. @ Test
14. Public void test () throws exception {
15. String inputstr = "simple encryption ";
16. system. Err. println ("Original:/N" + inputstr );
17.
18. byte [] inputdata = inputstr. getbytes ();
19. String code = coder. encryptbase64 (inputdata );
20.
21. system. Err. println ("base64 encrypted:/N" + Code );
22.
23. byte [] Output = coder. decryptbase64 (CODE );
24.
25. String outputstr = new string (output );
26.
27. system. Err. println ("base64 decrypted:/N" + outputstr );
28.
29. // verify base64 encryption/Decryption consistency
30. assertequals (inputstr, outputstr );
31.
32. // verify that MD5 encryption for the same content is consistent
33. assertarrayequals (CODER. encryptmd5 (inputdata), coder
34 .. encryptmd5 (inputdata ));
35.
36. // verify that sha is consistent with the encryption of the same content
37. assertarrayequals (CODER. encryptsha (inputdata), coder
38 .. encryptsha (inputdata ));
39.
40. String key = coder. initmackey ();
41. system. Err. println ("Mac key:/N" + key );
42.
43. // verify that HMAC encrypts the same key for the same content.
44. assertarrayequals (CODER. encrypthmac (inputdata, Key), coder. encrypthmac (
45. inputdata, key ));
46.
47. biginteger MD5 = new biginteger (CODER. encryptmd5 (inputdata ));
48. system. Err. println ("MD5:/N" + md5.tostring (16 ));
49.
50. biginteger Sha = new biginteger (CODER. encryptsha (inputdata ));
51. system. Err. println ("Sha:/N" + Sha. tostring (32 ));
52.
53. biginteger MAC = new biginteger (CODER. encrypthmac (inputdata, inputstr ));
54. system. Err. println ("HMAC:/N" + Mac. tostring (16 ));
55 .}
56 .}
Import static org. JUnit. Assert .*;

Import org. JUnit. test;

/**
*
* @ Author liangdong
* @ Version 1.0
* @ Since 1.0
*/
Public class codertest {

@ Test
Public void test () throws exception {
String inputstr = "simple encryption ";
System. Err. println ("Original:/N" + inputstr );

Byte [] inputdata = inputstr. getbytes ();
String code = coder. encryptbase64 (inputdata );

System. Err. println ("base64 encrypted:/N" + Code );

Byte [] Output = coder. decryptbase64 (CODE );

String outputstr = new string (output );

System. Err. println ("base64 decrypted:/N" + outputstr );

// Verify the consistency of base64 encryption and decryption
Assertequals (inputstr, outputstr );

// Verify that MD5 encryption for the same content is consistent
Assertarrayequals (CODER. encryptmd5 (inputdata), coder
. Encryptmd5 (inputdata ));

// Verify that sha is consistent with the encryption of the same content
Assertarrayequals (CODER. encryptsha (inputdata), coder
. Encryptsha (inputdata ));

String key = coder. initmackey ();
System. Err. println ("Mac key:/N" + key );

// Verify that HMAC encrypts the same key for the same content.
Assertarrayequals (CODER. encrypthmac (inputdata, Key), coder. encrypthmac (
Inputdata, key ));

Biginteger MD5 = new biginteger (CODER. encryptmd5 (inputdata ));
System. Err. println ("MD5:/N" + md5.tostring (16 ));

Biginteger Sha = new biginteger (CODER. encryptsha (inputdata ));
System. Err. println ("Sha:/N" + Sha. tostring (32 ));

Biginteger MAC = new biginteger (CODER. encrypthmac (inputdata, inputstr ));
System. Err. println ("HMAC:/N" + Mac. tostring (16 ));
}
}

Console output:

Console code
1. Original:
2. Simple Encryption
3. After base64 encryption:
4.566a5y2v5yqg5a + G
5.
6. After base64 decryption:
7. Simple Encryption
8. Mac key:
9. ugxdhc + 6 ylrdaik ++ leftgwimbuyuj6mqhwyhsgf4trvkvbbsqvy/a22xu8xt1ruemdcww155bke
10. pbipkd7qhg =
11.
12. MD5:
13.-550b4d90349ad4629462113e7934de56
14. Sha:
15.91k9vo7p400cjkgfhjh0ia9qthsjagfn
16. HMAC:
17.2287d192387e94254bdbba2fa941009a
Original article:
Simple Encryption
After base64 encryption:
566a5y2v5yqg5a + G

After base64 decryption:
Simple Encryption
Mac key:
Ugxdhc + 6 ylrdaik ++ leftgwimbuyuj6mqhwyhsgf4trvkvbbsqvy/a22xu8xt1ruemdcww155bke
Pbipkd7qhg =

MD5:
-550b4d90349ad4629462113e7934de56
SHA:
91k9vo7p400cjkgfhjh0ia9qthsjagfn
HMAC:
2287d192387e94254bdbba2fa941009a

Note:
During compilation, you may see the following prompt:

Reference

Warning sun. Misc. base64decoder is a dedicated API of sun and may be deleted in future versions.

Import sun. Misc. base64decoder;
^
Warning sun. Misc. base64encoder is a dedicated API of sun and may be deleted in future versions.

Import sun. Misc. base64encoder;
^

Base64encoder and base64decoder are unofficial JDK implementation classes. Although it can be found and used in JDK, it cannot be found in API. Sun and COM. classes starting with sun packages are not documented. They belong to the foundation of Java and javax class libraries. Most implementations are related to the underlying platform and are generally not recommended.

Base64 encryption and decryption are bidirectional and can be reversed.
MD5, Sha, and HMAC are one-way encryption. After any data is encrypted, only one unique encryption string is generated, which is usually used to verify whether the data is modified during transmission. The HMAC algorithm has a key that enhances the security of data transmission and the uncontrollable factors outside the algorithm.
One-way encryption is mainly used to verify whether data is modified during transmission.

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.