Import Java.util.UUID; All in Android.jar.
Import Javax.crypto.Cipher;
Import Javax.crypto.spec.IvParameterSpec;
Import Javax.crypto.spec.SecretKeySpec;
Import android.util.Base64;
String key = new String (""); Key value
String IV = new String (""); Vector
Encryption, whose parameters are the data to be encrypted
public static string Encrypt (String data) throws Exception
{
byte[] Raw = Key.getbytes ();
secretkeyspec skeyspec = new Secretkeyspec (Raw, "AES");
//Set algorithm/mode/complement method
cipher Cipher = Cipher.getinstance ("aes/cbc/pkcs5padding");
//set vector increase algorithm strength
ivparameterspec paramter = new Ivparameterspec (Iv.getbytes ());
cipher.init (Cipher.encrypt_mode, Skeyspec, paramter);
//two encryption with Base64
byte[] encrypted = Cipher.dofinal (Data.getbytes ());
string encryptData = new String (Base64.encode (encrypted, base64.default));
Prevent line breaks after data encryption (remove line breaks)
String changedata = new String (Encryptdata.replaceall ("\r|\n", "" "));
return changedata;
}
Decryption, whose parameters are the data to decrypt
public static string Decrypt (String data) throws Exception
{
Byte[] Raw = key.getbytes ("UTF-8");
Secretkeyspec Skeyspec = new Secretkeyspec (Raw, "AES");
Set algorithm/mode/complement method
Cipher Cipher = cipher.getinstance ("aes/cbc/pkcs5padding");
Set vector increase algorithm strength
Ivparameterspec parameter = new Ivparameterspec (Iv.getbytes ());
Encrypt two times with Base64
Cipher.init (Cipher.decrypt_mode, skeyspec, parameter);
byte[] encrypted1 = Base64.decode (data, base64.default);
try {
byte[] Original = cipher.dofinal (encrypted1);
String decryptdata = new String (original);
return decryptdata;
} catch (Exception e) {
System.out.println (E.tostring ());
Return "";
}
}
In general, if the decrypted data exists in Chinese, it is customary to display it in UTF-8 on Android, assuming this is the case:
Refer to: http://www.sharejs.com/codes/java/5422
Convert Utf-8 to Chinese
public static string Getansimsg (String datastr)
{
int index = 0;
StringBuffer buffer = new StringBuffer ();
int li_len = Datastr.length ();
while (Index < Li_len)
{
if (Index >= li_len-1 | |! " \\u ". Equals (datastr.substring (index, index + 2)))
{
Buffer.append (Datastr.charat (index));
index++;
Continue
}
String charstr = "";
CHARSTR = datastr.substring (index + 2, index + 6);
Char letter = (char) integer.parseint (CHARSTR, 16);
Buffer.append (letter);
Index + = 6;
}
return buffer.tostring ();
}
AES Encryption Decryption