Java encryption technology (I)-base64 and one-way encryption algorithm MD5 & Sha & Mac

Source: Internet
Author: User
Tags hmac asymmetric encryption

From: http://snowolf.iteye.com/blog/379860

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 introducesBase64,MD5,Sha,HMACMethods.
MD5,Sha,HMACThese three encryption algorithms are non-reversible encryption and 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
 

 
/ **
  * BASE64 decryption http://www.bt285.cn http://www.5a520.cn
  *
  * @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.=Symbol filling.

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
 
/ **
  * MD5 encryption http://www.bt285.cn http://www.5a520.cn
  *
  * @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
 
/ **
  * SHA encryption http://www.5a520.cn http://www.bt285.cn
  *
  * @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
 
/ **
  * Initialize HMAC key http://www.guihua.org http://www.feng123.com
  *
  * @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);

}

A complete class is provided as follows:

Java code
 
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 http://www.bt285.cn http://www.feng123.com
 *
 * @author 梁栋
 * @version 1.0
 * @since 1.0
 * /
public abstract class Coder {
 public static final String KEY_SHA = "SHA";
 public static final String KEY_MD5 = "MD5";

 / **
 * MAC algorithm can choose from 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 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 Exceptio
n {

 SecretKey secretKey = new SecretKeySpec (decryptBASE64 (key), KEY_MAC);

 Mac mac = Mac.getInstance (secretKey.getAlgorithm ());
 mac.init (secretKey);

 return mac.doFinal (data);

 }
}

Then a test class is provided:

Java code
 
import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


/ **
 * DES security coding component author by http://www.bt285.cn http://www.5a520.cn
 *
 * <pre>
 * Supports DES, DESede (TripleDES, which is 3DES), AES, Blowfish, RC2, RC4 (ARCFOUR)
 * 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 fr
om 32 to 448 (inclusive)
 * RC2 key size must be between 40 and 1024 bits
 * RC4 (ARCFOUR) key size must be between 40 and 1024 bits
 * Specific content needs attention JDK Document http: //
/docs/technotes/guides/security/SunProviders.html
 * </ pre>
 *
 * @author 梁栋
 * @version 1.0
 * @since 1.0
 * /
public abstract class DESCoder extends Coder {
 / **
 * ALGORITHM algorithm <br>
 * Can be replaced with 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 rang
e from 32 to 448 (inclusive)
 * RC2 key size must be between 40 and 1024 bits
 * RC4 (ARCFOUR) key size must be between 40 and 1024 bits
 * </ pre>
 *
 * Use the following code in Key toKey (byte [] key) method
 * <code> SecretKey secretKey = new SecretKeySpec (key, ALGORITHM); </ code>
replace
 * <code>
 * DESKeySpec dks = new DESKeySpec (key);
 * SecretKeyFactory keyFactory = SecretKeyFactory.getInstance (ALGORITHM);

 * SecretKey secretKey = keyFactory.generateSecret (dks);
 * </ code>
 * /
 public static final String ALGORITHM = "DES";

 / **
 * Conversion key <br>
 *
 * @param key
 * @return
 * @throws Exception
 * /
 private static Key toKey (byte [] key) throws Exception {
 DESKeySpec dks = new DESKeySpec (key);
 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance (ALGORITHM)
;
 SecretKey secretKey = keyFactory.generateSecret (dks);

 // When using other symmetric encryption algorithms, such as AES, Blowfish, etc., replace the following with
Three lines of code
 // SecretKey secretKey = new SecretKeySpec (key, ALGORITHM);

 return secretKey;
 }

 / **
 * Decrypt
 *
 * @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);
 }

 / **
 * 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);
 }

 / **
 * Generate key
 *
 * @return
 * @throws Exception
 * /
 public static String initKey () throws Exception {
 return initKey (null);
 }

 / **
 * Generate 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 ());
 }
}

Console output:

Console code

 

Original article: simple encrypted base64: 566a5y2v5yqg5a + gbase64 after decryption: simple encrypted Mac key: ugxdhc + 6 ylrdaik ++ encrypt/decrypt = MD5:-encrypt: decrypt

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.

* BASE64解密 http://www.bt285.cn http://www.5a520.cn  
*
* @param key  
* @return  
* @throws Exception  
*/  

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.