Android端对String进行AES加密/解密方法

网上收集整理的Android端对String进行AES加密/解密方法
两种方法都实测可用

方法一

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESCipher {

    //    private static final String CipherMode = "AES/ECB/PKCS5Padding";使用ECB加密,不需要设置IV,但是不安全
    private static final String CipherMode = "AES/CFB/NoPadding";//使用CFB加密,需要设置IV

    /**
     * 对字符串加密
     *
     * @param key  密钥
     * @param data 源字符串
     * @return 加密后的字符串
     */
    public static String encrypt(String key, String data) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance(CipherMode);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, new IvParameterSpec(
                    new byte[cipher.getBlockSize()]));
            byte[] encrypted = cipher.doFinal(data.getBytes());
            return Base64.encodeToString(encrypted, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 对字符串解密
     *
     * @param key  密钥
     * @param data 已被加密的字符串
     * @return 解密得到的字符串
     */
    public static String decrypt(String key, String data) throws Exception {
        try {
            byte[] encrypted1 = Base64.decode(data.getBytes(), Base64.DEFAULT);
            Cipher cipher = Cipher.getInstance(CipherMode);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, keyspec, new IvParameterSpec(
                    new byte[cipher.getBlockSize()]));
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}

方法二

import android.util.Log;

import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class AESUtil {


//    private static final String CipherMode = "AES/ECB/PKCS5Padding";使用ECB加密,不需要设置IV,但是不安全
    private static final String CipherMode = "AES/CFB/NoPadding";//使用CFB加密,需要设置IV

    // /** 创建密钥 **/
    private static SecretKeySpec createKey(String password) {
        byte[] data = null;
        if (password == null) {
            password = "";
        }
        StringBuilder sb = new StringBuilder(32);
        sb.append(password);
        while (sb.length() < 32) {
            sb.append("0");
        }
        if (sb.length() > 32) {
            sb.setLength(32);
        }

        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new SecretKeySpec(data, "AES");
    }

    // /** 加密字节数据 **/
    private static byte[] encrypt(byte[] content, String password) {
        try {
            SecretKeySpec key = createKey(password);
            System.out.println(key);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(
                    new byte[cipher.getBlockSize()]));
            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // /** 加密(结果为16进制字符串) **/
    public static String encrypt(String password,String content ) {
        Log.d("加密前","seed="+password+"\ncontent="+content);
        byte[] data = null;
        try {
            data = content.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = encrypt(data, password);
        String result = byte2hex(data);
        Log.d("加密后","result="+result);
        return result;
    }

    // /** 解密字节数组 **/
    private static byte[] decrypt(byte[] content, String password) {

        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(
                    new byte[cipher.getBlockSize()]));

            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // /** 解密16进制的字符串为字符串 **/
    public static String decrypt(String password,String content) {
        Log.d("解密前","seed="+password+"\ncontent="+content);
        byte[] data = null;
        try {
            data = hex2byte(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = decrypt(data, password);
        if (data == null)
            return null;
        String result = null;
        try {
            result = new String(data, "UTF-8");
            Log.d("解密后","result="+result);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    // /** 字节数组转成16进制字符串 **/
    private static String byte2hex(byte[] b) { // 一个字节的数,
        StringBuilder sb = new StringBuilder(b.length * 2);
        String tmp = "";
        for (byte aB : b) {
            // 整数转成十六进制表示
            tmp = (Integer.toHexString(aB & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); // 转成大写
    }

    // /** 将hex字符串转换成字节数组 **/
    private static byte[] hex2byte(String inputString) {
        if (inputString == null || inputString.length() < 2) {
            return new byte[0];
        }
        inputString = inputString.toLowerCase();
        int l = inputString.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            String tmp = inputString.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }
}

以上代码皆为在其他博客收集整理,但出处已经忘了,如果有不当之处请联系我!

Java中可以使用javax.crypto包中的类来进行AES加密解密。具体实现步骤如下: 1. 生成一个AES密钥 ``` KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(128); SecretKey key = keygen.generateKey(); ``` 2. 创建Cipher对象,并初始化为加密模式或解密模式 ``` Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); ``` 3. 加密/解密数据 ``` byte[] ciphertext = cipher.doFinal(plaintext); byte[] plaintext = cipher.doFinal(ciphertext); ``` 完整代码示例: ``` import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class AESUtil { private static final String CHARSET_NAME = "UTF-8"; private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding"; /** * 随机生成AES密钥 * * @param keySize 密钥长度,单位:位 * @return 生成的密钥 * @throws NoSuchAlgorithmException 异常 */ public static byte[] generateKey(int keySize) throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(keySize); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } /** * AES加密 * * @param plaintext 明文 * @param key 密钥 * @param iv 初始化向量 * @return 密文 * @throws NoSuchPaddingException 异常 * @throws NoSuchAlgorithmException 异常 * @throws InvalidAlgorithmParameterException 异常 * @throws InvalidKeyException 异常 * @throws BadPaddingException 异常 * @throws IllegalBlockSizeException 异常 */ public static byte[] encrypt(byte[] plaintext, byte[] key, byte[] iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(iv)); return cipher.doFinal(plaintext); } /** * AES解密 * * @param ciphertext 密文 * @param key 密钥 * @param iv 初始化向量 * @return 明文 * @throws NoSuchPaddingException 异常 * @throws NoSuchAlgorithmException 异常 * @throws InvalidAlgorithmParameterException 异常 * @throws InvalidKeyException 异常 * @throws BadPaddingException 异常 * @throws IllegalBlockSizeException 异常 */ public static byte[] decrypt(byte[] ciphertext, byte[] key, byte[] iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(iv)); return cipher.doFinal(ciphertext); } /** * 生成随机的初始化向量 * * @param ivSize 初始化向量长度,单位:位 * @return 生成的初始化向量 */ public static byte[] generateIv(int ivSize) { byte[] iv = new byte[ivSize / 8]; new SecureRandom().nextBytes(iv); return iv; } /** * 将字节数组转换为十六进制字符串 * * @param bytes 字节数组 * @return 十六进制字符串 */ public static String toHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 2); for (byte b : bytes) { sb.append(String.format("%02x", b & 0xff)); } return sb.toString(); } /** * 将十六进制字符串转换为字节数组 * * @param hexString 十六进制字符串 * @return 字节数组 */ public static byte[] toByteArray(String hexString) { int len = hexString.length() / 2; byte[] bytes = new byte[len]; for (int i = 0; i < len; i++) { int index = i * 2; bytes[i] = (byte) Integer.parseInt(hexString.substring(index, index + 2), 16); } return bytes; } public static void main(String[] args) throws Exception { // 随机生成16字节的AES密钥和16字节的初始化向量 byte[] key = generateKey(128); byte[] iv = generateIv(128); String plaintextStr = "hello, AES!"; byte[] plaintext = plaintextStr.getBytes(CHARSET_NAME); // AES加密 byte[] ciphertext = encrypt(plaintext, key, iv); String ciphertextHex = toHexString(ciphertext); System.out.println("密文:" + ciphertextHex); // AES解密 byte[] ciphertextBytes = toByteArray(ciphertextHex); byte[] decrypted = decrypt(ciphertextBytes, key, iv); String decryptedStr = new String(decrypted, CHARSET_NAME); System.out.println("明文:" + decryptedStr); } } 相关问题:
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值