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

更多相关文章

  1. Android 字符串转换大小写
  2. Android内容提供者ContentProvider用法实例分析
  3. android 计算字符串长度,高度
  4. Android中ArrayList动态数组用法
  5. 内容提供器
  6. 【Java】java和android网络编程 - 对byte数组压缩和解压缩(zip,g
  7. Android中五大字符串总结(String、StringBuffer、StringBuilder、
  8. android之 实现对搜索框输入内容(自动出现匹配内容)

随机推荐

  1. 深入垂直业务场景,SaaS版供应商业务协同平
  2. 淘宝移动端首页的商品列表
  3. 淘宝移动端首页的商品列表
  4. 详解MacOs免密登录CentOs操作步骤
  5. iOS组件依赖避免冲突的小技巧分享
  6. 移动端布局学习小结与实践
  7. 移动端布局学习小结与实践
  8. 移动端布局学习小结与实践
  9. 移动布局原理、实战手机页面的基本整体架
  10. 仿PHP中文网首页