Android加密解密之AES

最近笔者工作中涉及到AES加密解密开始很懵到网上找了很多文章都没解决最后通过不懈努力终于解决所以在此记录解决方法希望给能你们带来帮助。

简介啥的我就不多说了网上一搜一大把如果需要了解请自行百度这里我直接上代码。


import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

/**
 * AES解密工具类
 */
public class AESUtil {
    /**
     * 密钥
     */
    private static String mKey="flde@@13sdf*@345";
    /**
     * 加解密算法/工作模式/填充方式 AES/ECB/PKCS5Padding、AES/ECB/PKCS7Padding
     */
    private static String mTransformation="AES/ECB/PKCS5Padding";
    /**
     * 算法
     */
    private static String mAlgorithm="AES";
    /**
     * 编码格式
     */
    private static String mCharset="utf-8";

    /**
     * 解密
     * @param s
     * @return
     */
    public static String decrypt(String s) {
        return decodeAES(s);
    }
    /**
     * 解密
     * @param s
     * @return
     */
    public static String encrypt(String s) {
        return encryptAES(s);
    }

    /**
     * 加密
     * @param data
     * @return
     */
    private static String encryptAES(String data){
        try {
            byte[] raw =  mKey.getBytes(mCharset);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, mAlgorithm);
            Cipher cipher = Cipher.getInstance(mTransformation);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(data.getBytes(mCharset));
            return encryptBASE64(encrypted);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密AES
     * @param data
     * @return
     * @throws Exception
     */
    private static String decodeAES(String data) {
        try {
            byte[] raw = mKey.getBytes(mCharset);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, mAlgorithm);
            Cipher cipher = Cipher.getInstance(mTransformation);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = decryptBASE64(data);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, mCharset);
                return originalString;
            } catch (Exception e) {
                return null;
            }
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * BASE64解密
     * @param key
     * @return
     * @throws Exception
     */
    private static byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }
    /**
     * BASE64加密
     * @param key
     * @return
     */
    private static String encryptBASE64(byte[] key){
        return (new BASE64Encoder()).encodeBuffer(key);
    }
}

调用方法

public static void main(String[] args) {
        //需加/解密前字符串
        String data  = "\t{\"name\":\"winks\",\"city\":\"成都\"}";
        System.out.println("需要加密解密字符串:"+data);
        String dataE = encrypt(data);
        System.out.println("加密后字符串:"+dataE);
        String dataD = decrypt(dataE);
        System.out.println("解密后字符串:"+dataD);
    }

调用结果
在这里插入图片描述

注:在加密解密的时候一定要注意密钥、编码格式、加解密算法/工作模式/填充方式一定要切记因为笔者就犯过类似的错误。

如果需要验证数据是否正确可以使用AES在线加/解密工具查看,希望我的方法能解决你的问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里是一个简单的示例,展示了如何在 Android 中使用 AES 加密和解密文件: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.MessageDigest; import java.util.Arrays; public class AesUtil { private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; private static final String SECRET_KEY = "my_secret_key"; private static final String IV = "my_initialization_vector"; public static void encrypt(String inputFile, String outputFile) throws Exception { SecretKeySpec secretKeySpec = generateKey(SECRET_KEY); IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes("UTF-8")); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); FileInputStream inputStream = new FileInputStream(inputFile); FileOutputStream outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, bytesRead); if (output != null) { outputStream.write(output); } } byte[] output = cipher.doFinal(); if (output != null) { outputStream.write(output); } inputStream.close(); outputStream.close(); } public static void decrypt(String inputFile, String outputFile) throws Exception { SecretKeySpec secretKeySpec = generateKey(SECRET_KEY); IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes("UTF-8")); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); FileInputStream inputStream = new FileInputStream(inputFile); FileOutputStream outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, bytesRead); if (output != null) { outputStream.write(output); } } byte[] output = cipher.doFinal(); if (output != null) { outputStream.write(output); } inputStream.close(); outputStream.close(); } private static SecretKeySpec generateKey(String key) throws Exception { byte[] keyBytes = key.getBytes("UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-256"); keyBytes = sha.digest(keyBytes); keyBytes = Arrays.copyOf(keyBytes, 16); return new SecretKeySpec(keyBytes, "AES"); } } ``` 在此示例中,我们使用 AES/CBC/PKCS5Padding 加密模式和 SHA-256 哈希算法生成密钥。我们将密钥和初始向量 IV 保存为常量,但您可以根据需要进行更改。 要使用此示例,请在您的代码中调用 `AesUtil.encrypt(inputFile, outputFile)` 或 `AesUtil.decrypt(inputFile, outputFile)` 方法,其中 `inputFile` 是要加密或解密的文件路径,而 `outputFile` 是加密或解密后的文件路径。 请注意,此示例中的加密和解密操作是阻塞的,并且使用了相对较小的缓冲区。对于大文件和需要异步处理的情况,您需要进行适当的优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值