Packagecom.microwisdom.utils;Importjava.security.NoSuchAlgorithmException;ImportJava.security.SecureRandom;ImportJava.util.logging.Level;ImportJava.util.logging.Logger;ImportJavax.crypto.Cipher;ImportJavax.crypto.KeyGenerator;ImportJavax.crypto.SecretKey;ImportJavax.crypto.spec.SecretKeySpec;Importorg.apache.commons.codec.binary.Base64;/** * @versionV1.0 * @desc AES Encryption Tool class*/ Public classAesutil {Private Static FinalString key_algorithm = "AES"; Private Static FinalString default_cipher_algorithm = "aes/ecb/pkcs5padding";//The default encryption algorithm /*** AES Encryption operation * *@paramcontent Pending Encryption *@paramPassword encrypted password *@returnreturns the encrypted data after Base64 transcoding*/ Public Staticstring Encrypt (string content, string password) {Try{Cipher Cipher= Cipher.getinstance (Default_cipher_algorithm);//Create a password device byte[] bytecontent = Content.getbytes ("Utf-8"); Cipher.init (Cipher.encrypt_mode, Getsecretkey (password));//ciphers initialized to cryptographic mode byte[] result = Cipher.dofinal (bytecontent);//Encrypt returnBase64.encodebase64string (result);//return via Base64 transcoding}Catch(Exception ex) {Logger.getlogger (aesutil.class. GetName ()). log (Level.severe,NULL, ex); } return NULL; } /*** AES Decryption operation * *@paramcontent *@paramPassword *@return */ Public Staticstring Decrypt (string content, string password) {Try { //instantiation ofCipher Cipher =cipher.getinstance (Default_cipher_algorithm); //use key initialization, set to decryption modeCipher.init (Cipher.decrypt_mode, Getsecretkey (password)); //Perform Actions byte[] result =cipher.dofinal (base64.decodebase64 (content)); return NewString (Result, "Utf-8"); } Catch(Exception ex) {Logger.getlogger (aesutil.class. GetName ()). log (Level.severe,NULL, ex); } return NULL; } /*** Generate Encryption Key * *@return */ Private StaticSecretkeyspec Getsecretkey (FinalString Password) { //returns the Keygenerator object that generates the specified algorithm key generatorkeygenerator kg =NULL; Try{kg=keygenerator.getinstance (Key_algorithm); //AES requires a key length ofKg.init (128,NewSecureRandom (Password.getbytes ())); //Generate a keySecretkey Secretkey =Kg.generatekey (); return NewSecretkeyspec (secretkey.getencoded (), key_algorithm);//Convert to AES private key}Catch(NoSuchAlgorithmException ex) {Logger.getlogger (aesutil.class. GetName ()). log (Level.severe,NULL, ex); } return NULL; } Public Static voidMain (string[] args) {String s= "Hello, hello"; System.out.println ("s:" +s); String S1= Aesutil.encrypt (S, "1234"); System.out.println ("S1:" +S1); System.out.println ("S2:" +aesutil.decrypt (S1, "1234")); }}
Java AES Cryptographic Tool class