BASE64, MD5, SHA, and HMAC encryption algorithms

Source: Internet
Author: User
Tags base64 decrypt hmac md5 md5 encryption
The code is as follows: Copy code
Package com. ice. webos. util. security;
 
Import java. io. UnsupportedEncodingException;
Import java. math. BigInteger;
Import java. security. Key;
Import java. security. MessageDigest;
Import java. security. SecureRandom;
 
Import javax. crypto. Cipher;
Import javax. crypto. KeyGenerator;
Import javax. crypto. Mac;
Import javax. crypto. SecretKey;
Import javax. crypto. SecretKeyFactory;
Import javax. crypto. spec. DESKeySpec;
Import javax. crypto. spec. SecretKeySpec;
 
Import sun. misc. BASE64Decoder;
Import sun. misc. BASE64Encoder;
 
/**
* <Ul>
* <Li> BASE64 encryption and decryption are bidirectional and can be reversed. </Li>
* <Li> MD5, SHA, and HMAC are unidirectional 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. </Li>
* <Li> The HMAC algorithm has a key that enhances the security during data transmission and the uncontrollable factors outside the algorithm. </Li>
* <Li> DES-Data Encryption Standard, which is the Data Encryption algorithm.
* The DES algorithm has three Entry parameters: Key, Data, and Mode.
* <Ul>
* <Li> Key: The 8-byte 64-bit Key used by the DES algorithm. </li>
* <Li> Data: 8-byte 64-bit. It is the Data to be encrypted or decrypted. </li>
* <Li> Mode: DES can be encrypted or decrypted. </Li>
* </Ul>
* </Li>
* <Ul>
  *
* @ Author Ice_Liu
  *
*/
Public class CryptUtil {
Private static final String KEY_MD5 = "MD5 ";
Private static final String KEY_SHA = "SHA ";
/**
* The MAC algorithm can be any of the following algorithms:
      *
* <Pre>
      * 
* HmacMD5
* HmacSHA1
* HmacSHA256
* HmacSHA384
* HmacSHA512
* </Pre>
*/
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 = KeyGenerator. getInstance (KEY_MAC );
SecretKey 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 secretKey = new SecretKeySpec (decryptBASE64 (key), KEY_MAC );
Mac mac = Mac. getInstance (secretKey. getAlgorithm ());
Mac. init (secretKey );
Return mac. doFinal (data );
     }
 
/**
* DES algorithm <br>
* It can be replaced by any of the following algorithms, and the size of the key value changes accordingly.
      *
* <Pre>
* DES key size must be equal to 56
* DESede (TripleDES) key size must be equal to 112 or 168
* AES key size must be equal to 128,192 or 256, but 192 and 256 bits may not be available
* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (random)
* RC2 key size must be between 40 and 1024 bits
* RC4 (ARCFOUR) key size must be between 40 and 1024 bits
* </Pre>
*/
Public static final String ALGORITHM = "DES ";
 
/**
* DES algorithm conversion key <br>
      *
* @ Param key
* @ Return
* @ Throws Exception
*/
Private static Key toKey (byte [] key) throws Exception {
SecretKey secretKey = null;
If (ALGORITHM. equals ("DES") | ALGORITHM. equals ("DESede ")){
DESKeySpec dks = new DESKeySpec (key );
SecretKeyFactory keyFactory = SecretKeyFactory. getInstance (ALGORITHM );
SecretKey = keyFactory. generateSecret (dks );
} Else {
// When using other symmetric encryption algorithms, such as AES and Blowfish, replace the preceding three lines of code with the following code:
SecretKey = new SecretKeySpec (key, ALGORITHM );
         }
Return secretKey;
     }
 
/**
* DES algorithm decryption
      *
* @ Param data
* @ Param key
* @ Return
* @ Throws Exception
*/
Public static byte [] decrypt (byte [] data, String key) throws Exception {
Key k = toKey (decryptBASE64 (key ));
Cipher cipher = Cipher. getInstance (ALGORITHM );
Cipher. init (Cipher. DECRYPT_MODE, k );
Return cipher. doFinal (data );
     }
 
/**
* DES algorithm encryption
      *
* @ Param data
* @ Param key
* @ Return
* @ Throws Exception
*/
Public static byte [] encrypt (byte [] data, String key) throws Exception {
Key k = toKey (decryptBASE64 (key ));
Cipher cipher = Cipher. getInstance (ALGORITHM );
Cipher. init (Cipher. ENCRYPT_MODE, k );
Return cipher. doFinal (data );
     }
 
/**
* DES algorithm generation key
      *
* @ Return
* @ Throws Exception
*/
Public static String initKey () throws Exception {
Return initKey (null );
     }
 
/**
* DES algorithm generation key
      *
* @ Param seed
* @ Return
* @ Throws Exception
*/
Public static String initKey (String seed) throws Exception {
SecureRandom secureRandom = null;
If (seed! = Null ){
SecureRandom = new SecureRandom (decryptBASE64 (seed ));
} Else {
SecureRandom = new SecureRandom ();
         }
KeyGenerator kg = KeyGenerator. getInstance (ALGORITHM );
Kg. init (secureRandom );
SecretKey secretKey = kg. generateKey ();
Return encryptBASE64 (secretKey. getEncoded ());
     }
 
Public static void main (String [] args ){
Try {
String s = "ampersand overwrite ";
String B = CryptUtil. encryptBASE64 (s. getBytes ("UTF-8 "));
System. out. println ("after BASE64 encryption:" + B );
Byte [] c = CryptUtil. decryptBASE64 (B );
System. out. println ("BASE64 decrypted:" + new String (c, "UTF-8 "));
 
C = encryptMD5 (s. getBytes ());
System. out. println ("after MD5 encryption:" + new BigInteger (c). toString (16 ));
 
C = encryptSHA (s. getBytes ());
System. out. println ("SHA encrypted:" + new BigInteger (c). toString (16 ));
 
String key = initMacKey ();
System. out. println ("HMAC key:" + key );
C = encryptHMAC (s. getBytes (), key );
System. out. println ("HMAC encrypted:" + new BigInteger (c). toString (16 ));
 
Key = initKey ();
System. out. println (ALGORITHM + "key: t" + key );
C = encrypt (s. getBytes ("UTF-8"), key );
System. out. println (ALGORITHM + "encrypted:" + new BigInteger (c). toString (16 ));
C = decrypt (c, key );
System. out. println (ALGORITHM + "decrypted:" + new String (c, "UTF-8 "));
} Catch (UnsupportedEncodingException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
         }
     }
 }

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.