Browse Source

Change-Id: Iec1e360a7bdc3e40eea3a5bcefef611b06e9ad45

albertshaw 8 years ago
parent
commit
24f9785b4d
1 changed files with 14 additions and 23 deletions
  1. 14 23
      src/main/java/com/goafanti/common/utils/AesUtils.java

+ 14 - 23
src/main/java/com/goafanti/common/utils/AesUtils.java

@@ -10,13 +10,10 @@ public class AesUtils {
 
 	public static String encrypt(String content, String key) throws Exception {
 		try {
-			String data = content;
-			String iv = key;
-
 			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
 			int blockSize = cipher.getBlockSize();
 
-			byte[] dataBytes = data.getBytes();
+			byte[] dataBytes = content.getBytes();
 			int plaintextLength = dataBytes.length;
 			if (plaintextLength % blockSize != 0) {
 				plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
@@ -26,12 +23,11 @@ public class AesUtils {
 			System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
 
 			SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
-			IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
+			IvParameterSpec ivspec = new IvParameterSpec(key.getBytes());
 
 			cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
-			byte[] encrypted = cipher.doFinal(plaintext);
 
-			return Base64.encodeBase64String(encrypted);
+			return Base64.encodeBase64String(cipher.doFinal(plaintext));
 
 		} catch (Exception e) {
 			e.printStackTrace();
@@ -41,33 +37,28 @@ public class AesUtils {
 
 	public static String decrypt(String content, String key) throws Exception {
 		try {
-			String data = content;
-			String iv = key;
-
-			byte[] decoded = Base64.decodeBase64(data);
+			byte[] decoded = Base64.decodeBase64(content);
 
 			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
 			SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
-			IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
+			IvParameterSpec ivspec = new IvParameterSpec(key.getBytes());
 
 			cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
 
 			byte[] original = cipher.doFinal(decoded);
-			String originalString = new String(original);
-			return originalString;
+			int i = original.length - 1;
+			for (; i >= 0; i--) {
+				if (original[i] != 0) {
+					break;
+				}
+			}
+			byte[] subarray = new byte[i + 1];
+			System.arraycopy(original, 0, subarray, 0, i + 1);
+			return new String(subarray);
 		} catch (Exception e) {
 			e.printStackTrace();
 			return null;
 		}
 	}
-	
-	public static void main(String[] args) throws Exception {
-		String pwd = "Ai/0sYzmwiWiE6vq";
-		String msg = "hahahahahahaha";
-		String encrypted = AesUtils.encrypt(msg, pwd);
-		System.out.println(encrypted);
-		System.out.println(encrypted.length());
-		System.out.println(AesUtils.decrypt(encrypted, pwd));
-	}
 
 }