The following is the implementation of the Code:
Package Com.smt.cipher.symmetry;import Java.nio.charset.charset;import Java.security.securerandom;import Java.util.base64;import javax.crypto.cipher;import Javax.crypto.keygenerator;import javax.crypto.SecretKey;/** * DES Tools * @author Zhangyukun * */public class Aesutil {public static final String ENCODING = Charset.defaultcharset (). Nam E ();/** * Encrypt * @param data source * @param cipherstr key character string (multiples of 8) * @return */public static string Encrypt (string content, String secretkeystr) {string rt = null;try {byte[] data = Getdescipher (Secretkeystr, Cipher.encrypt_mode). dofinal (cont Ent.getbytes (ENCODING)); RT = New String (Base64.getencoder (). Encode (data), ENCODING);} catch (Exception e) {e.printstacktrace ();} return RT;} /** * Decryption * @param data decryption * @param cipherstr key string (multiple of 8) * @return */public static string Descrypt (string data, string SE CRETKEYSTR) {String RT = null;try {byte[] cipher = Getdescipher (Secretkeystr, Cipher.decrypt_mode). Dofinal (base64.getde Coder (). Decode (Data.getbytes ()); RT = new String (cipher,encoding);} catch (Exception e) {e.printstacktrace ();} return RT;} /** * Get password * @param secretkeystr * @param mode * @return */public static Cipher getdescipher (String secretkeystr,int mode {int remainder = Secretkeystr.length ()%8;if (remainder! = 0) {throw new RuntimeException ("secret key string must be a multiple of 8");} try {keygenerator keygen =keygenerator.getinstance ("AES"); Keygen.init (+, New SecureRandom (Secretkeystr.getbytes ( (ENCODING))); Secretkey Secretkey=keygen.generatekey (); Cipher Cipher = cipher.getinstance ("AES"); Cipher.init (mode, secretkey); return Cipher;} catch (Exception e) {e.printstacktrace ();} return null;}}
Test code:
Package Com.smt.cipher;import Java.security.nosuchalgorithmexception;import Com.smt.cipher.symmetry.DESUtil; public class Main2 {public static void main (string[] args) throws NoSuchAlgorithmException {System.out.println ( Desutil.encrypt ("Test text des", "ABCDABCD")); System.out.println ( desutil.descrypt (Desutil.encrypt ("Test text des", "ABCDABCD"), "ABCDABCD"));}}
Output Result:
Java des encryption implementation