In the actual coding, we often encounter the encryption when the password is stored in the database, and then encrypt the URL, which simply encapsulates the AES encryption algorithm in Java.
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. Testing
//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) After normal encryption, the resulting byte array is converted directly to a string for output, or normal decryption is converted from a string to a byte array for what happens?
//1-Test Encryption First 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:
Here, the encrypted byte array is converted directly into a string output, garbled.
//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
Cause: 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 of the above test is encrypted and then encoded, or decoded and then decrypted (see: 4, Test) The second is to use 16 binary and binary conversion functions (refer to: (2) below).
(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 }
Examples of Use:
//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:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java encapsulated AES Encryption algorithm