前后端(Java + Android + iOS) 一行代码实现AES加密解密算法

概述:

简单说使用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:
  1. 只需要引入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. 代码实现:

下载上述公共类,引入头文件即可调用对应方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章