In actual coding, you often encounter encryption when you store a password in a database. The encryption at URL pass-through. This simply encapsulates the AES encryption algorithm in Java below.
0. Import class
Import Java. Security. SecureRandom;Import Javax. Crypto. Cipher;Import Javax. Crypto. Keygenerator;Import Javax. Crypto. Secretkey;Import Javax. Crypto. Spec. Secretkeyspec;import org. Apache. Axis. Encoding. Base64;//non-mandatory
1. Encryption interface
/** * Encryption * @param content to encrypt contents * @param password encryption key * @return */ Public Static byte[]Encrypt(string content, string password) {Try{Keygenerator KGen = keygenerator.getinstance ("AES"); Kgen.init ( -,NewSecureRandom (Password.getbytes ())); Secretkey Secretkey = Kgen.generatekey ();byte[] Encodeformat = secretkey.getencoded (); Secretkeyspec key =NewSecretkeyspec (Encodeformat,"AES"); Cipher Cipher = cipher.getinstance ("AES");byte[] bytecontent = Content.getbytes ("Utf-8"); Cipher.init (Cipher.encrypt_mode, key);byte[] result = Cipher.dofinal (bytecontent);returnResult }Catch(Exception e) {E.printstacktrace (); }return NULL; }
2. Decryption interface
/** decryption * @param content to decrypt contents * @param Password decryption key * @return */ Public Static byte[]Decrypt(byte[] content, String password) {Try{Keygenerator KGen = keygenerator.getinstance ("AES"); Kgen.init ( -,NewSecureRandom (Password.getbytes ())); Secretkey Secretkey = Kgen.generatekey ();byte[] Encodeformat = secretkey.getencoded (); Secretkeyspec key =NewSecretkeyspec (Encodeformat,"AES"); Cipher Cipher = cipher.getinstance ("AES"); Cipher.init (Cipher.decrypt_mode, key);byte[] result = cipher.dofinal (content);returnResult }Catch(Exception e) {E.printstacktrace (); }return NULL; }
3. Codec function (not required)
//编码函数 public static String encode(String content, String key) throws Exception { byte[] encrypt = encrypt(content, key); return Base64.encode(encrypt); } //解码函数 public static String decode(String encode, String key) throws Exception { byte[] encrypt = Base64.decode(encode); byte[] content = decrypt(encrypt, key); return new String(content); }
4. Test
//0-Normal Use Public Static void Main(string[] args) throws exception{String content ="Holybin"; String Password ="12345678"; System. out. println ("Encryption before 1:"+ content);byte[] EncryptResult1 = Encrypt (content, password);//General encryption byte[] DecryptResult1 = Decrypt (Encryptresult1,password);//General decryptionSystem. out. println ("1 after decryption:"+NewString (DECRYPTRESULT1)); System. out. println ("\ n Encrypt top 2:"+ content); String encryptResult2 = encode (content, password);//encode and re-encrypt firstSystem. out. println ("2 after encryption:"+ ENCRYPTRESULT2); String decryptResult2 = decode (encryptResult2, password);//Decode and decrypt firstSystem. out. println ("2 after decryption:"+ DECRYPTRESULT2); }
The results are as follows:
5. Problems and thinking
(1) What happens when a byte array is converted directly to a string for output after normal encryption, or when a normal decryption is converted from a string to a byte array?
//1-First Test encryption Public Static void Main(string[] args) throws exception{String content ="Holybin"; String Password ="12345678"; System. out. println ("Encryption before 1:"+ content);byte[] EncryptResult1 = Encrypt (content, password);//General encryptionSystem. out. println ("1 after encryption:"+ ENCRYPTRESULT1); System. out. println ("1 after encryption:"+NewString (ENCRYPTRESULT1));byte[] DecryptResult1 = Decrypt (Encryptresult1,password);//General decryptionSystem. out. println ("1 after decryption:"+NewString (DECRYPTRESULT1)); }
Result 1:
This converts the encrypted byte array directly into a string output. garbled characters appear.
//2-re-test decryption Public Static void Main(string[] args) throws exception{String content ="Holybin"; String Password ="12345678"; System. out. println ("Encryption before 1:"+ content);byte[] EncryptResult1 = Encrypt (content, password);//General encryptionString STRENCRYPTRESULT1 =NewString (ENCRYPTRESULT1,"UTF-8");//system.out.println ("Post-Encryption 1:" + strEncryptResult1); byte[] DecryptResult1 = Decrypt (Strencryptresult1.getbytes ("UTF-8"), password);//General decryptionSystem. out. println ("1 after decryption:"+NewString (DECRYPTRESULT1)); }
Result 2:
Here, extract the bytes array from the encrypted string for decryption, an error occurred
Reason: Mainly because the encrypted byte array is not coerced into a string, the encrypted string can not be directly extracted bytes array for decryption, there are two solutions: first, like the example above test sample encryption and then encode, or first decode and then decrypt (refer to: 4, test). The second is the use of 16 binary and binary conversion function (reference: The following point (2)).
(2) 16 binary and binary reciprocal conversion functions
//binary turn hex Public StaticStringParsebyte2hexstr(byteBuf[]) {StringBuffer SB =NewStringBuffer (); for(inti =0; i < buf.length; i++) {String hex = integer.tohexstring (Buf[i] &0xFF);if(hex.length () = =1) {hex =' 0 '+ hex; } sb.append (Hex.touppercase ()); }returnSb.tostring (); }//16 binary turn binary Public Static byte[]Parsehexstr2byte(String hexstr) {if(Hexstr.length () <1)return NULL;byte[] result =New byte[Hexstr.length ()/2]; for(inti =0; I < hexstr.length ()/2; i++) {intHigh = Integer.parseint (hexstr.substring (i *2I2+1), -);intLow = Integer.parseint (hexstr.substring (i *2+1I2+2), -); Result[i] = (byte) (High * -+ low); }returnResult }
Use the Demo sample:
//3-Test conversion function Public Static void Main(string[] args) throws Exception {String content ="Holybin"; String Password ="12345678";//EncryptionSystem. out. println ("Encryption before 1:"+ content);byte[] Encryptresult = Encrypt (content, password);//General encryptionString Strencryptresult = Parsebyte2hexstr (Encryptresult); System. out. println ("1 after encryption:"+ Strencryptresult);//Decryption byte[] Bytedecryptresult = Parsehexstr2byte (Strencryptresult);byte[] Decryptresult = Decrypt (bytedecryptresult, password);//General decryptionSystem. out. println ("1 after decryption:"+NewString (Decryptresult)); }
Results:
Test code: Encrptdecrypt.java
Java encapsulated AES Encryption algorithm