This article describes the encryption and decryption functions implemented by Java based on Des symmetric encryption algorithm. Share it for your reference, as follows:
Des encryption related categories:
SecureRandom is inherited from the java.util.Random class
There are three types of constructors of this class, the following examples are:
SecureRandom() constructs a secure random number generator (RNG) that implements the default random number algorithm.
SecureRandom(byte[] seed) constructs a secure random number generator (RNG) that implements the default random number algorithm.
DESKeySpec is used to generate the key content of the key using the original key.
DESKeySpec has two constructors:
DESKeySpec(byte[] key) Creates a DESKeySpec object using the first 8 bytes in the key as the key content of the DES key.
DESKeySpec(byte[] key, int offset) Creates a DESKeySpec object, using the first 8 bytes in the key that begins with and contains offset as the key content of the DES-EDE key.
SecretKeyFactory , a key factory used to convert a key (opic encryption key of type Key) to a key specification (transparent representation of the underlying key material), and vice versa. Secret key factory operates only on secret (symmetric) keys.
SecretKey object, secret key object, generates secret key by calling the generatedSecret (DESKeySpec desktop space) method of the secret key factory
The Cipher class provides password functions for encryption and decryption, and obtains instances by calling Cipher's getInstance("des")
The Cipher object calls the init() method to initialize the object. The specific parameters of the init() method are determined according to the specific situation, including encrypted and decrypted constants.
Finally, call Cipher's doFinal() method for encryption and decryption.
Here I would like to ask you a question. Whether it is the first type of encoding using BASE64Encoder or the second type of org.apache.commons.codec.binary.Base64 encoding, when converting String to byte and byte to String, UTF-8/GBK and other encodings are required to encode. Is it decoded?
1. Use sun.misc.BASE64Decoder and BASE64Encoder for decoding and encoding
package com.soufun.com;import java.io.IOException;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.util.Date;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;// Import 64-bit encoding of sun import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;/** *@author WHD * *Encoder even if you import the sun.misc package, an error will be reported. At this time, you can remove your JRE package and import it again. */public class DesUtil { // Define encryption method private final static String DES = "DES"; private final static String UTF8="GBK"; static SecretKeyFactory keyFactory = null; static { try { keyFactory=SecretKeyFactory.getInstance("DES"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) throws Exception { long begin=new Date().getTime(); String data = "aaades encryption test"; // Note: During the DES encryption and decryption process, the key length must be a multiple of 8. String key = "qazwsxed"; System.err.println(encrypt(data, key)); System.err.println(decrypt(encrypt(data, key), key)); long end =new Date().getTime(); System.out.println(end-begin); } /** * Description Encrypts according to the key value* @param data * @param key Encryption key byte array* @return * @throws Exception */ public static String encrypt(String data, String key) throws Exception { // Use the specified encoding to obtain the content to be encrypted. Generally, the secret key is letters or numbers without specifying the encoding, but the specified can also be byte[] bt = encrypt(data.getBytes(UTF8), key.getBytes(UTF8)); //Note: When encrypting and decrypting, use sun's BASE64Encoder() for encoding and decoding, otherwise there will be garbled code.//I have viewed many instances online, but there is no encoding and decoding, and there is no garbled code problem. I have garbled code here, so I use BASE64Encoder() for encoding and decoding String strs = new BASE64Encoder().encode(bt); return strs; } /** * Description Decrypt according to key value* @param data * @param key Encryption key byte array* @return * @throws IOException * @throws Exception */ public static String decrypt(String data, String key) throws IOException, Exception { if (data == null) return null; //Note: When encrypting and decrypting, use sun's BASE64Encoder() for encoding and decoding, otherwise there will be garbled BASE64Decoder decoder = new BASE64Decoder(); byte[] buf = decoder.decodeBuffer(data); byte[] bt = decrypt(buf,key.getBytes()); return new String(bt,UTF8); } /** * Description Encrypt according to key value* @param data * @param key Encrypt key byte array* @return * @throws Exception */ private static byte[] encrypt(byte[] data, byte[] key) throws Exception { // Generate a trusted random number source SecureRandom sr = new SecureRandom(); // Create a DESKeySpec object from the original key data, that is, the key content of the key that creates the key DESKeySpec dks = new DESKeySpec(key); // The key factory is used to convert the key (opic encryption key of type Key) to the key specification (transparent representation of the underlying key material), and vice versa. Secret key factory operates only on secret (symmetric) keys. // Use singleton mode instead here //SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // Generate SecretKey(key) object according to the provided key specification (key material). SecretKey securekey = keyFactory.generateSecret(dks); // The Cipher object actually completes the encryption operation, and this class provides password functions for encryption and decryption. Cipher cipher = Cipher.getInstance(DES); // Initialize this Cipher with a key and a random source. ENCRYPT_MODE is used to initialize Cipher into a constant for encryption mode. cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); //Formal execution of encryption operation return cipher.doFinal(data); } /** * Description Decrypt according to key value* @param data * @param key Encryption key byte array* @return * @throws Exception */ private static byte[] decrypt(byte[] data, byte[] key) throws Exception { // Generate a trusted random number source SecureRandom sr = new SecureRandom(); // Create a DESKeySpec object from the original key data, that is, the key content of the key that creates the key DESKeySpec dks = new DESKeySpec(key); // The key factory is used to convert the key (opic encryption key of type Key) to the key specification (transparent representation of the underlying key material), and vice versa. Secret key factory operates only on secret (symmetric) keys. // Use singleton mode instead here //SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // Generate SecretKey (key) object according to the provided key specification (key material). SecretKey securekey = keyFactory.generateSecret(dks); // The Cipher class provides password functions for encryption and decryption. Cipher cipher = Cipher.getInstance(DES); // DECRYPT_MODE is used to initialize Cipher into a constant in the decryption mode. cipher.init(Cipher.DECRYPT_MODE, securekey, sr); // Formal decryption operation return cipher.doFinal(data); }}2. Use org.apache.commons.codec.binary.Base64 to decode and encode
package com.soufun.com;import java.io.IOException;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.util.Date;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;import org.apache.commons.codec.binary.Base64;/** *@author WHD * */public class DesUtil { // Define encryption method private final static String DES = "DES"; private final static String UTF8="GBK"; static SecretKeyFactory keyFactory = null; static { try { keyFactory=SecretKeyFactory.getInstance("DES"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) throws Exception { long begin=new Date().getTime(); String data = "aaades encryption test"; // Note: During DES encryption and decryption, the key length must be multiples of 8. String key = "qazwsxed"; System.err.println(encrypt(data, key)); System.err.println(decrypt(encrypt(data, key), key)); long end =new Date().getTime(); System.out.println(end-begin); } /** * Description Encrypt according to the key value* @param data * @param key encryption key byte array* @return * @throws Exception */ public static String encrypt(String data, String key) throws Exception { // Use the specified encoding to obtain the content to be encrypted. Generally, the key is letters or numbers without specifying the encoding, but the specified can also be byte[] bt = encrypt(data.getBytes(UTF8), key.getBytes()); // The first one uses sun.misc.BASE64Encoder; it is encoded, but it is said that using org.apache.commons.codec.binary.Base64 is better, so try String strs = Base64.encodeBase64String(bt); return strs; } /** * Description Decrypt according to key value* @param data * @param key Encryption key byte array* @return * @throws IOException * @throws Exception */ public static String decrypt(String data, String key) throws IOException, Exception { if (data == null) return null; // Use org.apache.commons.codec.binary.Base64 to decode byte [] buf=Base64.decodeBase64(data); byte[] bt = decrypt(buf,key.getBytes()); return new String(bt,UTF8); } /** * Description Encrypt according to key value* @param data * @param key Encryption key byte array* @return * @throws Exception */ private static byte[] encrypt(byte[] data, byte[] key) throws Exception { // Generate a trusted random number source SecureRandom sr = new SecureRandom(); // Create a DESKeySpec object from the original key data, that is, the key content of the key that creates the key DESKeySpec dks = new DESKeySpec(key); // The key factory is used to convert the key (opic encryption key of type Key) to the key specification (transparent representation of the underlying key material), and vice versa. Secret key factory operates only on secret (symmetric) keys. // Use singleton mode instead here //SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // Generate SecretKey(key) object according to the provided key specification (key material). SecretKey securekey = keyFactory.generateSecret(dks); // The Cipher object actually completes the encryption operation, and this class provides password functions for encryption and decryption. Cipher cipher = Cipher.getInstance(DES); // Initialize this Cipher with a key and a random source. ENCRYPT_MODE is used to initialize Cipher into a constant for encryption mode. cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); //Formal execution of encryption operation return cipher.doFinal(data); } /** * Description Decrypt according to key value* @param data * @param key Encryption key byte array* @return * @throws Exception */ private static byte[] decrypt(byte[] data, byte[] key) throws Exception { // Generate a trusted random number source SecureRandom sr = new SecureRandom(); // Create a DESKeySpec object from the original key data, that is, the key content of the key that creates the key DESKeySpec dks = new DESKeySpec(key); // The key factory is used to convert the key (opic encryption key of type Key) to the key specification (transparent representation of the underlying key material), and vice versa. Secret key factory operates only on secret (symmetric) keys. // Use singleton mode instead here //SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // Generate SecretKey (key) object according to the provided key specification (key material). SecretKey securekey = keyFactory.generateSecret(dks); // The Cipher class provides password functions for encryption and decryption. Cipher cipher = Cipher.getInstance(DES); // DECRYPT_MODE is used to initialize Cipher into a constant in the decryption mode. cipher.init(Cipher.DECRYPT_MODE, securekey, sr); // Formal decryption operation return cipher.doFinal(data); }}Download address of the package used in 1 and 2:
Download: sun.misc.BASE64Decoder.
Download: apache's Base64 encoding, decoder.
3. No encoding is used, decoding package
package com.soufun.com;import java.io.IOException;import java.security.NoSuchAlgorithmException;import java.util.Date;import java.util.HashMap;import java.util.Map;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;import javax.crypto.spec.IvParameterSpec;/** *@author WHD * */public class DESCrypt { static SecretKeyFactory secretKeyFactory = null; //Cipher's "algorithm/pattern/filling" static final String CIPHER = "DES/CBC/PKCS5Padding"; static { try { // Get the secret key project secretKeyFactory = SecretKeyFactory.getInstance("DES"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } // Define constants, encoding format private static final String UTF8 = "GBK"; /* * Container for object cache*/ static abstract class Cache { private final Map innerCache = new HashMap(); protected abstract Object createValue(Object key) throws Exception; public Object get(Object key) throws Exception { Object value; synchronized (innerCache) { value = innerCache.get(key); if (value == null) { value = new CreationPlaceholder(); innerCache.put(key, value); } } if (value instance of CreationPlaceholder) { synchronized (value) { CreationPlaceholder progress = (CreationPlaceholder) value; if (progress.value == null) { progress.value = createValue(key); synchronized (innerCache) { innerCache.put(key, progress.value); } } return progress.value; } } return value; } static final class CreationPlaceholder { Object value; } } /* * hex->str & str->hex */ public static byte[] stringToHex(String ss) { // String conversion we byte digest[] = new byte[ss.length() / 2]; for (int i = 0; i < digest.length; i++) { String byteString = ss.substring(2 * i, 2 * i + 2); int byteValue = Integer.parseInt(byteString, 16); digest[i] = (byte) byteValue; } return digest; } public static String hexToString(byte b[]) { StringBuffer hexString = new StringBuffer(); for (int i = 0; i < b.length; i++) { String plainText = Integer.toHexString(0xff & b[i]); if (plainText.length() < 2) { hexString.append("0"); } hexString.append(plainText); } return hexString.toString(); } private static byte[] _convertKeyIv(String text) throws IOException { if (text.length() == 8) { return text.getBytes(UTF8); } if (text.startsWith("0x") && text.length() == 32) { byte[] result = new byte[8]; for (int i = 0; i < text.length(); i += 2) { if (text.charAt(i++) == '0' && text.charAt(i++) == 'x') { try { result[i / 4] = (byte) Integer.parseInt( text.substring(i, i + 2), 16); } catch (Exception e) { throw new IOException("TXT '" + text + "' is invalid!"); } } } return result; } throw new IOException("TXT '" + text + "' is invalid!"); } /* * SecretKey & IvParameterSpec's cache*/ private static Cache SecretKeySpecs = new Cache() { protected Object createValue(Object key) throws Exception { SecretKey secretKeyObj = null; try { secretKeyObj = secretKeyFactory.generateSecret(new DESKeySpec( _convertKeyIv((String) key))); } catch (Exception e) { e.printStackTrace(); } return secretKeyObj; } }; private static Cache IvParamSpecs = new Cache() { protected Object createValue(Object key) throws Exception { IvParameterSpec ivObj = null; ivObj = new IvParameterSpec(_convertKeyIv((String) key)); return ivObj; } }; /* * Encryption & decryption*/ public static String encrypt(String text, String authKey, String authIv) { SecretKey secretKeyObj = null; IvParameterSpec ivObj = null; try { secretKeyObj = (SecretKey) SecretKeySpecs.get(authKey); ivObj = (IvParameterSpec) IvParamSpecs.get(authIv); } catch (Exception e) { e.printStackTrace(); } byte[] data = null; try { data = text.getBytes(UTF8); } catch (Exception e) { e.printStackTrace(); } byte[] authToken = null; try { authToken = encrypt(data, secretKeyObj, ivObj); } catch (Exception e) { e.printStackTrace(); } return hexToString(authToken); } public static byte[] encrypt(byte[] data, SecretKey secretKey, IvParameterSpec iv) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER); cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv); return cipher.doFinal(data); } public static String decrypt(String hexString, String authKey, String authIv) throws Exception { SecretKey secretKeyObj = null; IvParameterSpec ivObj = null; try { secretKeyObj = (SecretKey) SecretKeySpecs.get(authKey); ivObj = (IvParameterSpec) IvParamSpecs.get(authIv); } catch (Exception e) { e.printStackTrace(); } String text = decrypt(hexString, secretKeyObj, ivObj); return text; } public static String decrypt(String message, SecretKey secretKey, IvParameterSpec iv) throws Exception { byte[] data = stringToHex(message); return decrypt(data, secretKey, iv); } public static String decrypt(byte[] data, SecretKey secretKey, IvParameterSpec iv) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER); cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); byte[] retByte = cipher.doFinal(data); return new String(retByte); } public static void main(String[] args) throws Exception { long begin= new Date().getTime(); String authKey = "w8f3k9c2"; String authIv = "w8f3k9c2"; String text = "aaades encryption test"; // 140CB412BA03869F // 140cb412ba03869f // Encrypt the original text String encryptedText = encrypt(text, authKey, authIv); System.out.println("encryptedText:" + encryptedText); // Restore the ciphertext String plainText = decrypt(encryptedText, authKey, authIv); System.out.println("plainText:" + plainText); //2a329740ce15f549be64190b183a5be2 long end =new Date().getTime(); System.out.println(end-begin); }}PS: Friends who are interested in encryption and decryption can also refer to the online tools of this site:
Password security online detection:
http://tools.VeVB.COM/password/my_password_safe
High-strength password generator:
http://tools.VeVB.COM/password/CreateStrongPassword
Thunder, Express, and Tornado URL encryption/decryption tools:
http://tools.VeVB.COM/password/urlrethunder
Online hash/hash algorithm encryption tool:
http://tools.VeVB.COM/password/hash_encrypt
Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 encryption tool:
http://tools.VeVB.COM/password/hash_md5_sha
Online sha1/sha224/sha256/sha384/sha512 encryption tool:
http://tools.VeVB.COM/password/sha_encode
I hope this article will be helpful to everyone's Java programming.