概述:
簡單說使用AES加密,首先需要了解以下四個屬性:
- 密鑰長度(Key Size)
- 加密模式(Cipher Mode)
- 填充方式(Padding)
- 初始向量(Initialization Vector)
實際項目開發中,前(Android/ios)端與後端(java)需要使用相同的屬性值去加解密,以達到數據的安全傳輸,另外還有一個約定一個密鑰值。
個人項目中使用
密鑰長度(Key Size) : 128
加密模式(Cipher Mode) : ECB
填充方式(Padding) : PKCS5Padding (ios用kCCOptionPKCS7Padding)
初始向量(Initialization Vector):ECB模式下不需要
代碼:
一、Java:
- 只需要引入Cipher架包
2.代碼實現:
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
public class AesUtil {
// 加密模式ECB 填充方式PKCS5Padding
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
//data加密
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); //密鑰長度 128
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
return cipher.doFinal(content.getBytes("utf-8"));
}
//data解密
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes,"utf-8");
}
//字節加密
public static String base64Encode(byte[] bytes){
return Base64.encodeBase64String(bytes);
}
//字節解密
public static byte[] base64Decode(String base64Code) throws Exception{
return new BASE64Decoder().decodeBuffer(base64Code);
}
//字符串加密
public static String aesEncrypt(String content, String encryptKey) throws Exception {
return base64Encode(aesEncryptToBytes(content, encryptKey));
}
//字符串解密
public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
return aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
}
}
二、Android實現:
1. 引入已封裝好的公共類包
下載地址: https://github.com/Dongxk/XKAES.git
下載解壓引入自己項目即可使用,失效請私信!
2. 代碼實現:
引入公共類import com.dongxk.utils. AESUtils
AESUtils.encrypt(‘要加密的字符串’, ‘私鑰key’))
三、iOS實現:
iOS提供了NSString加解密、NSData加解密、Base64格式處理、16進制數據處理。
1. 引入已封裝好的公共類包
下載地址:https://github.com/Dongxk/XKAES_iOS.git
下載解壓引入自己項目即可使用,失效請私信!
2. 主要方法:
具體講解可參考:https://www.jianshu.com/p/93466b31f675
3. 代碼實現:
下載上述公共類,引入頭文件即可調用對應方法。