系统相关
首页 > 系统相关> > Android native 开发 怎么对aes 加解密?

Android native 开发 怎么对aes 加解密?

作者:互联网

在 Android 原生开发中,可以使用 javax.crypto 包来进行 AES 加密和解密。以下是一个简单的示例:

1. 添加依赖

确保你的项目中包含了 javax.crypto 包,这是 Android SDK 自带的,无需额外添加。

2. AES 加密与解密示例

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    // 生成密钥
    public static byte[] generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256); // AES-256
        SecretKey secretKey = keyGen.generateKey();
        return secretKey.getEncoded();
    }

    // 加密
    public static byte[] encrypt(byte[] key, byte[] data) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        return cipher.doFinal(data);
    }

    // 解密
    public static byte[] decrypt(byte[] key, byte[] encryptedData) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return cipher.doFinal(encryptedData);
    }

    public static void main(String[] args) {
        try {
            String plainText = "Hello, World!";
            byte[] key = generateKey();
            byte[] encryptedData = encrypt(key, plainText.getBytes());
            byte[] decryptedData = decrypt(key, encryptedData);

            System.out.println("Original text: " + plainText);
            System.out.println("Encrypted text: " + new String(encryptedData));
            System.out.println("Decrypted text: " + new String(decryptedData));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Java

3. 注意事项

标签:
来源: