Android AES加密 ecb模式加密

Android AES加密 ==ecb模式加密

下面有两套代码都可以实现

第一套
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;

public class AESECB {
     

    // 加密
    public static String Encrypt(String sSrc, String sKey) throws Exception {
     
        if (sKey == null) {
     
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
     
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

//        return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
        return Base64.encodeToString(encrypted, Base64.DEFAULT);
    }

    // 解密
    public static String Decrypt(String sSrc, String sKey) throws Exception {
     
        try {
     
            // 判断Key是否正确
            if (sKey == null) {
     
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
     
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
//            byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            byte[] encrypted1 = Base64.decode(sSrc.getBytes("UTF-8"), Base64.DEFAULT);
            try {
     
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {
     
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
     
            System.out.println(ex.toString());
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
     
        /*
         * 此处使用AES-128-ECB加密模式,key需要为16位。
         */
        // 需要加密的字串
        String sKey = "key值key值key值";
        String cSrc = "Linsk123456_ecb模式";
        System.out.println(cSrc);
        // 加密
        String enString = AESECB.Encrypt(cSrc, sKey);
        System.out.println("加密后的字串是:" + enString);

        // 解密
        String DeString = AESECB.Decrypt(enString, sKey);
        System.out.println("解密后的字串是:" + DeString);
    }
}

执行代码,生成字符串末尾带"\n",需要替换掉

String sKey = "key值key值key值";
AESECB.Encrypt("待加密字符串", sKey).replaceAll("\r|\n", "")


第二套
import android.util.Base64;
import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密解密工具
 *
 * @author huangxiaoguo
 */
public class AESUtils {
     

    public static String encrypt(String sSrc, String sKey){
     
        String rts = "";
        try {
     
            byte[] data = sSrc.getBytes("utf-8");
            byte[] key = sKey.getBytes("utf-8");
            byte[] encrypted = encrypt(data, key);
            rts = Base64.encodeToString(encrypted, Base64.DEFAULT);
        } catch (UnsupportedEncodingException e) {
     
            e.printStackTrace();
        }
        return rts;
    }

    public static String decrypt(String sSrc, String sKey) {
     
        String rts = "";
        try {
     
            byte[] raw = sKey.getBytes("utf-8");
            byte[] encrypted1 = Base64.decode(sSrc.getBytes("UTF-8"), Base64.DEFAULT);
            byte[] original = decrypt(encrypted1, raw);
            rts = new String(original,"utf-8");
        } catch (UnsupportedEncodingException e) {
     
            e.printStackTrace();
        }
        return rts;
    }

    /**
     * AES加密
     *
     * @param data
     *            将要加密的内容
     * @param key
     *            密钥
     * @return 已经加密的内容
     */
    public static byte[] encrypt(byte[] data, byte[] key) {
     
        //不足16字节,补齐内容为差值
        int len = 16 - data.length % 16;
        for (int i = 0; i < len; i++) {
     
            byte[] bytes = {
      (byte) len };
            data = ArrayUtils.concat(data, bytes);
        }
        try {
     
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            return cipher.doFinal(data);
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        return new byte[] {
     };
    }

    /**
     * AES解密
     *
     * @param data
     *            将要解密的内容
     * @param key
     *            密钥
     * @return 已经解密的内容
     */
    public static byte[] decrypt(byte[] data, byte[] key) {
     
        data = ArrayUtils.noPadding(data, -1);
        try {
     
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] decryptData = cipher.doFinal(data);
            int len = 2 + ByteUtils.byteToInt(decryptData[4]) + 3;
            return ArrayUtils.noPadding(decryptData, len);
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        return new byte[] {
     };
    }
}

ArrayUtils

/**
 * 数组工具 
 *  
 * @author huangxiaoguo
 */  
public class ArrayUtils {
       

    /** 
     * 合并数组 
     *  
     * @param firstArray 
     *            第一个数组 
     * @param secondArray 
     *            第二个数组 
     * @return 合并后的数组 
     */  
    public static byte[] concat(byte[] firstArray, byte[] secondArray) {
       
        if (firstArray == null || secondArray == null) {
       
            return null;  
        }  
        byte[] bytes = new byte[firstArray.length + secondArray.length];  
        System.arraycopy(firstArray, 0, bytes, 0, firstArray.length);  
        System.arraycopy(secondArray, 0, bytes, firstArray.length,  
                secondArray.length);  
        return bytes;  
    }  

    /** 
     * 去除数组中的补齐 
     *  
     * @param paddingBytes 
     *            源数组 
     * @param dataLength 
     *            去除补齐后的数据长度 
     * @return 去除补齐后的数组 
     */  
    public static byte[] noPadding(byte[] paddingBytes, int dataLength) {
       
        if (paddingBytes == null) {
       
            return null;  
        }  

        byte[] noPaddingBytes = null;  
        if (dataLength > 0) {
       
            if (paddingBytes.length > dataLength) {
       
                noPaddingBytes = new byte[dataLength];  
                System.arraycopy(paddingBytes, 0, noPaddingBytes, 0, dataLength);  
            } else {
       
                noPaddingBytes = paddingBytes;  
            }  
        } else {
       
            int index = paddingIndex(paddingBytes);  
            if (index > 0) {
       
                noPaddingBytes = new byte[index];  
                System.arraycopy(paddingBytes, 0, noPaddingBytes, 0, index);  
            }  
        }  

        return noPaddingBytes;  
    }  

    /** 
     * 获取补齐的位置 
     *  
     * @param paddingBytes 
     *            源数组 
     * @return 补齐的位置 
     */  
    private static int paddingIndex(byte[] paddingBytes) {
       
        for (int i = paddingBytes.length - 1; i >= 0; i--) {
       
            if (paddingBytes[i] != 0) {
       
                return i + 1;  
            }  
        }  
        return -1;  
    }  
}

ByteUtils

public class ByteUtils {
     
    public static int byteToInt(byte b) {
     
        return (b) & 0xff;
    }
}

执行代码,生成字符串末尾带"\n",需要替换掉

String sKey = "key值key值key值";
AESUtils.encrypt("待加密字符串", sKey).replaceAll("\r|\n", "")

参考
https://blog.csdn.net/dingweijson/article/details/84920045

https://blog.csdn.net/huangxiaoguo1/article/details/78043098

你可能感兴趣的:(密码加密)